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
25#include <cassert>
26#include <iostream>
27
34 if (n < 0) {
35 n = -n; // take the absolute value of n
36 }
37
38 int number_of_divisors = 1;
39
40 for (int i = 2; i * i <= n; i++) {
41 // This part is doing the prime factorization.
42 // Note that we cannot find a composite divisor of n unless we would
43 // already previously find the corresponding prime divisor and dvided
44 // n by that prime. Therefore, all the divisors found here will
45 // actually be primes.
46 // The loop terminates early when it is left with a number n which
47 // does not have a divisor smaller or equal to sqrt(n) - that means
48 // the remaining number is a prime itself.
49 int prime_exponent = 0;
50 while (n % i == 0) {
51 // Repeatedly divide n by the prime divisor n to compute
52 // the exponent (e_i in the algorithm description).
53 prime_exponent++;
54 n /= i;
55 }
56 number_of_divisors *= prime_exponent + 1;
57 }
58 if (n > 1) {
59 // In case the remaining number n is a prime number itself
60 // (essentially p_k^1) the final answer is also multiplied by (e_k+1).
61 number_of_divisors *= 2;
62 }
63
64 return number_of_divisors;
65}
66
70void tests() {
71 assert(number_of_positive_divisors(36) == 9);
72 assert(number_of_positive_divisors(-36) == 9);
73 assert(number_of_positive_divisors(1) == 1);
74 assert(number_of_positive_divisors(2011) == 2); // 2011 is a prime
75 assert(number_of_positive_divisors(756) == 24); // 756 = 2^2 * 3^3 * 7
76}
77
81int main() {
82 tests();
83 int n;
84 std::cin >> n;
85 if (n == 0) {
86 std::cout << "All non-zero numbers are divisors of 0 !" << std::endl;
87 } else {
88 std::cout << "Number of positive divisors is : ";
89 std::cout << number_of_positive_divisors(n) << std::endl;
90 }
91 return 0;
92}
int number_of_positive_divisors(int n)