ikselven's solution for Project Euler problem 37 and 87

This commit is contained in:
ikselven 2017-03-17 08:35:24 +01:00
parent 416b24f900
commit 6987013290
2 changed files with 115 additions and 0 deletions

69
2017-03-07/ikselven_euler37.js Executable file
View file

@ -0,0 +1,69 @@
#!/usr/bin/js24
function isPrime(num) {
if (num === 3) {
return true;
}
if (num % 2 === 0) {
return false;
}
for (let i = 3; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
function findNextPrime(num) {
while(!isPrime(++num)) {
}
return num;
}
function rightTruncatable(num, pset) {
while (num > 9) {
num = Math.floor(num/10);
if (!pset.has(num)){
return false;
}
}
return true;
}
function leftTruncatable(num, pset) {
while (num > 9) {
exp = Math.pow(10, Math.floor(Math.log(num) / Math.log(10)));
num -= Math.floor(num / exp) * exp;
if (!pset.has(num)) {
return false;
}
}
return true;
}
let num = 7;
let pset = new Set([2,3,5,7]);
let tset = new Set();
while(tset.size < 11) {
num = findNextPrime(num);
putstr('\rChecking '+num);
pset.add(num);
if (rightTruncatable(num, pset) && leftTruncatable(num, pset)) {
tset.add(num);
print('\r'+num+' ');
}
}
print("Found 11 numbers, summing up.");
let sum = 0;
for (let number of tset) {
print(number);
sum += number;
}
print(sum);

46
2017-03-14/ikselven_euler87.js Executable file
View file

@ -0,0 +1,46 @@
#!/usr/bin/js24
function isPrime(num) {
if (num === 3) {
return true;
}
if (num % 2 === 0) {
return false;
}
for (let i = 3; i <= Math.sqrt(num); i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
const MAX = 5e7;
let primes = [2, 3, 5, 7];
for(let i=10; i<Math.sqrt(MAX); i++) {
if (isPrime(i)) {
primes.push(i);
}
}
print("found "+primes.length+" prime numbers");
let sumSet = new Set();
for(let index4=0; index4 < primes.length; index4++) {
let fourth = primes[index4] * primes[index4] * primes[index4] * primes[index4];
for(let index3=0; index3 < primes.length; index3++) {
let cube = primes[index3] * primes[index3] * primes[index3];
for(let index2=0; index2 < primes.length; index2++) {
let sum = fourth + cube + primes[index2] * primes[index2];
if (sum >= MAX) {
break;
}
sumSet.add(sum);
}
}
}
print("found "+sumSet.size+" numbers");