Check if one integer is an integer power of another

后端 未结 13 1582
臣服心动
臣服心动 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:46

    I would implement the function like so:

    bool IsWholeNumberPower(int x, int y)
    {
        double power = log(x)/log(y);
        return floor(power) == power;
    }
    

    This shouldn't need check within a delta as is common with floating point comparisons, since we're checking whole numbers.

提交回复
热议问题