+ 1

C++ incorrect output summing multiples [Solved]

Passes some tests in Code Coach but not all. /* You need to calculate the sum of all the multiples of 3 or 5 below a given number. Task: Given an integer number, output the sum of all the multiples of 3 and 5 below that number. If a number is a multiple of both, 3 and 5, it should appear in the sum only once. Input Format: An integer. Output Format: An integer, representing the sum of all the multiples of 3 and 5 below the given input. Sample Input: 10 Sample Output: 23 */ #include <iostream> using namespace std; int main() { int sum = 0; int x = 1; int y; cin >> y; while(x<=y){ if((x % 5 == 0) != (x %3 == 0)) { sum += x; } x += 1; } cout<<sum<<endl; return 0; } If 100 is entered output is 2103 but should be 2318. Can anyone point out the error?

11th Nov 2022, 8:53 PM
Scott D
Scott D - avatar
6 Réponses
+ 2
You are including y. But asked to find below the numbers of y. See my next point. x < y != means not equal to || is OR logical operator, either one or both, must be true => true
11th Nov 2022, 9:33 PM
Jayakrishna 🇮🇳
+ 2
What is the != means there? Should not be || there instead? also below number y so use x<y , instead of x<=y
11th Nov 2022, 9:13 PM
Jayakrishna 🇮🇳
+ 1
Jayakrishna🇮🇳 Interesting! My logic was that it states : " If a number is a multiple of both, 3 and 5, it should appear in the sum only once. " != appears to work in some cases but not all. I thought "as long as %5 != %3 then sum them. But now I think that maybe it adds neither to the sum if they are != ... Could that be the problem? What is interesting is that I tried using || instead and the output was 2418 instead of 2318. So || instead of != seems to almost work. I can perhaps cheat by then using "sum2 = sum - y" but would still like to find the error in my logic. https://code.sololearn.com/cXMBxX63tBnV/?ref=app
11th Nov 2022, 9:29 PM
Scott D
Scott D - avatar
+ 1
Jayakrishna🇮🇳 Perfect! So I now see the two errors in my logic. Thank you for your help.
11th Nov 2022, 9:37 PM
Scott D
Scott D - avatar
+ 1
Jayakrishna🇮🇳 I should have put 2 + 2 together... If y was 100 and my output was over by 100, I should have seen that 😶
11th Nov 2022, 9:40 PM
Scott D
Scott D - avatar
0
can you please show your solved code
26th Dec 2023, 5:08 AM
Таксин
Таксин - avatar