Computer >> Computer tutorials >  >> Programming >> Javascript

Representing number as the power and product of primes in JavaScript


Problem

We are required to write a JavaScript function that takes in a positive integer. Our function should represent this number as the sum of some powers of prime numbers.

Therefore, for the number n, our function should return a string like this −

n = "(p1**n1)(p2**n2)...(pk**nk)"

Where p1, p2, p3..pk are prime numbers and n1, n2,..nk are their non-negative powers and a ** b stands for a raised to the power b.

Example

Following is the code −

const isPrime = num => {
    for(let i = 2; i < num; i++){
        if(num % i === 0){
            return false;
        }
    };
    return num > 1;
}
const count = (arr = [], n = 1) => {
for(const k in arr){
    if(n % k === 0){
         arr[k] += 1;
         return count(arr, n / k)
      }
   };
       
   return arr;
};
const primeFactors = (n) => {
    const res = [];
    for(let i = 2; i < n; i++){
        if(isPrime(i)){
            res.push(i);
        }
    };
  const arr = [];
    for(const el in res){
        arr[el] = 0;
    };
    count(arr,n);
    let str = '';
    for(const x in arr){
  if(arr[x] > 1){
         str += '(%s**%s)' %(x,arr[x])
      }else if(arr[x] === 1){
          str += '(%s)' % (x)
      };
  };
   return str
};
console.log(primeFactors(86240));

Output

(2**5)(5)(7**2)(11)