Reputation: 105
My question looks like this For numbers from 2 to 20, output the proper divisors and their sum.
So it should look like this:
2: 1 = 1
3: 1 = 1
4: 1+2 = 3
5: 1 = 1
6: 1+2+3 = 6
...
20: 1+2+4+5+10 = 23
This is what i wrote so far:
#include <iostream>
int main () {
int a=2;
int sum=1;
while (a<=10){
std::cout<<a<<": ";
for(int b=1; b<a; b=b+1)
{
if(a%b == 0)
{
std::cout<<b<<" + ";
sum+=b;}
if (b == a-1){
std::cout<<"= "<<sum<<"\n";
}
}
a++;
}
return 0;
}
When i compile and run, the output ends up looking like this:
2: 1 + = 2
3: 1 + = 3
4: 1 + 2 + = 6
5: 1 + = 7
6: 1 + 2 + 3 + = 13
7: 1 + = 14
8: 1 + 2 + 4 + = 21
9: 1 + 3 + = 25
10: 1 + 2 + 5 + = 33
My issues are currently:
Why does it give me the sum of all of the previous b results? I am trying to get the sum of only the divisors for each number. It gives me the sum of all previous sums.
Also, how do i get rid of the extra (+) at the end?
Many thanks!
EDIT:
Thanks guys! Here's the code after i adjusted it and cleaned it up a little bit!
#include <iostream>
int main() {
int a = 2;
while (a <= 20) {
std::cout <<a <<": ";
int sum = 0;
for (int b = 1; b < a; b = b + 1) {
if (a%b == 0) {
if (b == 1) {
std::cout <<b;
} else {
std::cout <<" + " <<b; }
sum += b; }
if (b == a-1) {
std::cout <<"= " <<sum <<"\n";
}
}
a++;
}
return 0;
}
It now works like a charm. The output has a few too many whitespaces but its good enough. Many thanks!
Upvotes: 0
Views: 208
Reputation: 22360
Try something like this it uses this answer for not adding the +
after the last item of divisors
:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
std::vector<int> properDivisors ( int number ) {
std::vector<int> divisors ;
for ( int i = 1 ; i < number / 2 + 1 ; i++ )
if ( number % i == 0 )
divisors.push_back( i ) ;
return divisors ;
}
int main()
{
for(size_t i = 2; i <= 20; ++i)
{
std::vector<int> divisors = properDivisors(i);
std::cout << i << ": ";
const char *padding = "";
for (auto iter = divisors.begin(); iter != divisors.end(); ++iter) {
std::cout << padding << *iter;
padding = " + ";
}
int sum = 0;
for (auto& n : divisors)
sum += n;
std::cout << " = " << sum;
std::cout << std::endl;
}
}
Output:
2: 1 = 1
3: 1 = 1
4: 1 + 2 = 3
5: 1 = 1
6: 1 + 2 + 3 = 6
7: 1 = 1
8: 1 + 2 + 4 = 7
9: 1 + 3 = 4
10: 1 + 2 + 5 = 8
11: 1 = 1
12: 1 + 2 + 3 + 4 + 6 = 16
13: 1 = 1
14: 1 + 2 + 7 = 10
15: 1 + 3 + 5 = 9
16: 1 + 2 + 4 + 8 = 15
17: 1 = 1
18: 1 + 2 + 3 + 6 + 9 = 21
19: 1 = 1
20: 1 + 2 + 4 + 5 + 10 = 22
Try it here!
Upvotes: 0
Reputation: 289
You need to reset the value of sum to zero at the beginning of each iteration of the while loop to avoid the multiple sum problem.
As far as the extra +, you could print "+" before the value of 'b' instead of after, and only if b > 1 (there is guaranteed a printed value before the current value of b).
Upvotes: 2