"Prime Numbers III"
In math, a prime number is only divisible by 1 and itself
Given the first few primes below:
How many of the primes below 1,000,000 have the sum of their digits equal to the number of days in a fortnight?
OK the real challenge here is calculating the primes up to 1,000,000, once you can do that calculating the sum of the digits of each prime is easy, if it matches the number of days in a fortnight (14) then increment a counter. I recommend googling "Sieve of Eratosthenes"
Awnser:
= 1218
Source:
function solution(){ $solution = 0; $maxprime = 1000000; for ($a = 0; $a <= $maxprime; $a++){ //Set all numbers to 1 $primes[$a] = 1; $primes[0] = 0; $primes[1] = 0;// Do not include 0 and 1 } for ($a = 2; $a * $a < $maxprime; $a++){ // Search for prime numbers if ($primes[$a] == 1){ for ($b = $a * $a; $b <= $maxprime; $b += $a){ $primes[$b] = 0; // Remove the none primes } } } for ($c = 0; $c <= $maxprime; $c++){ if ($primes[$c] == 1){ $primesum = 0; // reset the sum of digits for($i = 0; $i < strlen($c); $i++){ $primetostring = strval($c); $primesum += $primetostring[$i]; } $color = ($primesum == 14 ? 'lightgreen' : 'red'); if($primesum == 14){ $solution++; } // echo "".$c." "; } } echo "= ".$solution.""; }