Sum of Multiples of 3 and 5 Below 1000 - Simple C++ Programming Question

  • Thread starter Thread starter Finkle
  • Start date Start date
  • Tags Tags
    Programming
Click For Summary
SUMMARY

The discussion revolves around a C++ programming challenge from Project Euler, specifically the task of calculating the sum of all multiples of 3 or 5 below 1000. The user initially miscalculated the sum as 234168 due to including 1000 in their range. Upon realizing the mistake, they corrected their approach by excluding 1000. The user also seeks feedback on potential bad coding habits in their implementation.

PREREQUISITES
  • Basic understanding of C++ programming syntax
  • Familiarity with control structures such as loops and conditionals
  • Knowledge of the modulo operator for determining multiples
  • Experience with basic input/output operations in C++
NEXT STEPS
  • Review C++ best practices for variable naming and code readability
  • Learn about the efficiency of using different looping constructs in C++
  • Explore the use of functions to modularize code for better organization
  • Investigate alternative algorithms for solving Project Euler problems
USEFUL FOR

Self-taught programmers, C++ learners, and anyone interested in solving algorithmic challenges efficiently.

Finkle
Messages
6
Reaction score
0
I'm teaching myself C++ and am stuck on this VERY simple problem. I'm not sure what's wrong with my code.

The problem is from https://projecteuler.net/ if anyone is wondering.

Homework Statement


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.

Homework Equations



The Attempt at a Solution


Code:
#include <iostream>
using namespace std;

int main()
{
	int num, add;

	num = 1;
	add = 0;
	while(num < 1001)
	{
		if(num % 3 == 0 || num % 5 == 0)
		{
			add = num + add;
		}
		num = num + 1;
	}
	cout<<add<<endl;
	return 0;
}

The answer I get from this is 234168 but the site says this is wrong.
 
Physics news on Phys.org
Annnnd I figured out what I did wrong. The problem states below rather than up to 1000. It included 1000 in the answer so I just subtract that and be on my way.

If there are any bad habits that are in my code, I would like to know just so I don't continue using it.

Thanks.
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 22 ·
Replies
22
Views
4K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
5
Views
2K
  • · Replies 7 ·
Replies
7
Views
8K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 5 ·
Replies
5
Views
6K