Algorithms_in_C++  1.0.0
Set of algorithms implemented in C++.
number_of_positive_divisors.cpp File Reference

C++ Program to calculate number of divisors. More...

#include <iostream>
#include <vector>
Include dependency graph for number_of_positive_divisors.cpp:

Functions

int number_of_positive_divisors (int n)
 
int main ()
 

Detailed Description

C++ Program to calculate number of divisors.

This algorithm use the prime factorization approach. Any number can be written in multiplication of its prime factors.
Let N = P1^E1 * P2^E2 ... Pk^Ek
Therefore. number-of-divisors(N) = (E1+1) * (E2+1) ... (Ek+1).
Where P1, P2 ... Pk are prime factors and E1, E2 ... Ek are exponents respectively.

Example:-
N = 36
36 = (3^2 * 2^2)
number_of_positive_divisors(36) = (2+1) * (2+1) = 9.
list of positive divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36.

Similarly if N is -36 at that time number of positive divisors remain same.

Example:-
N = -36
-36 = -1 * (3^2 * 2^2)
number_of_positive_divisors(-36) = (2+1) * (2+1) = 9.
list of positive divisors of -36 = 1, 2, 3, 4, 6, 9, 12, 18, 36.

Function Documentation

◆ main()

int main ( )

Main function

62  {
63  int n;
64  std::cin >> n;
65  if (n < 0) {
66  n = -n;
67  }
68  if (n == 0) {
69  std::cout << "All non-zero numbers are divisors of 0 !" << std::endl;
70  } else {
71  std::cout << "Number of positive divisors is : ";
73  }
74 }
Here is the call graph for this function:

◆ number_of_positive_divisors()

int number_of_positive_divisors ( int  n)

Algorithm

34  {
35  std::vector<int> prime_exponent_count;
36  for (int i = 2; i * i <= n; i++) {
37  int prime_count = 0;
38  while (n % i == 0) {
39  prime_count += 1;
40  n /= i;
41  }
42  if (prime_count != 0) {
43  prime_exponent_count.push_back(prime_count);
44  }
45  }
46  if (n > 1) {
47  prime_exponent_count.push_back(1);
48  }
49 
50  int divisors_count = 1;
51 
52  for (int i = 0; i < prime_exponent_count.size(); i++) {
53  divisors_count = divisors_count * (prime_exponent_count[i] + 1);
54  }
55 
56  return divisors_count;
57 }
Here is the call graph for this function:
std::vector< int >
std::vector::size
T size(T... args)
std::vector::push_back
T push_back(T... args)
std::cout
std::endl
T endl(T... args)
number_of_positive_divisors
int number_of_positive_divisors(int n)
Definition: number_of_positive_divisors.cpp:34
std::cin