fix(curriculum): Problem 47 - Added optimized solution

This commit is contained in:
Aditya
2018-11-11 20:09:45 +05:30
committed by Valeriy
parent dc9b371317
commit aaba2298bf

View File

@ -53,57 +53,54 @@ distinctPrimeFactors(4, 4);
</div> </div>
</section> </section>
## Solution ## Solution
<section id='solution'> <section id='solution'>
```js ```js
function distinctPrimeFactors(targetNumPrimes, targetConsecutive) { function distinctPrimeFactors(targetNumPrimes, targetConsecutive) {
function numberOfPrimeFactors(n) {
let factors = 0;
function isPrime(num) { // Considering 2 as a special case
for (let i = 2, s = Math.sqrt(num); i <= s; i++) { let firstFactor = true;
if (num % i === 0) { while (n % 2 == 0) {
return false; n = n / 2;
if (firstFactor) {
factors++;
firstFactor = false;
}
}
// Adding other factors
for (let i = 3; i < Math.sqrt(n); i += 2) {
firstFactor = true;
while (n % i == 0) {
n = n / i;
if (firstFactor) {
factors++;
firstFactor = false;
} }
} }
return num !== 1;
} }
function getPrimeFactors(num) { if (n > 1) { factors++; }
const factors = [];
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
// found a factor
if (isPrime(i)) {
factors.push(i);
}
if (isPrime(num / i) && i !== Math.sqrt(num)) {
factors.push(num / i);
}
}
}
return factors; return factors;
} }
function findConsecutiveNumbers() {
let number = 0; let number = 0;
let consecutive = 0; let consecutive = 0;
while (consecutive < targetConsecutive) { while (consecutive < targetConsecutive) {
number++; number++;
if (getPrimeFactors(number).length >= targetNumPrimes) { if (numberOfPrimeFactors(number) >= targetNumPrimes) {
consecutive++; consecutive++;
} else { } else {
consecutive = 0; consecutive = 0;
} }
} }
return (number - targetConsecutive) + 1; return number - targetConsecutive + 1;
}
return findConsecutiveNumbers();
} }
``` ```