About calculating divisors of a number
First of all, remember that you can determine whether the number
b
is a divisor of the number
a
as follows.
C++
|
if( a % b == 0 )
// number b is a divisor of number a
else
// number b is not a divisor of number a
|
Python |
if a % b == 0:
// number b is a divisor of number a
else:
// number b is not a divisor of number a
|
Pascal |
if a mod b = 0 then
// number b is a divisor of number a
else
// number b is not a divisor of number a
|
The easiest way to find all divisors of the number n
is to check the divisibility of n
by each of the numbers 1, 2, 3, ..., n in turn
.
The example below shows how to display all divisors of a number
n
.
C++
|
Python |
Pascal |
for(int i = 1; i <= n; i++)
if( n % i == 0 )
cout << i << " ";
|
for i in range(1, n+1):
if n % i == 0:
print( i )
|
for i:=1 to n do
if n mod i = 0 then
write(i, ' ');
|
If you need to calculate the number of divisors of the number
n
, then it is enough to create a variable that will increase by
1
if the condition is met (
n % i == 0, n mod i = 0
).
C++
|
Python |
Pascal |
k = 0
for(int i = 1; i <= n; i++)
if( n % i == 0 )
k++;
cout << k;
|
k = 0
for i in range(1, n+1):
if n % i == 0:
k += 1
print( k )
|
k := 0
for i:=1 to n do
if n mod i = 0 then
k := k + 1;
write(k);
|