尔冬橙

博客园 首页 新随笔 联系 订阅 管理

 

欧拉计划网站地址:http://projecteuler.net/

第1题 Add all the natural numbers below one thousand that are multiples of 3 or 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.

第一个题目,就像所有语言都有的“Hello World”一样。就是统计一下1000以内,所有是3,或者5倍数的和。

#include <stdio.h>
main()
{
  int i,sum = 0;
  for(i=3;i<1000;i++) 
  {
    if(i%3==0 || i%5==0)
      sum+=i;                    
  }     
  printf("sum=%d",sum);
}

  

 对每一个数都做2次求余运算代价比较高。

 1 #include <stdio.h>
 2 main()
 3 {
 4   int i,sum = 0;
 5   for(i=3;i<1000;i+=3) //加所有3个倍数。 
 6   {
 7     sum += i;                    
 8   }     
 9   for(i=5;i<1000;i+=5)//加所有5个倍数。
10   {
11     sum +=i;                    
12   }
13   for(i=15;i<1000;i+=15) //减去所有3*5的倍数。 
14   {
15     sum-=i;                      
16   }
17   printf("sum=%d",sum);
18 }

 

posted on 2012-05-11 15:25  尔冬橙  阅读(289)  评论(0编辑  收藏  举报