Advertisement
Guest User

Untitled

a guest
Apr 15th, 2018
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Naive sieve in range 1..sqrt(x)
  2. var isPrime = function(x) {
  3.   for (var i = 2, sqr = Math.floor(Math.sqrt(x)); i <= sqr; i++) {
  4.     if (x % i === 0) {
  5.       return false;
  6.     }
  7.   }
  8.   return true;
  9. }
  10.  
  11. // Optimized sieve for numbers in range 1..99999, uses 64 checks at max.
  12. var isPrimeFast = (function() {  
  13.   // Pre-calculate primes in range 1..sqrt(99999)
  14.   var smallPrimes = [];
  15.   for (var i = 2; i < 316; i++) {
  16.     if (isPrime(i)) {
  17.       smallPrimes.push(i);
  18.     }
  19.   }
  20.  
  21.   return function(x) {
  22.     var sqr = Math.floor(Math.sqrt(x));
  23.     for (var i = 0; smallPrimes[i] <= sqr; i++) {
  24.       if (x % smallPrimes[i] === 0) {
  25.         return false;
  26.       }
  27.     }
  28.     return true;
  29.   }
  30. })();
  31.  
  32. var isPalindrome = function(str) {
  33.   for (var i = 0; i < str.length / 2; i++) {
  34.     if (str[i] != str[str.length - i - 1]) {
  35.       return false;
  36.     }
  37.   }
  38.   return true;
  39. }
  40.  
  41. var findMaxPalindromeProductOfPrimes = function() {
  42.   var bigPrimes = [];
  43.  
  44.   // Largest to smallest, find a prime
  45.   for (var a = 99999; a >= 10000; a--) {
  46.     if (!isPrimeFast(a)) {
  47.       continue;
  48.     }
  49.    
  50.     // and check its product with previously found primes,
  51.     // largest to smallest
  52.     bigPrimes.push(a);
  53.     for (var j = 0; j < bigPrimes.length; j++) {
  54.       var b = bigPrimes[j];
  55.       if (isPalindrome('' + (a * b))) {
  56.         // Code enters here when `a` and `b` are the largest possible
  57.         return {
  58.           "value" : a * b,
  59.           "factors" : [a, b]
  60.         }
  61.       }
  62.     }
  63.   }
  64. }
  65.  
  66. console.log(findMaxPalindromeProductOfPrimes());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement