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)