Home > Net >  Check an number in an array is a powers number
Check an number in an array is a powers number

Time:11-30

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));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Can you give me a example for this solution by javascript?

CodePudding user response:

How about

arr = [16, 32, 72, 96].filter(
    value => Number.isInteger(Math.log2(value))
)

CodePudding user response:

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);

CodePudding user response:

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/

CodePudding user response:

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
}
}
  • Related