Finding the k-prime numbers with a specific distance in a range in JavaScript


K-Prime Numbers

A natural number is called k-prime if it has exactly k prime factors, counted with multiplicity.

Which means even though the only prime factor of 4 is 2 it will be a 2-prime number because −

4 = 2 * 2 and both 2s will be counted separately taking the count to 2.

Similarly, 8 is 3-prime because 8 = 2 * 2 * 2 taking the count to 3.

Problem

We are required to write a JavaScript function that takes in a number k, a distance and a range.

Our function should return an array of arrays containing k-prime numbers within the range the distance between whom is exactly equal to the distance specified.

Example

Following is the code −

 Live Demo

const k = 2;
const step = 2;
const range = [0, 50];
const kPrimeSteps = (k = 1, step = 1, [start, end]) => {
   const res = [];
   let i = start;
   const findLen = (n = 1) => {
      let count = 0, i = 2;
      while (i * i <= n) {
         while (n % i === 0) {
            count++;
            n /= i;
         }
         i++;
      }
      if (n > 1) count++;
      return count;
   }
   while (i <= end - step) {
      if ((findLen(i) == k && findLen(i+step) == k))
      res.push([i, i+step]);
      i++;
   }
   return res;
};
console.log(kPrimeSteps(k, step, range));

Output

Following is the console output −

[ [ 4, 6 ], [ 33, 35 ] ]

Updated on: 20-Apr-2021

254 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements