Is Power
Description
Determine if the given number is a power of some non-negative integer.
Example
- For
n = 125, the output should beisPower(n) = true; - For
n = 72, the output should beisPower(n) = false.
Input/Output
-
[execution time limit] 4 seconds (js)
-
[input] integer n
A positive integer.
Guaranteed constraints:
1 ≤ n ≤ 400. -
[output] boolean
trueifncan be represented in the formab(ato the power ofb) whereaandbare some non-negative integers andb ≥ 2, false otherwise.
[JavaScript (ES6)] Syntax Tips
1
2
3
4
5
6
// Prints help message to the console
// Returns a string
function helloWorld(name) {
console.log("This prints to the console when you Run Tests");
return "Hello, " + name;
}
Solution
1
2
3
4
5
6
7
8
9
function isPower(n) {
var i = 2;
while (Math.pow(n, 1 / i) >= 2) {
if (Math.ceil(Math.pow(Math.round(Math.pow(n, 1 / i)), i) == n))
return true;
i++;
}
return n === 1;
}