Last active
August 29, 2015 14:10
-
-
Save rocketeerbkw/35f0fe35edfed58b9568 to your computer and use it in GitHub Desktop.
Find the sum of all prime numbers between zero and two million and encode the answer
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 -f sum_primes.php | |
Sum: 142913828922 | |
Sum to Hex: | |
31 34 32 39 31 33 38 32 38 39 32 32 | |
Hex to Base64: | |
MzEgMzQgMzIgMzkgMzEgMzMgMzggMzIgMzggMzkgMzIgMzIg | |
$ |
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 | |
/** | |
* @File | |
* Calculate the sum of all primes from 0-2000000. | |
* | |
* Special thanks to my reddit secret santa! | |
*/ | |
// Cheat by downloading a list of pre-generated primes. | |
$filename = 'primes1.zip'; | |
if (!file_exists($filename)) { | |
$primes_zip = file_get_contents('http://primes.utm.edu/lists/small/millions/primes1.zip'); | |
file_put_contents($filename, $primes_zip); | |
} | |
$primes_data = file_get_contents('zip://' . $filename . '#primes1.txt'); | |
$primes = []; | |
preg_match_all('/\s(\d+)\s/', $primes_data, $primes); | |
// Add! | |
$sum = 0; | |
$prime = 0; | |
foreach ($primes[1] as $prime) { | |
// Stop at 2000000 | |
if ($prime > 2000000) { | |
break; | |
} | |
$sum += $prime; | |
} | |
echo 'Sum: ' . $sum . PHP_EOL . PHP_EOL; | |
// Convert the answer to Hex | |
$answer_hex = ''; | |
foreach (str_split($sum) as $char) { | |
$dec = ord($char); | |
$hex = dechex($dec); | |
$answer_hex .= str_pad($hex, 2, 0, STR_PAD_LEFT) . ' '; | |
} | |
echo 'Sum to Hex: ' . PHP_EOL . $answer_hex . PHP_EOL . PHP_EOL; | |
echo 'Hex to Base64: ' . PHP_EOL . base64_encode($answer_hex) . PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment