Hi, so the exercise I am supposed to do is :
"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."

So, the question is pretty simply, nothing hard to understand. Here is the function I did to get it :

#include <iostream>
#include <string>

using namespace std;

int calculate(int max)
{
	int result = 0;


	for(int i = 1; 5 * i < max ; i++)
	{
		
			result += (i *  5);
			cout << (i * 5) << " + ";

	}

	for( int i = 1 ; 3 * i < max ; i++)
	{
		result += (i * 3);
		cout << (i * 3) << " + ";
	}
	cout << 0;

	return result;
}

int main()
{
	cout <<" = " << calculate(1000);
	cin.ignore();
	cin.get();
}

The function does give me a result but when I put it in to the exercise box, it says it's a wrong answer and would redirect me again to the problem. I don't see why it doesn't work, it works completely fine for the 10 but it won't work for the 1000;
And also, the couts in the calculate function are completely secondary, they were just there to show me what is getting added, you can delete them all, it won't matter;
And sorry if the solution to this is easy, I am in my first week of C++ so I'm still quite noob-ish;

Thanks a lot for the answers in advance guys :)

Oh, and if you want the website to this and many other problems, just ask me :), I didn't think it was necessary to resolve this though.

Recommended Answers

All 2 Replies

The problem with your algo is that when you get to numbers like 15 which are divisible by both 3 and 5 you add it in twice. I think a a better way would be to use one for loop from 3 to 1000 and check with an if statement if the number is divisible by either 3 or 5. If it is add it to the total if not continue. One way you can make it run a faster is to skip all even numbers. (hint) You can do this in the step condition in the for loop.

commented: Thank you :) +0

The problem with your algo is that when you get to numbers like 15 which are divisible by both 3 and 5 you add it in twice. I think a a better way would be to use one for loop from 3 to 1000 and check with an if statement if the number is divisible by either 3 or 5. If it is add it to the total if not continue. One way you can make it run a faster is to skip all even numbers. (hint) You can do this in the step condition in the for loop.

Oh, thank you SO much :), that was so helpful..
I should try thinking for more than five minutes though next time and stop being lazy..
And the "The problem with your algo is that when you get to numbers like 15 which are divisible by both 3 and 5 you add it in twice." is all what needed :D
Thanks a lot man, that was extremely helpful.

+1

Topic closed...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.