Project Euler Spoilers, #001 - PHP Sums
I cannot ask for help on their forums, but i've been at this for 3 hours now. Spoilers Below I don't understand what i'm doing wrong. The question is:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.
Here's my equation I made.
for($total = 0, $f = 5, $t = 3; $t < 1000; $t+=3){
if($f < 1000)
{
$total += $f + $t;
echo "Five: $f, Three: $t = $total<br />";
$f += 5;
}
开发者_运维技巧 else
{
$total += $t;
echo "Five: $f, Three: $t = $total<br />";
}
}
The answer is:233168. Where's my error?
You are counting numbers that are divisible both by 3 and 5 twice.
Suppose S(3) denotes sum of numbers divisible by 3 and S(5) denotes sum of numbers divisible by 5 till a given number n, then sum of numbers divisible by 3 or 5 is given by
S(3 U 5) = S(3) + S(5) - S(3 ∩ 5) where S(3 ∩ 5) denotes sum of those numbers divisible by both 3 and 5.
In your case, you are calculating S(3 U 5) = S(3) + S(5) and hence getting wrong answer.
精彩评论