Created
August 5, 2014 08:57
-
-
Save P1xt/09e15ca3052f67c712b2 to your computer and use it in GitHub Desktop.
Prime Palindrome
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var highEnd = 1000; | |
var primes = sieve(highEnd); | |
highEnd--; | |
var found = false; | |
while (found == false ) { | |
if (isPalindrome(highEnd.toString()) == true) { | |
if (primes[highEnd] == true) { | |
found = true; | |
} | |
} | |
highEnd--; | |
} | |
console.log(++highEnd); | |
function isPalindrome(input) { | |
var i; | |
var length = input.length -1; | |
for (i=0; i< length; i++) { | |
if (input[i] != input[length-i]) { | |
return false; | |
} | |
} | |
return true; | |
} | |
function sieve (highEnd) { | |
var sieve = newFilledArray(highEnd, true); | |
var maxCheck = Math.sqrt(highEnd); | |
var i, j; | |
var results = []; | |
for (i = 2; i <= maxCheck; i++) { | |
if (sieve[i] == true) { | |
for (j = i * i; j < highEnd; j += i) { | |
sieve[j] = false | |
} | |
} | |
} | |
for (i=2; i<highEnd; i++) { | |
if (sieve[i]==true) { | |
results.push(i); | |
} | |
} | |
return(sieve); | |
} | |
function newFilledArray(length, val) { | |
var array = []; | |
for (var i = 0; i < length; i++) { | |
array[i] = val; | |
} | |
return array; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// first create a sieve containing all the prime numbers between | |
// 1 and 1000 | |
$highEnd = 1000; | |
$maxCheck = sqrt($highEnd); | |
$sieve = array_fill(0,1000, true); | |
for ($i = 2; $i<= $maxCheck; $i++) { | |
if ($sieve[$i] == true) { | |
for ($j = $i * $i; $j < $highEnd; $j += $i) { | |
$sieve[$j] = false; | |
} | |
} | |
} | |
// filter out all the non-primes | |
//$sieve = array_filter($sieve); | |
// starting at the largest prime in the sample | |
// loop backward until a palindrome is encountered | |
do { | |
end($sieve); | |
$key = (string) key($sieve); | |
$value = array_pop($sieve); | |
$length = strlen($key) -1; | |
$found = false; | |
if ($value) { | |
$found = true; | |
for ($i=0; $i< $length; $i++) { | |
if ($key[$i] != $key[$length-$i]) { | |
$found = false; | |
} | |
} | |
} | |
} while (! $found); | |
echo $key; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment