欧拉计划网站地址: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 }

 

相关文章:

  • 2021-10-30
  • 2021-08-24
  • 2021-09-13
  • 2022-12-23
  • 2021-06-18
  • 2021-05-24
  • 2021-10-09
猜你喜欢
  • 2022-12-23
  • 2021-10-02
  • 2022-12-23
  • 2021-08-08
  • 2022-03-03
  • 2021-11-02
  • 2021-10-05
相关资源
相似解决方案