Created
August 5, 2014 09:00
-
-
Save P1xt/da007c1ec296949f03fc 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
<?php | |
/** | |
* Write a program to determine the biggest prime palindrome under 1000. | |
INPUT SAMPLE: | |
There is no input for this program. | |
OUTPUT SAMPLE: | |
Your program should print the largest palindrome on stdout, i.e. | |
929 | |
* */ | |
// 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