Reputation: 13
How to check which number is a power in this array?
arr = [16, 32, 72, 96]
output: [16, 32]
because 16 = 4^2
and 32 = 2^5
It's not a solution about power of 2, it's about power of n.
This is my actual code :
let array1 = [16, 32, 72];
function findPowofNum(array1) {
// var result = [];
if (array1.length == 1)
return true;
for(let i = 2; i * i <= array1.length; i++) {
let value = Math.log(array1/length) / Math.log(i);
if((value - Math.floor(value)) < 0.00000001)
return true;
}
return false;
}
console.log(findPowofNum(array1));
Can you give me a example for this solution by javascript?
Upvotes: 0
Views: 647
Reputation: 42010
This will return true if at least one element y of the array is equal to basepower, where base and power are integers.
The basic idea is to simply try each possible base, compute the value of power needed to make basepower equal to the value, and check to see if power is very close to an integer.
This code only works for positive values, and probably won't work for for value in the upper range near Number.MAX_SAFE_INTEGER, though I really haven't tested it.
let array1 = [7, 13, 72, 27];
function isPowOfNum(val) {
// smallest base is 2, largest is sqrt(val)
for (let base=2; base <= Math.sqrt(val); base++) {
// if val = base ** x then log(val) = x * log(base), x = log(val) / log(base)
// and x is an integer
let power = Math.log(val) / Math.log(base);
if (Math.abs(power - Math.round(power)) < 0.000001) {
return true;
}
}
return false;
}
function findPowofNum(array1) {
if (array1.length === 1)
return true;
return array1.some(isPowOfNum);
}
console.log(findPowofNum(array1));
Upvotes: -1
Reputation: 11
const numbers = [16, 32, 72, 96];
const power = numbers.filter(isPowerOfTwo);
function isPowerOfTwo(n)
{
if (n == 0)
return 0;
while (n != 1)
{
if (n%2 != 0)
return 0;
n = n/2;
}
return 1;
}
console.log(power);
To know more about this visit
visit: https://www.geeksforgeeks.org/program-to-find-whether-a-given-number-is-power-of-2/
Upvotes: 1
Reputation:
You can use a custom boolean function to iterate through the elements and append to an empty array as you check like this..
function isPowerofTwo(n){
return (Math.ceil((Math.log(n) / Math.log(2))))
== (Math.floor(((Math.log(n) / Math.log(2)))));
}
let arr= [16, 32, 72, 96];
let values=[]
for(let i=0;i<arr.length;i++){
if(isPowerofTwo(arr[i])){
values.push(arr[i]);
}
}
console.log(values);
Upvotes: 1
Reputation: 1
I think it is 2^4 not 4^2 and what I believe is you want to check if the number is and root of 2 or not Solution
let arr=[16,32,72,96];
let i=1;
for(i=1;i<=10;i++){ // this loop will run up to 2^10
let k=Math.pow(2,i);if(k==arr[i-1]){
//do whatever you want to do with the number
}
}
Upvotes: -1
Reputation: 2652
How about
arr = [16, 32, 72, 96].filter(
value => Number.isInteger(Math.log2(value))
)
Upvotes: 1