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!