From 54d12e4d46ee0553dae5a0f52ad1d469e09a598a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Sommer?= Date: Thu, 9 Mar 2017 14:54:20 +0100 Subject: [PATCH] =?UTF-8?q?2017-03-07:=20J=C3=B6rgs=20L=C3=B6sung=20f?= =?UTF-8?q?=C3=BCr=20Euler=2037?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 2017-03-07/jo-so_euler37.js | 72 +++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100755 2017-03-07/jo-so_euler37.js diff --git a/2017-03-07/jo-so_euler37.js b/2017-03-07/jo-so_euler37.js new file mode 100755 index 0000000..c99df18 --- /dev/null +++ b/2017-03-07/jo-so_euler37.js @@ -0,0 +1,72 @@ +#!/usr/bin/js +/* + Copyright © 2017 Jörg Sommer + + License: MIT https://opensource.org/licenses/MIT + */ + +'use strict'; + +////// +// +// Some monkey patching +// +if (typeof putstr === 'undefined') + // in case of node.js + var putstr = process.stdout.write.bind(process.stdout); + +if (typeof print === 'undefined') + // in case of node.js + var print = console.log.bind(console); + +////// +// +// Solution of Euler 37 https://projecteuler.net/problem=37 +// +let primeNumbers = new Set([2,3,5,7,11,13,17,19]); + +function nextPrimeNumAfter(number) { + while (true) { + number += 2; + for (var i = Math.floor(Math.sqrt(number)); i >= 3; --i) { + if (number % i == 0) + break; + } + if (i < 3) + return number; + } +} + +function allSubnumsArePrime(num) { + let rightSide = num % 10; + let leftSide = Math.floor(num / 10); + let factor = 1; + while (leftSide > 0) { + if (!(primeNumbers.has(leftSide) && primeNumbers.has(rightSide))) + return false; + + factor *= 10; + rightSide += (leftSide % 10) * factor; + leftSide = Math.floor(leftSide / 10); + } + + return true; +} + +let sum = 0; +let num = 19; + +for (let numCnt = 0; numCnt < 11; ) { + num = nextPrimeNumAfter(num); + + primeNumbers.add(num); + + putstr('\rChecking ' + num); + if (allSubnumsArePrime(num)) { + print('\r' + num + ' '); + sum += num; + ++numCnt; + } +} + +print('Answer: ' + sum);