2 codes, same objective

Feb 11, 2015 at 12:04am
Guys, why do this 2 codes give me different asnswers?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
  #include <iostream>

using namespace std;

int main()
{
	int SumUp = 0;

	int nX3CMax = 333;
	for (int nX3 = 3 , nCountX3 = 0; nCountX3 <= nX3CMax; ++nCountX3)
		SumUp += (nX3 * nCountX3);

	int nX5CMax = 199;
	for (int nX5 = 5 , nCountX5 = 0; nCountX5 <= nX5CMax; ++nCountX5)
		SumUp += (nX5 * nCountX5);

	cout << SumUp << endl;
	system("pause");
	return 0;
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  #include <iostream>

using namespace std;

int main()
{
	int SumUp = 0;

	for ( int iii = 1 ; iii < 1000 ; iii++)
		{	
			if ((iii % 3) == 0 || (iii % 5) == 0 )
				SumUp += iii;
		}

	cout << SumUp << endl;
	system("pause");
	return 0;
}
Last edited on Feb 11, 2015 at 12:04am
Feb 11, 2015 at 12:17am
closed account (2UD8vCM9)
I think the reason that it is not functioning like you expect is because there are numbers divisible by both 5 and 3 (for example: 15)

In the second code, you would only add this once, while in the first code, you're adding this twice.

Also please don't post such unclear code with no explanation on what it should even be doing. Your variable names are awful.
Last edited on Feb 11, 2015 at 12:18am
Feb 11, 2015 at 12:18am
Because they are doing different things.

Here is code which does same thing as first:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main()
{
    int SumUp = 0;

    for ( int iii = 1 ; iii < 1000 ; iii++) {
        if ((iii % 3) == 0)
            SumUp += iii;
        if ((iii % 5) == 0)
            SumUp += iii;
    }

    cout << SumUp << endl;
    system("pause");
}
Last edited on Feb 11, 2015 at 12:18am
Feb 11, 2015 at 12:21am
You are both right... ty... and sorry for variables names, I will do better next time.
Topic archived. No new replies allowed.