Hello,
I am trying to find the divisors of the numbers 2 through 100, add them up, and print them out as follows:
2: 1 = 1
3: 1 = 1
4: 1+2 = 3
5: 1 = 1
6: 1+2+3 = 6
...
100: 1+2+4+5....
I know how to find the divisors of one number, but I am having trouble iterating through all numbers up to 100 (I haven't even attempted the adding and printing yet). Right now I am just trying to get a list of all the divisors for numbers 1 through 100. All that prints when I run the program is a 1. Here is my code:
#include <iostream>
using std::cout;
using std::endl;
int main () {
int num = 2;
int i = 1;
while (num < 100)
{
if (num % i ==0 && i < num)
{
cout << i << endl;
i++;
}
if (i >= num)
{
i == 1;
num++;
}
else
{
i++;
}
}
return 0;
}
Hengry, sorry I forgot to mention I'm doing all divisors excluding the number itself; otherwise you'd be right.
Thank you Mantor22!
Part of the issue was an == where there should have just been =. I used a sum variable but did it differently, since I don't really understand how to use bool. However, I'm stuck at how to not end each line of divisors with an extra '+'. Here is my code:
#include <iostream>
using std::cout;
using std::endl;
int main () {
int num = 2;
int i = 1;
int sum = 0;
cout << num << ":";
while( num < 20 )
{ if (num % i == 0 && i < num)
{sum = sum + i;
cout << i << "+";
i++;}
elseif (num % i != 0 && i < num)
{i++;}
else
{i = 1;
num++;
cout <<"=" << sum;
cout << "\n" << num << ":";
sum = 0;}
}
return 0;
}
Which gave me this result:
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
...