- May 21, 2003
- 2,403
- 3
- 81
I've been wanting to learn C++ for a long time and I've started on several books and tutorials. The lack of appropriate problems to practice on has held me back until today I when discovered Project Euler.
Problem 1 was pretty easy and I came up with this in a couple of minutes and it gives the correct answer:
Of course I'm not satisfied just getting the correct answer, I wanted to reduce the # of LOC and make it more elegant and maybe get a quicker execution time so I paired it down to this:
Which is smaller but gives the wrong answer and evidently is not logically the same but I don't see how.
The key difference being
is apparently not the same as
I don't see why though, can anyone give me any hints why these aren't equivalent? Any other tips on C++ are also welcome.
Problem 1 was pretty easy and I came up with this in a couple of minutes and it gives the correct answer:
Code:
int num = 1;
double sum = 0;
for (num = 1; num < 1000; num++)
if ((num % 3) == 0){
sum = sum + num;}
else if ((num % 5) == 0){
sum = sum + num;}
cout << "the answer is: " << sum;}
Of course I'm not satisfied just getting the correct answer, I wanted to reduce the # of LOC and make it more elegant and maybe get a quicker execution time so I paired it down to this:
Code:
int sum = 0;
for (int num = 1; num < 1000; num++)
if ((num % 3)||(num % 5) == 0){
sum += num;}
cout << "the answer is: " << sum;}
The key difference being
Code:
if ((num % 3)||(num % 5) == 0){...}
Code:
if ((num % 3) == 0){...}
else if ((num % 5) == 0){...}
