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

JavascriptWeb DevelopmentFront End Technology

<h2>K-Prime Numbers</h2><p>A natural number is called k-prime if it has exactly k prime factors, counted with multiplicity.</p><p>Which means even though the only prime factor of 4 is 2 it will be a 2-prime number because &minus;</p><p>4 = 2 * 2 and both 2s will be counted separately taking the count to 2.</p><p>Similarly, 8 is 3-prime because 8 = 2 * 2 * 2 taking the count to 3.</p><h2>Problem</h2><p>We are required to write a JavaScript function that takes in a number k, a distance and a range.</p><p>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.</p><h2>Example</h2><p>Following is the code &minus;</p><p><a class="demo" href="" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">const k = 2; const step = 2; const range = [0, 50]; const kPrimeSteps = (k = 1, step = 1, [start, end]) =&gt; { &nbsp; &nbsp;const res = []; &nbsp; &nbsp;let i = start; &nbsp; &nbsp;const findLen = (n = 1) =&gt; { &nbsp; &nbsp; &nbsp; let count = 0, i = 2; &nbsp; &nbsp; &nbsp; while (i * i &lt;= n) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;while (n % i === 0) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; n /= i; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;i++; &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; if (n &gt; 1) count++; &nbsp; &nbsp; &nbsp; return count; &nbsp; &nbsp;} &nbsp; &nbsp;while (i &lt;= end - step) { &nbsp; &nbsp; &nbsp; if ((findLen(i) == k &amp;&amp; findLen(i+step) == k)) &nbsp; &nbsp; &nbsp; res.push([i, i+step]); &nbsp; &nbsp; &nbsp; i++; &nbsp; &nbsp;} &nbsp; &nbsp;return res; }; console.log(kPrimeSteps(k, step, range));</pre><h2>Output</h2><p>Following is the console output &minus;</p><pre class="result notranslate">[ [ 4, 6 ], [ 33, 35 ] ]</pre>
Updated on 20-Apr-2021 06:30:49