也来做下欧拉项目练习题: 题目001

本文提供了一个C语言实现的简单算法,用于计算1000以内3或5的所有倍数之和。通过定义函数sum_of_mul并使用for循环遍历指定范围内的整数,如果该整数能被3或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.
*/

#include <stdio.h>
#include <stdlib.h>

#define TEST 1           //编程之前就应该考虑测试(运行时将1改为0)

#if TEST
  #define END_NUM       10       //问题给出的常数  
  #define SUM               23
#else
  #define END_NUM       1000       
#endif

  #define BEGIN_NUM     1       
  #define FAC_1             3
  #define FAC_2             5

int sum_of_mul (const int ,const int ,const int ,const int ) ;

int main( void )
{
   printf ( "the sum of all the multiples"   //太长的string literal
            " of %d or %d below %d " ,      //可以用这种方法“分割”
            FAC_1 , FAC_2 , END_NUM       
           ); 
   printf ( "is  %d.\n",
            sum_of_mul ( BEGIN_NUM , END_NUM , FAC_1 , FAC_2  )
           );

              
 #if TEST
   printf ( "= %d\n", SUM ) ;             
 #else
 #endif
 
   system("PAUSE"); 
   return 0;
}

int sum_of_mul (const int begin ,const int end ,
                        const int fac1  ,const int fac2 )
{
    int sum = 0 ;
    int i ;
    for( i = begin ; i < end ; i ++ )
      {
         if ( i % fac1 == 0 || i % fac2 == 0 )
           {
             sum += i ;  
           } 
      }
    return sum ;
}

参考博文
http://www.cnblogs.com/zhouyinhui/archive/2011/01/05/1926769.html

转载于:https://www.cnblogs.com/KBTiller/archive/2011/03/06/1972414.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值