Extracting Divisors: A Simple Guide for Adding Factors

  • Thread starter Thread starter soul5
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
soul5
Messages
63
Reaction score
0
Ok this is what I did


int n;
count << 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:
Physics news on Phys.org
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:
soul5 said:
int sum=0;
int n;
count << enter number;
cin >> n;

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

if ( n % i == 0 )

sum += i;

}

count << " sum is " << sum << endl;

changed again
 
Last edited:
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.