Check if one integer is an integer power of another

后端 未结 13 1540
臣服心动
臣服心动 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 for the exponent in O(log N) steps:

    #define MAX_POWERS 100
    
    int is_power(unsigned long x, unsigned long y) {
      int i;
      unsigned long powers[MAX_POWERS];
      unsigned long last;
      last = powers[0] = y;
    
      for (i = 1; last < x; i++) {
        last *= last; // note that last * last can overflow here!
        powers[i] = last;
      }
      while (x >= y) {
        unsigned long top = powers[--i];
        if (x >= top) {
          unsigned long x1 = x / top;
          if (x1 * top != x) return 0;
          x = x1;
        }
      }
      return (x == 1);
    }
    

    Negative numbers are not handled by this code, but it can be done easyly with some conditional code when i = 1

提交回复
热议问题