# I need to extract a divisor

1. Oct 4, 2008

### soul5

Ok this is what I did

int n;
cout << enter number;
cin >> n;

for (int i = 1 ; i < n ; i++ )

if ( n % i == 0 )

I could use some help please like how to I extract the divisor?

so I can add them. Thanks a lot.

Last edited: Oct 5, 2008
2. Oct 5, 2008

### Defennder

Your if condition tells you if i is a divisor. Since you said you want to add up all the divisors you have to declare an identifier, say int sum=0; at the start.

So you can do this should the if statement be satisfied:

if(n%i==0)
sum += i;

If you're writing a function, then you'll want to return sum after you're done. Alternatively if you want all the divisors individually, one way is to initialise an integer vector, say vector<int> divisors (remember to #include <vector>), and use divisors.push_back(i); each time your if condition is true.

More importantly you can improve your program slightly by specifying your for loop as :
for(int i=1;i<=n/2;i++) since it is evident that there cannot be any divisors of n which is larger than n/2.

Last edited: Oct 5, 2008
3. Oct 5, 2008

### soul5

changed again

Last edited: Oct 5, 2008
4. Oct 5, 2008

### Defennder

Well it looks ok to me. You forgot a semiconlon for your sum statement though. The best way to know if it'll work is to actually try it out. One thing overlooked earlier: your for loop doesn't allow i to be "n", which it should, since for any number n, n itself is a divisor of n. So change it to i<=n.