Skip to content

Instantly share code, notes, and snippets.

@booknara
Created April 21, 2016 22:49
Show Gist options
  • Save booknara/7fbda95a46d26082649b532e27599e9a to your computer and use it in GitHub Desktop.
Save booknara/7fbda95a46d26082649b532e27599e9a to your computer and use it in GitHub Desktop.
Checking the number of Power N
/**
* Created by Daehee Han(@daniel_booknara) on 4/21/16.
*/
public class PowerN {
public static void main(String[] args) {
int base = 3;
for (int i = 1; i < 100; i++) {
if (isPowerN(base, i))
System.out.println(i + " is power of " + base);
else
System.out.println(i + " is NOT power of " + base);
}
}
public static boolean isPowerN(int n, int value) {
double result = logNAndValue(n, value);
return isInteger(result);
}
public static boolean isInteger(double value) {
return Math.floor(value) == value;
}
/**
* Note : If the base is odd, it returns incorrect value.
* For instance, 243 is power of 3, but return value is 4.99999999999.
*
* @param base
* @param value
* @return
*/
public static double logNAndValue(int base, int value) {
return Math.log(value) / Math.log(base);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment