Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

c - Find the sum of all the multiples of 3 or 5 below 1000

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. I have the following code but the answer does not match.

#include<stdio.h>
int main()
{
    long unsigned int i,sum=0;
    clrscr();
    for(i=0;i<=1000;i++)
    {
        if((i%5==0)||(i%3==0))
        {
            sum=sum+1;
        }
    }
    printf("%d
",sum);
    getchar();
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rather than using range/loop based solutions you may wish to leverage more math than brute force.

There is a simple way to get the sum of multiples of a number, less than a number.

For instance, the sum of multiples of 3 up to 1000 are: 3 + 6 + 9 + ... + 999 Which can be rewritten as: 3* ( 1 + 2 + 3 + ... + 333)

There is a simple way to sum up all numbers 1-N:

Sum(1,N) = N*(N+1)/2

So a sample function would be

unsigned int unitSum(unsigned int n)
{
    return (n*(n+1))/2;
}

So now getting all multiples of 3 less than 1000 (aka up to and including 999) has been reduced to:

3*unitSum((int)(999/3))

You can do the same for multiples of 5:

5*unitSum((int)(999/5))

But there is a caveat! Both of these count multiples of both such as 15, 30, etc It counts them twice, one for each. So in order to balance that out, you subtract once.

15*unitSum((int)(999/15))

So in total, the equation is:

sum = 3*unitSum((int)(999/3)) + 5*unitSum((int)(999/5)) - 15*unitSum((int)(999/15))

So now rather than looping over a large set of numbers, and doing comparisons, you are just doing some simple multiplication!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...