0

No output in my code???

So I was writing a code to calculate the sum of all the multiples of 3 and 5 below 1000, but when I finished it and run it, the program didn't have any output. I revised the code for mistakes but I didn't find anything, so maybe someone could tell me why there's no output? Here's the code: #include <iostream> using namespace std; int main() { int multiple5 = 5; int multiple3 = 3; int result = 0; while (multiple3 < 1000) { // I use this if so the multiple5 int doesn't sum to the result after reaching 1000. if (multiple5 >= 1000) { result += multiple3; multiple3 += 3; } //Here is the code that is executed when both multiples are below 1000. else { // I use this if because sometimes the multiple may be the same, and I don't want it to be sumed twice. if (multiple3 != multiple5) { result += multiple3 + multiple5; } else { result += multiple3; multiple3 += 3; multiple5 += 5; } } } cout << result; }

28th Jul 2017, 9:31 AM
Facundo Jurisich
Facundo Jurisich - avatar
3 Respostas
+ 1
If you walk through the program step by step you can usually find the problem easily. Or you can just put std::cout << "blabla" << std::endl; and see where it is called (or not). 3 < 1000 = true, so the while loop is entered 5 >= 1000 = false, so the if is skipped and it goes to the else 3 != 5 = true, so it goes into that if statement and executes result += multiple3 + multiple5; and the next else is skipped. So multiple3 and multiple5 remain untouched and you end up with an infinite loop that keeps incrementing result. I'm guessing this is for project euler ^^ In that case [spoiler] There is an easier way to get the sum of 3 and 5. (n * (MAX / n)) * (1 + (MAX / n)) / 2, where n is the number and MAX is inclusive You replace n by 3 for example and you end up with the sum until MAX To deal with multiple sums you then subtract the same formula with n = 3 * 5 Much faster than just iterating through it. #include <iostream> unsigned long long sum(int n, unsigned long long MAX) { return (n * (MAX / n)) * (1 + (MAX / n)) / 2; } int main() { const unsigned long long MAX = 999; int n1 = 3; int n2 = 5; std::cout << sum(n1, MAX) + sum(n2, MAX) - sum(n1 * n2, MAX); return 0; }
28th Jul 2017, 12:19 PM
Dennis
Dennis - avatar
+ 1
Immortal: Wow when I saw the % operator first time I couldn't think of any utility to it, that was very clever! Dennis: Yes it was for project euler :). Thanks for pointing out the problem. I still don't understand your code so I suppose I should continue the course a bit more before trying to do more problems. Anyway, thanks both!
28th Jul 2017, 8:42 PM
Facundo Jurisich
Facundo Jurisich - avatar