Ronaldo
Ronaldo

Reputation: 27

Use a nested for loop to list the factors of all the numbers from 1 to 100

What the output is suppose to look like:

1: 1
2: 1, 2
etc.
40: 1, 2, 4, 5, 8, 20, 40
etc.
50: 1, 2, 5, 10, 25, 50
etc.

I'm using modulus to try to get the factors from 1-100 (i.e. 5%3 will be 2, 4%3 will be 1, 4%2 will be 0 --> SO 2 is a factor of 4). I think I need another loop to have it come out like the output up above. If anybody can kindly explain to me what I have done wrong and the steps I can take to get on the right path would be greatly appreciated. Whats wrong is that the numbers aren't matching to the output And I cant seem to get it to print out in the sequence above.

   #include <iostream>
   using namespace std; 


     int main()
   {
      cout<<1<<endl; 
      //Flag indicator
       bool isFactor;

    for(int i=2; i<100; i++)
    {
        isFactor=true;
        for(int j=3; j<i; j++)
        {
            if(i%j==0)
            {
                isFactor=false;             
            }
        }
        if(isFactor)
        {
        cout<<i;
        }

    }
    cout<<endl;

 }    

Upvotes: 0

Views: 689

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 311068

It seems you mean the following

#include <iostream>

int main() 
{
    for ( int i = 1; i <= 100; i++ )
    {
        std::cout << i << ": ";
        for ( int j = 1; j <= i / 2; j++ )
        {
            if ( i % j == 0 ) std::cout << j << ", ";
        }
        std::cout << i << std::endl;
    }
}

The program output can look like

1: 1
2: 1, 2
3: 1, 3
4: 1, 2, 4
5: 1, 5
6: 1, 2, 3, 6
7: 1, 7
8: 1, 2, 4, 8
9: 1, 3, 9
10: 1, 2, 5, 10
11: 1, 11
12: 1, 2, 3, 4, 6, 12
13: 1, 13
14: 1, 2, 7, 14
15: 1, 3, 5, 15
16: 1, 2, 4, 8, 16
17: 1, 17
18: 1, 2, 3, 6, 9, 18
19: 1, 19
20: 1, 2, 4, 5, 10, 20
21: 1, 3, 7, 21
22: 1, 2, 11, 22
23: 1, 23
24: 1, 2, 3, 4, 6, 8, 12, 24
25: 1, 5, 25
26: 1, 2, 13, 26
27: 1, 3, 9, 27
28: 1, 2, 4, 7, 14, 28
29: 1, 29
30: 1, 2, 3, 5, 6, 10, 15, 30
31: 1, 31
32: 1, 2, 4, 8, 16, 32
33: 1, 3, 11, 33
34: 1, 2, 17, 34
35: 1, 5, 7, 35
36: 1, 2, 3, 4, 6, 9, 12, 18, 36
37: 1, 37
38: 1, 2, 19, 38
39: 1, 3, 13, 39
40: 1, 2, 4, 5, 8, 10, 20, 40
.....

As for your code then it does not make sense.:)

For example why this loop

for(int i=2; i<100; i++)
//...

starts from 2 and does not include 100?

Or this code snippet

    if(isFactor)
    {
    cout<<i;
    }

must be inside the inner loop.

And this condition

  if(i%j==0)
    {
        isFactor=false;             
    }

must be written at least like

  if(i%j==0)
    {
        isFactor=true;             
    }

Upvotes: 1

Related Questions