project euler 第一题

Multiples of 3 and 5

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.

我想出两个解决方案。第一个是遍历,遇到满足条件的数。累加求和。代码如下

int sum = 0;
for(int i=1;i<1000;i++)
{
if( (i%3==0) || (i%5==0) )
{
sum += i;
}
}

第二个是根据题意,

int getSum(int num,int range)
{
int temp = range/num;

int sum = (temp*(temp+1))/2;
return sum*num;

}

 

int sum3 = getSum(3,999);
int sum5 = getSum(5,999);
int sum15 = getSum(15,999);

int sum = sum3 + sum5-sum15;

 

posted @ 2017-04-26 18:32  郭新晨  阅读(129)  评论(0编辑  收藏  举报