我编写了一个布尔函数来识别整数 m 是否为 n 的幂。但我的代码无法正常运行。例如,625是5的幂。但我的代码结果是错误的。
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("m: ");
int m = reader.nextInt();
Scanner reader2 = new Scanner(System.in);
System.out.print("n: ");
int n = reader2.nextInt();
System.out.println(power(m, n));
}
public static boolean power(int m, int n) {
if (m <= n) {
return false;
}
int pow = n;
while (pow <= m) {
pow = n * pow;
if (pow == m) {
return true;
}
pow++;
}
return false;
}
试试这个:
/* Returns true if y is a power of x */
public static boolean isPower(int x, int y)
{
// The only power of 1 is 1 itself
if (x == 1)
return (y == 1);
// Repeatedly compute power of x
int pow = 1;
while (pow < y)
pow = pow * x;
// Check if power of x becomes y
return (pow == y);
}