Check if one integer is an integer power of another

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

    You'd do better to repeatedly divide y into x. The first time you get a non-zero remainder you know x is not an integer power of y.

    while (x%y == 0)  x = x / y
    return x == 1
    

    This deals with your odd/even point on the first iteration.

提交回复
热议问题