Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Naive sieve in range 1..sqrt(x)
- var isPrime = function(x) {
- for (var i = 2, sqr = Math.floor(Math.sqrt(x)); i <= sqr; i++) {
- if (x % i === 0) {
- return false;
- }
- }
- return true;
- }
- // Optimized sieve for numbers in range 1..99999, uses 64 checks at max.
- var isPrimeFast = (function() {
- // Pre-calculate primes in range 1..sqrt(99999)
- var smallPrimes = [];
- for (var i = 2; i < 316; i++) {
- if (isPrime(i)) {
- smallPrimes.push(i);
- }
- }
- return function(x) {
- var sqr = Math.floor(Math.sqrt(x));
- for (var i = 0; smallPrimes[i] <= sqr; i++) {
- if (x % smallPrimes[i] === 0) {
- return false;
- }
- }
- return true;
- }
- })();
- var isPalindrome = function(str) {
- for (var i = 0; i < str.length / 2; i++) {
- if (str[i] != str[str.length - i - 1]) {
- return false;
- }
- }
- return true;
- }
- var findMaxPalindromeProductOfPrimes = function() {
- var bigPrimes = [];
- // Largest to smallest, find a prime
- for (var a = 99999; a >= 10000; a--) {
- if (!isPrimeFast(a)) {
- continue;
- }
- // and check its product with previously found primes,
- // largest to smallest
- bigPrimes.push(a);
- for (var j = 0; j < bigPrimes.length; j++) {
- var b = bigPrimes[j];
- if (isPalindrome('' + (a * b))) {
- // Code enters here when `a` and `b` are the largest possible
- return {
- "value" : a * b,
- "factors" : [a, b]
- }
- }
- }
- }
- }
- console.log(findMaxPalindromeProductOfPrimes());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement