How to write a function in Java to check if a number is a power of another number?
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

