Why does this work with 10 but not 1000?

Attempting to solve this problem http://wiki.answers.com/Q/What_is_the_sum_of_all_the_multiples_of_3_or_5_below_1000

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.

What am I missing?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using namespace 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;
}
You're counting numbers that are multiples of 3 and 5 twice.
The first such number is 15, so it's to be expected that the result is correct for n=10.
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
Last edited on
here's an even simpler program that does it CORRECT:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int i, sum=0;
	for (i=3; i<1000; i++)
	{
		if (i%3==0) sum+=i;
		else if (i%5==0) sum+=i;
		}
	cout<<sum<<endl; 
}

Try to follow the KISS principle.
Ah yes, thanks guys. Overlooked such a simple thing like that...

Does that else if operate like an Or kind of and make it so that multiples of both 3 and 5 don't get added twice? Just making sure I understand.
Last edited on
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
inline int 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;
}


An example on how math can be very very helpful:
http://www.cplusplus.com/forum/beginner/72513/#msg386751

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.
Last edited on
Topic archived. No new replies allowed.