project euler problem 1

Jan 25, 2012 at 1:15am
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// problem1.cpp
/* 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 <iostream>
using namespace std;

int main(){
	int num = 0;
	int x;
	for (x = 3; x < 1000; x++){
		if ( x % 3 == 0 ){
			num += x;
			cout << x << " ";
		}
	 	if ( x % 5 == 0 ){
			num += x;
			cout << x << " ";
		}
	}
	cout << endl << "total sum: " << num << endl;
	return 0;
}

when ii put in 10 it works but when ii put in a 1000 its wrong ?_?
Jan 25, 2012 at 1:38am
Please note that I am a beginner as well but I'm tearing through project euler pretty well.

This was my algorithm (correct term?) or solution for this problem.

Assume min and max are defined and everything else is kosher.

1
2
3
4
 for (int counter = min; counter < max; ++counter) {
          if ((counter % 3 == 0) || (counter % 5 == 0)) 
               sum += counter;
    }


I believe, correct me if I am wrong, that you are double counting...

By having 2 if statements then anything that satisfies bot gets counted twice.

Say 30.

30%3 = 0 so -> num+= x

but

30%5=0 is also true so num+=x happens again.

Try putting both tests in the same if statement like mine.


if ((counter % 3 == 0) || (counter % 5 == 0))

This way whether the first test is true or the second is true or both are true, you will only count once.
Last edited on Jan 25, 2012 at 1:43am
Jan 25, 2012 at 1:44am
yeaa that solved it. ii was thinking ii was suppose to solve all of multiples of 3 && 5.
thx for your help ^_^
Jan 25, 2012 at 1:47am
No problem. I actually had that problem for awhile. Was pulling my hair out. I basically had to print each number to the console which was when I noticed some numbers printing twice. LOL
Jan 25, 2012 at 2:02am
what project are you on now ?
Jan 25, 2012 at 2:05am
I think 32? My problem now is the math lol... About 75% of my time is figuring out the problem. Once that happens the code is not so bad.
Jan 25, 2012 at 2:37am
are you teaching yourself c++ or do you learn from an university.
sorry if im being too nosey ^_^
Jan 25, 2012 at 2:39am
I'm in an intro class this semester but I way beyond it now.

I just find it easier to have a book, the web and concrete problems to solve when learning.
Topic archived. No new replies allowed.