Check if one integer is an integer power of another

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

    On second thoughts, don't do this. It does not work for negative x and/or y. Note that all other log-based answers presented right now are also broken in exactly the same manner.

    The following is a fast general solution (in Java):

    static boolean isPow(int x, int y) {
        int logyx = (int)(Math.log(x) / Math.log(y));
        return pow(y, logyx) == x || pow(y, logyx + 1) == x;
    }
    

    Where pow() is an integer exponentiation function such as the following in Java:

    static int pow(int a, int b) {
        return (int)Math.pow(a, b);
    }
    

    (This works due to the following guarantee provided by Math.pow: "If both arguments are integers, then the result is exactly equal to the mathematical result of raising the first argument to the power of the second argument...")

    The reason to go with logarithms instead of repeated division is performance: while log is slower than division, it is slower by a small fixed multiple. At the same time it does remove the need for a loop and therefore gives you a constant-time algorithm.

提交回复
热议问题