Check if one integer is an integer power of another

后端 未结 13 1538
臣服心动
臣服心动 2020-11-27 05:15

This is an interview question: \"Given 2 integers x and y, check if x is an integer power of y\" (e.g. for x = 8 and y = 2 the answer is \"true\", and for x = 10 and y = 2 \

13条回答
  •  醉梦人生
    2020-11-27 05:49

    This looks to be pretty fast for positive numbers as it finds the lower and upper limits for desired power and then applies binary search.

    #include 
    #include 
    using namespace std;
    
    //x is the dividend, y the divisor.
    bool isIntegerPower(int x, int y)
    {
        int low = 0, high;
        int exp = 1;
        int val = y;
        //Loop by changing exponent in the powers of 2 and
        //Find out low and high exponents between which the required exponent lies.
        while(1)
        {
            val = pow((double)y, exp);
            if(val == x)
                return true;
            else if(val > x)
                break;
            low = exp;
            exp = exp * 2;
            high = exp;
        }
        //Use binary search to find out the actual integer exponent if exists
        //Otherwise, return false as no integer power.
        int mid = (low + high)/2;
        while(low < high)
        {
            val = pow((double)y, mid);
            if(val > x)
            {
                high = mid-1;
            }
            else if(val == x)
            {
                return true;
            }
            else if(val < x)
            {
                low = mid+1;
            }
            mid = (low + high)/2;
        }
        return false;
    }
    
    int main()
    {
        cout<

提交回复
热议问题