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.

Adam
  • 8,752
  • 12
  • 54
  • 96
  • 1
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – GSerg Oct 14 '19 at 20:45
  • 1
    Are you querying why 5 - 4 is 0.9999? Standard inability of double to represent certain integers - https://stackoverflow.com/questions/12165216/which-values-cannot-be-represented-correctly-by-a-double – Caius Jard Oct 14 '19 at 20:47
  • 1
    Also see https://stackoverflow.com/q/4429044/11683. – GSerg Oct 14 '19 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. – Patricia Shanahan Oct 15 '19 at 00:29

0 Answers0