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.