0

I'm trying to determine if a give integer n is a power of three. My approach is to take the base 3 log of n and check if there's anything after the decimal point of the result:

int n = 243; double result = Math.Log(n, 3); Console.WriteLine(result); if (result % 1 == 0) { return true; } return false; 

Here's the output of the program when I run the above code:

5 False 

I tried doing this another way:

 double result = Math.Log(n, 3); Console.WriteLine(result); Console.WriteLine((int)result); double remainder = result - (int)result; Console.WriteLine(remainder); if (remainder == 0) { return true; } return false; 

With n = 243 I get:

5 4 0.999999999999999 False 

Note that with n=27 True is returned as expected. What's going on here? I'm expecting True to be returned when n us 243.

4
  • 1
    Possible duplicate of Is floating point math broken? Commented Oct 14, 2019 at 20:45
  • 1
    Are you querying why 5 - 4 is 0.9999? Standard inability of double to represent certain integers - stackoverflow.com/questions/12165216/… Commented Oct 14, 2019 at 20:47
  • 1
    Also see stackoverflow.com/q/4429044/11683. Commented Oct 14, 2019 at 20:47
  • 1
    Once you have the approximate radix 3 log, round to an integer, raise 3 to that power in exact integer arithmetic, and see if it matches. Commented Oct 15, 2019 at 0:29

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.