project euler

I am stumped on a project euler problem #50

The prime 41, can be written as the sum of six consecutive primes:

41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most consecutive primes?

Here is what I have so far it just finds the primes…

$primes = array();
for ($x = 2; $x <= 1000; $x++) {
$xIsPrime = TRUE;
$sqrtX = sqrt($x);
foreach ($primes as $prime) if ($prime > $sqrtX || ((!($x % $prime)) && (!$xIsPrime = FALSE))) break;
if ($xIsPrime) echo ($primes[] = $x) . “
”;

}

What is your question?

Do you want us to solve this for you?

Is this for a school class?

As far as I see it, it is just a simple logic question and process.

First, think your logic a bit differently. Loop more like this… Just the flow of the code, not the code.
You figure out the code…

$goal_prime = 0;

locate the next prime number, call it $new_prime

$saved_prime = $goal_prime; (Need to save it in case the next prime makes the goal a non-prime…
$goal_prime = $goal_prime + $new_prime;

Check $goal_prime if it is a prime number or not by testing against the $primes array.
If it is a prime and is less than one million, loop back to locate the next prime number

If not, the answer is $saved_prime

Hope that logic makes since. This is all based on your prime number system working correctly.
I did not test that. But, if that is correct, the rest should be easy.

Sponsor our Newsletter | Privacy Policy | Terms of Service