From 877125eb8acff2dc638f3e95451e28f6d93f81bb Mon Sep 17 00:00:00 2001 From: Mann Mehta <44433995+mann2108@users.noreply.github.com> Date: Wed, 15 Apr 2020 03:00:23 +0530 Subject: [PATCH] Added number-of-divisors.cpp in math directory --- math/number-of-divisors.cpp | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 math/number-of-divisors.cpp diff --git a/math/number-of-divisors.cpp b/math/number-of-divisors.cpp new file mode 100644 index 000000000..fd2d40707 --- /dev/null +++ b/math/number-of-divisors.cpp @@ -0,0 +1,47 @@ +/// C++ Program to calculate number of divisors. + +#include +#include + +/** + * 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) + * numbe-of-divisors(36) = (2+1) * (2+1) = 9. + * list of divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36. +**/ + +int number_of_divisors(int n) { + std::vector prime_exponent_count; + for (int i=2; i*i <= n; i++) { + int prime_count = 0; + while (n % i == 0) { + prime_count += 1; + n /= i; + } + if (prime_count != 0) { + prime_exponent_count.push_back(prime_count); + } + } + int divisors_count = 1; + // If n is prime at that time vector prime_exponent_count will remain empty. + for (int i=0; i> n; + std::cout << number_of_divisors(n) << std::endl; +}