Skip to content

Commit b7b7dbb

Browse files
feat: add Euler totient function algorithm
1 parent 5c39e87 commit b7b7dbb

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

‎Maths/EulerTotient.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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 }

‎Maths/test/EulerTotient.test.js‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
})

0 commit comments

Comments
 (0)