Home > Java > 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?

王林
Release: 2024-02-22 13:20:14
forward
892 people have browsed it

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;
}
Copy after login

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);
}
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template