问题描述
我不得不开始学习C的,我做一个项目的一部分。我已经开始做了欧拉在它的问题,我有与。我必须找到低于1000的3或5的倍数的总和可能有人请帮助我。谢谢你。
#包括LT&;&stdio.h中GT;
INT开始;
INT总和;诠释主(){
同时(开始< 1001){
如果(起始%3 == 0){
总和=总和+启动;
启动+ = 1;
}其他{
启动+ = 1;
} 如果(启动%5 == 0){
总和=总和+启动;
启动+ = 1;
}其他{
启动+ = 1;
}
的printf(%d个\\ N,总和);
}
返回(0);
}
您已经得到了一些伟大的答案至今,主要建议是这样的:
的#include<&stdio.h中GT;
INT主(INT ARGC,CHAR *的argv [])
{
INT I;
INT SOLN = 0;
对于(i = 1; I< 1000;我++)
{
如果((I%3 == 0)||(I%5 == 0))
{
SOLN + =我;
}
}
的printf(%d个\\ N,溶液);
返回0;
}
所以我要采取不同的策略。我知道你这样做是为了学习C,所以这可能是一个有点切线。
说真的,你让电脑工作太辛苦了这个:)。如果我们想通一些事情提前出局,它可以使任务更容易。
嘛,怎么的3个多倍数小于1000?还有一个每个3进入1000时间 - 1
(the ⌊ and ⌋ mean that this is floor division, or, in programming terms, integer division, where the remainder is dropped).
And how many multiples of 5 are less than 1000?
Now what is the sum of all the multiples of 3 less than 1000?
And the sum of all the multiples of 5 less than 1000?
Some multiples of 3 are also multiples of 5. Those are the multiples of 15.Since those count towards mult and mult (and therefore sum and sum) we need to know mult and sum to avoid counting them twice.
So the solution to the problem "find the sum of all the multiples of 3 or 5 below 1000" is then
So, if we wanted to, we could implement this directly:
#include <stdio.h>
int main(int argc, char * argv[])
{
int i;
int const mult3 = (1000 - 1) / 3;
int const mult5 = (1000 - 1) / 5;
int const mult15 = (1000 - 1) / 15;
int sum3 = 0;
int sum5 = 0;
int sum15 = 0;
int soln;
for (i = 1; i <= mult3; i++) { sum3 += 3*i; }
for (i = 1; i <= mult5; i++) { sum5 += 5*i; }
for (i = 1; i <= mult15; i++) { sum15 += 15*i; }
soln = sum3 + sum5 - sum15;
printf("%d\n", soln);
return 0;
}
But we can do better. For calculating individual sums, we have Gauss's identity which says the sum from 1 to n (aka ∑ i) is n×(n+1)/2, so:
(Note that we can use normal division or integer division here - it doesn't matter since one of n or n+1 must be divisible by 2)
Now this is kind of neat, since it means we can find the solution without using a loop:
#include <stdio.h>
int main(int argc, char *argv[])
{
int const mult3 = (1000 - 1) / 3;
int const mult5 = (1000 - 1) / 5;
int const mult15 = (1000 - 1) / 15;
int const sum3 = (3 * mult3 * (mult3 + 1)) / 2;
int const sum5 = (5 * mult5 * (mult5 + 1)) / 2;
int const sum15 = (15 * mult15 * (mult15 + 1)) / 2;
int const soln = sum3 + sum5 - sum15;
printf("%d\n", soln);
return 0;
}
Of course, since we've gone this far we could crank out the entire thing by hand:
And write a much simpler program:
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("233168\n");
return 0;
}
这篇关于简单的C问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!