Skip to content

Commit f80b6cd

Browse files
committed
Add Euler's totient function implementation - Implements φ(n) using prime factorization method
- Includes comprehensive tests for small numbers, primes, prime powers, and larger values - All tests pass and follows project naming conventions
1 parent 95d47cd commit f80b6cd

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

src/number_theory/euler_totient.rs

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
pub fn euler_totient(n: u64) -> u64 {
2+
if n == 1 {
3+
return 1;
4+
}
5+
6+
let mut result = n;
7+
let mut num = n;
8+
let mut p = 2;
9+
10+
// Find all prime factors and apply formula
11+
while p * p <= num {
12+
// Check if p is a divisor of n
13+
if num % p == 0 {
14+
// If yes, then it is a prime factor
15+
// Apply the formula: result = result * (1 - 1/p)
16+
while num % p == 0 {
17+
num /= p;
18+
}
19+
result -= result / p;
20+
}
21+
p += 1;
22+
}
23+
24+
// If num > 1, then it is a prime factor
25+
if num > 1 {
26+
result -= result / num;
27+
}
28+
29+
result
30+
}
31+
32+
#[cfg(test)]
33+
mod tests {
34+
use super::*;
35+
36+
#[test]
37+
fn test_small_numbers() {
38+
assert_eq!(euler_totient(1), 1);
39+
assert_eq!(euler_totient(2), 1);
40+
assert_eq!(euler_totient(3), 2);
41+
assert_eq!(euler_totient(4), 2);
42+
assert_eq!(euler_totient(5), 4);
43+
assert_eq!(euler_totient(6), 2);
44+
}
45+
46+
#[test]
47+
fn test_prime_numbers() {
48+
// For prime p, φ(p) = p - 1
49+
assert_eq!(euler_totient(7), 6);
50+
assert_eq!(euler_totient(11), 10);
51+
assert_eq!(euler_totient(13), 12);
52+
assert_eq!(euler_totient(17), 16);
53+
}
54+
55+
#[test]
56+
fn test_prime_powers() {
57+
// For prime power p^k, φ(p^k) = p^(k-1) * (p-1)
58+
assert_eq!(euler_totient(9), 6); // 3^2, φ(9) = 3^1 * 2 = 6
59+
assert_eq!(euler_totient(25), 20); // 5^2, φ(25) = 5^1 * 4 = 20
60+
assert_eq!(euler_totient(8), 4); // 2^3, φ(8) = 2^2 * 1 = 4
61+
}
62+
63+
#[test]
64+
fn test_larger_numbers() {
65+
assert_eq!(euler_totient(10), 4);
66+
assert_eq!(euler_totient(12), 4);
67+
assert_eq!(euler_totient(100), 40);
68+
assert_eq!(euler_totient(1000), 400);
69+
}
70+
}

src/number_theory/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
mod compute_totient;
2+
mod euler_totient;
23
mod kth_factor;
34

45
pub use self::compute_totient::compute_totient;
6+
pub use self::euler_totient::euler_totient;
57
pub use self::kth_factor::kth_factor;

0 commit comments

Comments
 (0)