Sum of all the multiples of 3 or 5 below 1000 gives a wrong answer in C

前端 未结 7 1748
失恋的感觉
失恋的感觉 2020-12-22 05:27

Project Euler problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9

7条回答
  •  被撕碎了的回忆
    2020-12-22 06:19

    The answer can be computed with simple arithmetic without any iteration. Many Project Euler questions are intended to make you think about clever ways to find solutions without just using the raw power of computers to chug through calculations.

    Given positive integers N and F, the number of positive multiples of F that are less than N is floor((N-1)/F). (floor(x) is the greatest integer not greater than x.) For example, the number of multiples of 5 less than 1000 is floor(999/5) = floor(199.8) = 199.

    Let n be this number of multiples, floor((N-1)/F).

    The first multiple is F and the last multiple is nF. For example, with 1000 and 5, the first multiple is 5 and the last multiple is 199•5 = 995.

    The multiples are evenly spaced, so the average of all of them equals the average of the first and the last, so it is (F + nF)/2.

    The total of the multiples equals their average multiplied by the number of them, so the total of the multiples of F less than N is n • (F + nF)/2.

    As we have seen in other answers and in comments, adding the sum of multiples of 3 and the sum of multiples of 5 counts the multiples of both 3 and 5 twice. We can correct for this by subtracting the sum of those numbers. Multiples of both 3 and 5 are multiples of 15.

    Thus, we can compute the requested sum using simple arithmetic without any iteration:

    #include 
    
    
    static long SumOfMultiples(long N, long F)
    {
        long NumberOfMultiples = (N-1) / F;
        long FirstMultiple = F;
        long LastMultiple = NumberOfMultiples * F;
    
        return NumberOfMultiples * (FirstMultiple + LastMultiple) / 2;
    }
    
    
    int main(void)
    {
        long N = 1000;
        long Sum = SumOfMultiples(N, 3) + SumOfMultiples(N, 5) - SumOfMultiples(N, 3*5);
    
        printf("%ld\n", Sum);
    }
    

    As you do other Project Euler questions, you should look for similar ideas.

提交回复
热议问题