Euler 's Totient Function | Javascript program to calculate Euler ' s ▁ Totient ▁ Function ▁ using ▁ Euler ' s product formula ; Initialize result as n ; Consider all prime factors of n and for every prime factor p , multiply result with ( 1 - 1 / p ) ; Check if p is a prime factor . ; If yes , then update n and result ; If n has a prime factor greater than sqrt ( n ) ( There can be at - most one such prime factor ) ; Driver Code
function phi ( n ) { let result = n ; for ( let p = 2 ; p * p <= n ; ++ p ) { if ( n % p == 0 ) { while ( n % p == 0 ) n /= p ; result *= ( 1.0 - ( 1.0 / p ) ) ; } } if ( n > 1 ) result *= ( 1.0 - ( 1.0 / n ) ) ; return parseInt ( result ) ; } for ( let n = 1 ; n <= 10 ; n ++ ) document . write ( ` ${ n } ${ phi ( n ) } ` ) ;