Skip to content

Commit f50c87e

Browse files
authored
Merge pull request TheAlgorithms#344 from c-utkarsh/add-eulers-totient
Added EulersTotient
2 parents cc2da39 + b44d5bf commit f50c87e

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Maths/EulersTotient.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Source:
3+
https://en.wikipedia.org/wiki/Euler%27s_totient_function
4+
5+
EulersTotient(n) = n * product(1 - 1/p for all prime p dividing n)
6+
7+
Complexity:
8+
O(sqrt(n))
9+
*/
10+
11+
const EulersTotient = (n) => {
12+
// input: n: int
13+
// output: phi(n): count of numbers b/w 1 and n that are coprime to n
14+
let res = n
15+
for (let i = 2; i * i <= n; i++) {
16+
if (n % i === 0) {
17+
while (n % i === 0) {
18+
n = Math.floor(n / i)
19+
}
20+
// i is a prime diving n, multiply res by 1 - 1/i
21+
// res = res * (1 - 1/i) = res - (res / i)
22+
res = res - Math.floor(res / i)
23+
}
24+
}
25+
if (n > 1) {
26+
res = res - Math.floor(res / n)
27+
}
28+
return res
29+
}
30+
31+
const main = () => {
32+
// EulersTotient(9) = 6 as 1, 2, 4, 5, 7, and 8 are coprime to 9
33+
// > 6
34+
console.log(EulersTotient(9))
35+
// EulersTotient(10) = 4 as 1, 3, 7, 9 are coprime to 10
36+
// > 4
37+
console.log(EulersTotient(10))
38+
}
39+
40+
main()

0 commit comments

Comments
 (0)