I tried to come up with a simple C++ program to do it. I tested it first with a small number like 10 so the sum of all multiples of 3 or 5 bellow ten is 23.
The below Code gets just that, but when I extend it to do it for 1000 apparently judging by the answer given there, it is incorrect.
usingnamespace std;
int x,y,sum=0;
int _tmain(int argc, _TCHAR* argv[])
{
for (int i = 3; i < 1000; i += 3){
x+=i;
}
for (int i = 5; i < 1000; i += 5){
y+=i;
}
sum=x+y;
cout<<sum<<endl;
return 0;
}
I can't see anything wrong with your code
Try making x,y & sum type long
Ans: 166833 and 99500 ?
Note: There is an or b/n 3 & 5 in the problem description
I want to illustrate how using math can reduce programming and increase efficency (sometimes by a huge factor) in practical situations. This question can be done without a loop.
(Recall: sum of 1st n numbers is n(n+1)/2)
1 2 3 4 5 6 7 8 9 10 11 12
inlineint sum_of_mult(int f,int last)
//finds sum of multiples of f(short for factor) upto last number
{int n=last/f;return f*n*(n+1)/2;}
void main()
{
int last,sum;
cout<<"Enter last number ";
cin>>last;
sum=sum_of_mult(3,last)+sum_of_mult(5,last)-sum_of_mult(15,last);
cout<<"Sum = "<<sum<<endl;
}
Caution: This approach might not work for homework questions! Even if your answer is correct, it might not be acceptable to the one who is checking your answer, especially if the math involved is very complicated.