TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
number_of_positive_divisors.cpp
Go to the documentation of this file.
1
24
25
#include <cassert>
26
32
int
number_of_positive_divisors
(
int
n) {
33
if
(n < 0) {
34
n = -n;
// take the absolute value of n
35
}
36
37
int
number_of_divisors = 1;
38
39
for
(
int
i = 2; i * i <= n; i++) {
40
// This part is doing the prime factorization.
41
// Note that we cannot find a composite divisor of n unless we would
42
// already previously find the corresponding prime divisor and dvided
43
// n by that prime. Therefore, all the divisors found here will
44
// actually be primes.
45
// The loop terminates early when it is left with a number n which
46
// does not have a divisor smaller or equal to sqrt(n) - that means
47
// the remaining number is a prime itself.
48
int
prime_exponent = 0;
49
while
(n % i == 0) {
50
// Repeatedly divide n by the prime divisor n to compute
51
// the exponent (e_i in the algorithm description).
52
prime_exponent++;
53
n /= i;
54
}
55
number_of_divisors *= prime_exponent + 1;
56
}
57
if
(n > 1) {
58
// In case the remaining number n is a prime number itself
59
// (essentially p_k^1) the final answer is also multiplied by (e_k+1).
60
number_of_divisors *= 2;
61
}
62
63
return
number_of_divisors;
64
}
65
69
void
tests
() {
70
assert(
number_of_positive_divisors
(36) == 9);
71
assert(
number_of_positive_divisors
(-36) == 9);
72
assert(
number_of_positive_divisors
(1) == 1);
73
assert(
number_of_positive_divisors
(2011) == 2);
// 2011 is a prime
74
assert(
number_of_positive_divisors
(756) == 24);
// 756 = 2^2 * 3^3 * 7
75
}
76
80
int
main
() {
81
tests
();
82
return
0;
83
}
tests
void tests()
Definition
number_of_positive_divisors.cpp:69
number_of_positive_divisors
int number_of_positive_divisors(int n)
Definition
number_of_positive_divisors.cpp:32
main
int main()
Definition
number_of_positive_divisors.cpp:80
math
number_of_positive_divisors.cpp
Generated by
1.14.0