Check if one integer is an integer power of another

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

    If you have access to the largest power of y, that can be fitted inside the required datatype, this is a really slick way of solving this problem.

    Lets say, for our case, y == 3. So, we would need to check if x is a power of 3.

    Given that we need to check if an integer x is a power of 3, let us start thinking about this problem in terms of what information is already at hand.

    1162261467 is the largest power of 3 that can fit into an Java int.
    1162261467 = 3^19 + 0

    The given x can be expressed as [(a power of 3) + (some n)]. I think it is fairly elementary to be able to prove that if n is 0(which happens iff x is a power of 3), 1162261467 % x = 0.

    So, to check if a given integer x is a power of three, check if x > 0 && 1162261467 % x == 0.

    Generalizing. To check if a given integer x is a power of a given integer y, check if x > 0 && Y % x == 0: Y is the largest power of y that can fit into an integer datatype.

    The general idea is that if A is some power of Y, A can be expressed as B/Ya, where a is some integer and A < B. It follows the exact same principle for A > B. The A = B case is elementary.

提交回复
热议问题