Why 243 is so special in C


  • 1
    H

    Dears all,

    I wonder why 243 is so different in my program output, following is my program:

    bool isPowerOfThree(int n) {
    
           double result = log(n)/log(3);
    
           return result == (int)result;
    }
    

    The returned boolean is under expectation when n = 1,3,9,27,81 while failed in 243

    Does anyone know the reason?? Thanks


  • 2
    F

    Becase double/double will loss precision.

    my c++ solution is :

    class Solution {
    public:
        bool isPowerOfThree(int n) {
            if(n <= 0) return false;
            double result = (int)(0.5 + log(n)/log(3));
            return (pow(3, result) == n);
        }
    };

  • 0
    D

    Use log10(x)...not sure why but it works for me


  • 0
    C

    May be you can try the following code

    Int m = result;
    If((result-m)==0)
    return true;
    else
    return false;


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.