fix(curriculum): Problem 47 - Added optimized solution
This commit is contained in:
@ -53,58 +53,55 @@ 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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return num !== 1;
|
// Adding other factors
|
||||||
}
|
for (let i = 3; i < Math.sqrt(n); i += 2) {
|
||||||
|
firstFactor = true;
|
||||||
function getPrimeFactors(num) {
|
while (n % i == 0) {
|
||||||
const factors = [];
|
n = n / i;
|
||||||
for (let i = 2; i <= Math.sqrt(num); i++) {
|
if (firstFactor) {
|
||||||
if (num % i === 0) {
|
factors++;
|
||||||
// found a factor
|
firstFactor = false;
|
||||||
if (isPrime(i)) {
|
|
||||||
factors.push(i);
|
|
||||||
}
|
|
||||||
if (isPrime(num / i) && i !== Math.sqrt(num)) {
|
|
||||||
factors.push(num / i);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (n > 1) { factors++; }
|
||||||
|
|
||||||
return factors;
|
return factors;
|
||||||
}
|
}
|
||||||
|
|
||||||
function findConsecutiveNumbers() {
|
let number = 0;
|
||||||
let number = 0;
|
let consecutive = 0;
|
||||||
let consecutive = 0;
|
|
||||||
while (consecutive < targetConsecutive) {
|
|
||||||
number++;
|
|
||||||
if (getPrimeFactors(number).length >= targetNumPrimes) {
|
|
||||||
consecutive++;
|
|
||||||
} else {
|
|
||||||
consecutive = 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return (number - targetConsecutive) + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
return findConsecutiveNumbers();
|
while (consecutive < targetConsecutive) {
|
||||||
|
number++;
|
||||||
|
if (numberOfPrimeFactors(number) >= targetNumPrimes) {
|
||||||
|
consecutive++;
|
||||||
|
} else {
|
||||||
|
consecutive = 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
return number - targetConsecutive + 1;
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
</section>
|
</section>
|
||||||
|
Reference in New Issue
Block a user