Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do i find the divisors of a number using c?

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
How do i find the sum of the divisors of a number?

for example

for 12

1 + 2 + 3 + 4 + 6 =16
 
Find each of the divisors, and keep adding them to the running total.

int i, sum = 0, num = 12;

for(i=1; i <= num/2; i++)
if(!(num % i))
sum += i;

printf(&quot;%d&quot;, sum);

Bye.
Ankan. Please do correct me if I am wrong. :)
 
Don't forget about performance:

int x;
.....
x=num/2; /* by the way num<<1 is much faster than num/2 */
for(i=1; i <= x; i++)
........
John Fill
1c.bmp


ivfmd@mail.md
 
Thanks a lot, JohnFill, for reminding me. Will keep it in mind from now on.

And hey, I thought you could help me out at Thread205-112554. I'm just asking for a hint as to what's possibly wrong, maybe u can help. Please :). Bye.
Ankan.

Please do correct me if I am wrong. s-)
 
Hey John,
I almost forgot, your:
&quot; /* by the way num<<1 is much faster than num/2 */&quot;
should be
&quot; /* by the way num>>1 is much faster than num/2 */&quot;
and to be on the safe side num should be declared unsigned.

Hope you agree.
Bye.
Ankan.

Please do correct me if I am wrong. s-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top