简体   繁体   English

欧拉项目剧透,#001 - PHP 总和

[英]Project Euler Spoilers, #001 - PHP Sums

I cannot ask for help on their forums, but i've been at this for 3 hours now.我不能在他们的论坛上寻求帮助,但我已经在这里待了 3 个小时了。 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.如果我们列出所有小于 10 且是 3 或 5 的倍数的自然数,我们会得到 3、5、6 和 9。这些倍数的和是 23。求出 1000 以下的所有 3 或 5 的倍数之和。

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.答案是:233168。 Where's my error?我的错误在哪里?

You are counting numbers that are divisible both by 3 and 5 twice .您正在计算可以被 3 和 5 整除的数字两次

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) 表示可被 3 整除的数之和,S(5) 表示可被 5 整除的数之和直到给定数 n,则可被 3 或 5 整除的数之和由下式给出

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. S(3 U 5) = S(3) + S(5) - S(3 ∩ 5) 其中 S(3 ∩ 5) 表示可被 3 和 5 整除的这些数字的总和。

In your case, you are calculating S(3 U 5) = S(3) + S(5) and hence getting wrong answer.在您的情况下,您正在计算 S(3 U 5) = S(3) + S(5) 并因此得到错误的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM