From 58f6815aadf37b55f6d89bf298975f04a52aeddb Mon Sep 17 00:00:00 2001 From: John Law Date: Tue, 31 Mar 2020 23:26:32 +0200 Subject: [PATCH] Format Euler's Totient --- math/eulers_totient_function.cpp | 48 +++++++++++++++----------------- 1 file changed, 23 insertions(+), 25 deletions(-) diff --git a/math/eulers_totient_function.cpp b/math/eulers_totient_function.cpp index 8165f030e..31ced5a51 100644 --- a/math/eulers_totient_function.cpp +++ b/math/eulers_totient_function.cpp @@ -1,38 +1,36 @@ /// C++ Program to find Euler Totient Function #include -/** +/* + * Euler Totient Function is also known as phi function. + * phi(n) = phi(p1^a1).phi(p2^a2)... + * where p1, p2,... are prime factors of n. + * 3 Euler's properties: + * 1. phi(prime_no) = prime_no-1 + * 2. phi(prime_no^k) = (prime_no^k - prime_no^(k-1)) + * 3. phi(a,b) = phi(a). phi(b) where a and b are relative primes. + * Applying this 3 properties on the first equation. + * phi(n) = n. (1-1/p1). (1-1/p2). ... + * where p1,p2... are prime factors. + * Hence Implementation in O(sqrt(n)). + * phi(100) = 40 + * phi(1) = 1 + * phi(17501) = 15120 + * phi(1420) = 560 + */ -Euler Totient Function also know as phi function. - -phi(n) = phi(p1^a1).phi(p2^a2)... -where p1, p2,... are prime factor of n. - -3 Euler's Property: -1. phi(prime_no) = prime_no-1 -2. phi(prime_no^k) = (prime_no^k - prime_no^(k-1)) -3. phi(a,b) = phi(a). phi(b) where a and b are relative primes. - -Applying this 3 property on the first equation. -phi(n) = n. (1-1/p1). (1-1/p2). ... -where p1,p2... are prime factors. - -Hence Implementation in O(sqrt(n)). - -*/ - -/// Function to caculate euler totient function +// Function to caculate Euler's totient phi int phiFunction(int n) { int result = n; - for (int i=2; i*i <= n; i++) { - if (n%i == 0) { - while (n%i == 0) { + for (int i = 2; i * i <= n; i++) { + if (n % i == 0) { + while (n % i == 0) { n /= i; } - result -= result/i; + result -= result / i; } } - if (n > 1) result -= result/n; + if (n > 1) result -= result / n; return result; }