From e8e60ed18eb2faf881f85023de84bd7d9b11d65a Mon Sep 17 00:00:00 2001 From: Priyansh Kumar <71462800+Kpriyansh@users.noreply.github.com> Date: Fri, 22 Oct 2021 23:59:50 +0530 Subject: [PATCH] chore(CPlusPlus): add totient function (#549) Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- algorithms/CPlusPlus/Maths/totient.cpp | 58 ++++++++++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 59 insertions(+) create mode 100644 algorithms/CPlusPlus/Maths/totient.cpp diff --git a/algorithms/CPlusPlus/Maths/totient.cpp b/algorithms/CPlusPlus/Maths/totient.cpp new file mode 100644 index 00000000..0c51e96f --- /dev/null +++ b/algorithms/CPlusPlus/Maths/totient.cpp @@ -0,0 +1,58 @@ +/* +Program Description: +Euler's totient function (also called the Phi function) counts the number of positive integers less than n that +are coprime to n. That is, totient(n) is the number of m∈N such that 1≤m +#include +using namespace std; + + +vectorgetPrimeFactors(int n) { + vectorfactors; + if (n % 2 == 0) { + factors.push_back(2); + while (n % 2 == 0)n /= 2; + } + for (int i = 3; i * i <= n; i += 2) { + if (n % i == 0) { + factors.push_back(i); + while (n % i == 0)n /= i; + } + } + if (n > 1)factors.push_back(n); + return factors; +} +long long totient(int n) { + vectorprimefactors = getPrimeFactors(n); + long long numerator = 1, denominator = 1; + for (auto p : primefactors) { + numerator *= (long long)(p - 1); + denominator *= (long long)p; + } + return ((long long)n * numerator) / denominator; +} +int main() { + + int n; + cout << "Enter a number: "; + cin >> n; + cout << "Number of coprime integers are: " << totient(n) << "\n"; + return 0; +} diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 128c6aae..baa07a9c 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -147,6 +147,7 @@ - [Missing number](Maths/missing-number.cpp) - [Factorial of a number](Maths/factorial.cpp) - [Prime-number](Maths/prime-number.cpp) +- [Totient-function](Maths/totient.cpp) - [Even number of digits](Maths/even-no-of-digits.cpp) - [Power of two](Maths/power-of-two.cpp) - [Small numbers](Maths/small-numbers.cpp)