Extracting Divisors: A Simple Guide for Adding Factors

  • Thread starter Thread starter soul5
  • Start date Start date
AI Thread Summary
To extract divisors of a number in C++, initialize a sum variable to zero and iterate from 1 to n, checking if each number is a divisor using the modulus operator. If a number is a divisor, add it to the sum. To store all divisors, use a vector and push back each divisor when the condition is met. It's more efficient to limit the loop to n/2, as no divisors greater than n/2 exist, but ensure to include n itself as a divisor. The corrected loop should run from 1 to n, and remember to check for syntax errors like missing semicolons.
soul5
Messages
63
Reaction score
0
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:
Technology 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;
cout << enter number;
cin >> n;

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

if ( n % i == 0 )

sum += i;

}

cout << " 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.
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Back
Top