You are using a version without Ads of this website. Please, consider donating:

### Miscalc in find all sum of all mults of 3 and 5 less than 1000

My code is giving me the wrong answer for the total sum of :266341
According to online sources the correct answer is :233168.

I can't see the problem in my code. Can anyone find it?

#include <iostream>
#include <vector>

using namespace std;

int main ()
{

vector<int> array_mult_three (1); //vector to hold mulitples of 3
vector<int> array_mult_five (1); //vector to hold mulitples of 5

array_mult_three[0] = 3;
array_mult_five[0] = 5;

for (int multiply_counter = 1; (multiply_counter * 3) < 1000; ++multiply_counter)
{

int temp_multiple = 0;

temp_multiple = multiply_counter * 3; //multiples every numb < 1000 by 3

array_mult_three.push_back(temp_multiple); //creates new index and stores

}

for (int multiply_counter = 1; (multiply_counter * 5) < 1000; ++multiply_counter)
{

int temp_multiple = 0;

temp_multiple = multiply_counter * 5; //multiples every numb < 1000 by 3

array_mult_five.push_back(temp_multiple); //creates new index and stores

}

int sum_multiples3 = 0;

{

}

int sum_multiples5 = 0;

{

}

cout << "These are all the multiples of 3 less than a 1000:" << endl;

for (int counter = 1; counter < array_mult_three.size(); ++counter)
{
cout << array_mult_three[counter] << " ";
}

cout << "These are all the multiples of 5 less than a 1000:"<< endl;

for (int counter = 1; counter < array_mult_five.size(); ++counter)
{
cout << array_mult_five[counter] << " ";
}

cout<< "The sum of all the multiples of 3 and 5 less than 1000 is: " << sum_multiples5 + sum_multiples3 << endl;

cout << "Press any key to exit:";
char Get_Out = '\0';
cin >> Get_Out;

return 0;

}
You are adding multiples of 15 twice, once as multiples of three, and once more as multiples of five.

You don't really need those vectors, do you? The sum can be computed:

 ``12345678910`` ``````#include // sum of multiples of m less than n // 1+2+3+ ... +n == n * (n+1) / 2 int sum_mults( int n, int m ) { int c = (n-1)/m ; return m * c * (c+1) / 2 ; } int main() { std::cout << sum_mults(1000,3) + sum_mults(1000,5) - sum_mults(1000,15) << '\n' ; }``````

http://liveworkspace.org/code/47k1iN\$0
As well as the double counting of 15 and multiples, the output loop starts from 1,
`int counter = 1 `
but the summation loop starts from 0.
`int add_runs = 0`
Why?

Anyway, here's yet another version:
 ``123456789101112131415161718192021222324252627282930`` ``````#include #include using namespace std; int main() { const int limit = 1000; set multiples; for (int i=3; i::iterator it=multiples.begin(); it != multiples.end(); it++) { total += *it; cout << *it << " "; } cout << "\n\nTotal = " << total << endl; cin.get(); return 0; }``````
Last edited on
Topic archived. No new replies allowed.