2.1 KiB
2.1 KiB
id | challengeType | title |
---|---|---|
5900f39a1000cf542c50fead | 5 | Problem 46: Goldbach's other conjecture |
Description
Instructions
Tests
tests:
- text: <code>goldbachsOtherConjecture()</code> should return 5777.
testString: assert.strictEqual(goldbachsOtherConjecture(), 5777, '<code>goldbachsOtherConjecture()</code> should return 5777.');
Challenge Seed
function goldbachsOtherConjecture() {
// Good luck!
return true;
}
goldbachsOtherConjecture();
Solution
function goldbachsOtherConjecture() { function isPrime(num) {
if (num < 2) {
return false;
} else if (num === 2) {
return true;
}
const sqrtOfNum = Math.floor(num ** 0.5);
for (let i = 2; i <= sqrtOfNum + 1; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
function isSquare(num) {
return Math.sqrt(num) % 1 === 0;
}
// construct a list of prime numbers
const primes = [];
for (let i = 2; primes.length < 1000; i++) {
if (isPrime(i)) primes.push(i);
}
let num = 3;
let answer;
while (!answer) {
num += 2;
if (!isPrime(num)) {
let found = false;
for (let primeI = 0; primeI < primes.length && !found; primeI++) {
const square = (num - primes[primeI]) / 2;
if (isSquare(square)) {
found = true;
break;
}
}
if (!found) answer = num;
}
}
return answer;
}