Skip to content

Commit 7411314

Browse files
authored
Feat: add euler's totient function (#213)
1 parent f7a4b7d commit 7411314

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

maths/euler_totient.ts

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @description counts the positive integers up to a given integer n that are relatively prime to n.
3+
* @param {number} n - A natural number.
4+
* @return {number} - euler's totient.
5+
* @see https://en.wikipedia.org/wiki/Euler%27s_totient_function
6+
* @example phi(4) = 2
7+
* @example phi(5) = 4
8+
*/
9+
export const phi = (n: number): number => {
10+
let result: number = n;
11+
for (let i = 2; i * i <= n; i++) {
12+
if (n % i == 0) {
13+
while (n % i == 0) n = n / i;
14+
result -= Math.floor(result / i);
15+
}
16+
}
17+
if (n > 1) result -= Math.floor(result / n);
18+
19+
return result;
20+
};

maths/test/euler_totient.test.ts

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { phi } from "../euler_totient";
2+
3+
4+
const cases: [number, number][] = [
5+
[4, 2],
6+
[5, 4],
7+
[7, 6],
8+
[10, 4],
9+
[999, 648],
10+
[1000, 400],
11+
[1000000, 400000],
12+
[999999, 466560],
13+
[999999999999878, 473684210526240],
14+
];
15+
16+
describe("phi", () => {
17+
18+
test.each(cases)(
19+
"phi of %i should be %i",
20+
(num, expected) => {
21+
expect(phi(num)).toBe(expected);
22+
},
23+
);
24+
});

0 commit comments

Comments
 (0)