Skip to content

Commit 4c8b9d6

Browse files
committed
Phi function implemented
1 parent 78ad361 commit 4c8b9d6

File tree

3 files changed

+50
-13
lines changed

3 files changed

+50
-13
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,11 @@
6363
+ [Prime factorization](algorithms/prime.cpp)
6464
+ [Primality Test(School method)](algorithms/primality_test.cpp)
6565
+ [Miller–Rabin Primality Test](algorithms/primality_test.cpp)
66+
+ [Euler Totient (Phi Function)](algorithms/phi.cpp)
6667
+ [Extended Euclid](algorithms/extended_euclid.cpp)
6768
+ [Linear Diophatine Equation](algorithms/extended_euclid.cpp)
6869
+ [Modular Mutiplicative Inverse(using Extended Euclid)](algorithms/extended_euclid.cpp)
69-
+ [Matrix Exponenciation](algorithms/matrix_exp.xpp)
70+
+ [Matrix Exponentiation](algorithms/matrix_exp.xpp)
7071
+ [Floyd Cycle Finding Algorithm](algorithms/floyd_cycle_finding.cpp)
7172
+ [Big Integer](algorithms/big_integer.cpp)
7273
+ [Josephus Recurrence](algorithms/Josephus_Recurrence.cpp)

algorithms/phi.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// To find positive integers below n that are relatively prime
2+
// i.e. 36 = 2^3 * 3^2, Phi(36) = 36 * (1 - 1/2)* (1 - 1/3) = 12
3+
int phi (int n) {
4+
if ( n == 1 )
5+
return 0;
6+
int output = n;
7+
8+
if ( n % 2 == 0 ) {
9+
output -= (output / 2);
10+
while ( n % 2 == 0 )
11+
n /= 2;
12+
}
13+
14+
for ( int i = 3; i * i <= n; i += 2 ) { // i <= sqrtN may be ??
15+
if ( n % i == 0 ) {
16+
output -= (output / i);
17+
while ( n % i == 0 )
18+
n /= i;
19+
}
20+
}
21+
22+
if ( n > 1 )
23+
output -= (output / n);
24+
25+
return output;
26+
}
27+
28+
// using prime sieve
29+
// generate prime numbers upto certain limit using sieve/segmented sieve
30+
// sieve(sqrt(n));
31+
int phi (int n) {
32+
int phi = n;
33+
int sqrtN = sqrt(n);
34+
for(int i = 0; i < (int)primes.size() and primes[i] <= sqrtN; i++) {
35+
if(n % primes[i] == 0) {
36+
phi *= (1 - 1 / (double) primes[i]);
37+
while(n % primes[i] == 0) {
38+
n /= primes[i];
39+
}
40+
}
41+
}
42+
43+
if(n > 1) {
44+
phi *= (1 - 1 / (double) n);
45+
}
46+
47+
return phi;
48+
}

algorithms/prime.cpp

-12
Original file line numberDiff line numberDiff line change
@@ -90,16 +90,4 @@ void primeFactor2(int x, vector<pair<int, int>>& factors) {
9090
factors.push_back({p, freq});
9191
}
9292
}
93-
}
94-
95-
// primarility test
96-
bool isPrime(int x) {
97-
if(x < 2) return false;
98-
int sqrtX = sqrt(x);
99-
for(int i = 2; i <= sqrtX; i++) {
100-
if(x % i == 0) {
101-
return false;
102-
}
103-
}
104-
return true;
10593
}

0 commit comments

Comments
 (0)