File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /**
2+ * @function eulerTotient
3+ * @description Euler's totient function counts the positive integers up to n
4+ * that are relatively prime to n (i.e., gcd(k, n) = 1).
5+ * @param {number } n - A positive integer greater than 0
6+ * @returns {number } - Count of integers from 1 to n coprime to n
7+ * @see https://en.wikipedia.org/wiki/Euler%27s_totient_function
8+ * @example eulerTotient(9) => 6
9+ * @example eulerTotient(1) => 1
10+ */
11+ const eulerTotient = ( n ) => {
12+ if ( ! Number . isInteger ( n ) || n < 1 ) {
13+ throw new TypeError ( 'Input must be a positive integer' )
14+ }
15+ let result = n
16+ let p = 2
17+ let temp = n
18+ while ( p * p <= temp ) {
19+ if ( temp % p === 0 ) {
20+ while ( temp % p === 0 ) temp = Math . floor ( temp / p )
21+ result -= Math . floor ( result / p )
22+ }
23+ p ++
24+ }
25+ if ( temp > 1 ) result -= Math . floor ( result / temp )
26+ return result
27+ }
28+
29+ export { eulerTotient }
Original file line number Diff line number Diff line change 1+ import { eulerTotient } from '../EulerTotient.js'
2+
3+ describe ( 'eulerTotient' , ( ) => {
4+ test ( 'eulerTotient(1) returns 1' , ( ) => {
5+ expect ( eulerTotient ( 1 ) ) . toBe ( 1 )
6+ } )
7+
8+ test ( 'eulerTotient(2) returns 1' , ( ) => {
9+ expect ( eulerTotient ( 2 ) ) . toBe ( 1 )
10+ } )
11+
12+ test ( 'eulerTotient(9) returns 6' , ( ) => {
13+ expect ( eulerTotient ( 9 ) ) . toBe ( 6 )
14+ } )
15+
16+ test ( 'eulerTotient(10) returns 4' , ( ) => {
17+ expect ( eulerTotient ( 10 ) ) . toBe ( 4 )
18+ } )
19+
20+ test ( 'eulerTotient(36) returns 12' , ( ) => {
21+ expect ( eulerTotient ( 36 ) ) . toBe ( 12 )
22+ } )
23+
24+ test ( 'eulerTotient of a prime returns prime minus 1' , ( ) => {
25+ expect ( eulerTotient ( 7 ) ) . toBe ( 6 )
26+ expect ( eulerTotient ( 13 ) ) . toBe ( 12 )
27+ } )
28+
29+ test ( 'throws TypeError for zero' , ( ) => {
30+ expect ( ( ) => eulerTotient ( 0 ) ) . toThrow ( TypeError )
31+ } )
32+
33+ test ( 'throws TypeError for negative input' , ( ) => {
34+ expect ( ( ) => eulerTotient ( - 5 ) ) . toThrow ( TypeError )
35+ } )
36+
37+ test ( 'throws TypeError for float' , ( ) => {
38+ expect ( ( ) => eulerTotient ( 1.5 ) ) . toThrow ( TypeError )
39+ } )
40+ } )
You can’t perform that action at this time.
0 commit comments