Sum of all the multiples of 3 or 5 below 1000 gives a wrong answer in C

前端 未结 7 1728
失恋的感觉
失恋的感觉 2020-12-22 05:27

Project Euler problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9

7条回答
  •  执念已碎
    2020-12-22 06:15

    For the fun of it, I decided on giving the problem some additional constraints.

    • The loop iterator can not take values that aren't a multiple
    • The numbers must be added to the sum in numerical order.

    int sum_multiples(long int m1,long int m2,long int lim)
    {
        long int sum=0;
        for(long int i=m1;i((i+m2)/m2)*m2?((i+m2)/m2)*m2:((i+m1)/m1)*m1) sum+=i;
        return sum;
    }
    int  main(int argc, char *argv[])
    {
        printf("Total: %ld \n",sum_multiples(3,5,1000));
        return 0;
    }
    

提交回复
热议问题