Home  >  Article  >  How to write a function in Java to check if a number is a power of another number?

How to write a function in Java to check if a number is a power of another number?

王林
王林forward
2024-02-22 13:20:14844browse

php editor Youzi brings you answers to Java programming questions: How to write a function in Java to check whether a number is the power of another number? Writing such a function will help you quickly and accurately determine the multiple relationship between numbers in a Java program, which will facilitate your programming work. In this article, we will explore how to write such a function using Java language and give detailed code implementation and examples. Let’s take a closer look!

Question content

I wrote a boolean function that checks whether the integer m is a power of n. But my code is incorrect. For example, 625 is a power of 5. But my code returns false.

public static boolean isPower(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;
}

Solution

  • A bug in your solution was pointed out in the comments.
  • Your code also doesn't handle the m = 1 case well.
  • For most inputs, the following methods can reduce the number of iterations:
// for n, m > 0
static boolean isPower(int m, int n) {
    while (m % n == 0) {
        m /= n;
    }
    
    return (m == 1);
}

Here I repeatedly divide m by n until I encounter a non-zero remainder. For exact powers of n, I end up with m = 1.

Using this method all possible m values ​​of (n - 1)/n will be rejected on the first iteration because n Only one number among consecutive numbers has m % n == 0.

The above is the detailed content of How to write a function in Java to check if a number is a power of another number?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete