You are here:

C++/Divisors program confused?


I want to write a program that finds how many divisors a number has, and displays what those numbers are in the output.  For example:
the number 60 has 12 divisors which produce no remainder
How can i set this up?
thank you for your help.

to break up the problem into two smaller subproblems:

problem a. check if a number is the divisor of another number

the modulo operator finds the remainder of division of one number by another.
given two integers, a (the dividend) and n (the divisor), a modulo n (written as a % n in C or C++ ) is the remainder, on division of a by n.
for instance, the expression 7 % 3 would evaluate to 1, while 9 % 3 would evaluate to 0.
checking if a number is a divisor of another number is therefore easy; if a%n == 0, n is a divisor of a.

note: though here, we only need to check if the result is zero on non-zero, it is useful to remember that the modulo operator can be portably used only for non-negative integers.
"the binary % operator yields the remainder from the division of the first expression by the second. .... If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined".
- ISO/IEC 14882:2003 (the IS for C++) : paragraph 5.6.4

problem b. find all the divisors of a number n:

a trivial logic is:
 step 1. check if 2 is a divisor (is n%2 zero?)
 step 2. check if 3 is a divisor (is n%3 zero?)
 step 3. check if 4 is a divisor (is n%4 zero?)
 and so on upto n/2.

the obvious way to do this would be to write a loop; stating with 2 and going upto n/2.

first get this much working correctly.
and then give a thought to 'can i modify this to make it faster?'  


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2017 All rights reserved.