forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEulersTotientFunction.js
More file actions
Latest commit
28 lines (23 loc) · 919 Bytes
/
Copy pathEulersTotientFunction.js
File metadata and controls
28 lines (23 loc) · 919 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
author sandyboypraper
Here is the EulerTotientFunction.
it is also represented by phi
so EulersTotientFunction(n) (or phi(n)) is the count of numbers in {1,2,3,....,n} that are relatively
prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1.
*/
constgcdOfTwoNumbers=(x,y)=>{
// x is smaller than y
// let gcd of x and y is gcdXY
// so it divides x and y completely
// so gcdXY should also divide y%x (y = gcdXY*a and x = gcdXY*b and y%x = y - x*k so y%x = gcdXY(a - b*k))
// and gcd(x,y) is equal to gcd(y%x, x)
returnx===0 ? y : gcdOfTwoNumbers(y%x,x)
}
consteulersTotientFunction=(n)=>{
letcountOfRelativelyPrimeNumbers=1
for(letiterator=2;iterator<=n;iterator++){
if(gcdOfTwoNumbers(iterator,n)===1)countOfRelativelyPrimeNumbers++
}
returncountOfRelativelyPrimeNumbers
}
export{eulersTotientFunction}