FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

Feat: add euler's totient function by ayoubc · Pull Request #213 · TheAlgorithms/TypeScript · GitHub

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .ts  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
20 changes: 20 additions & 0 deletions maths/euler_totient.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/**
* @description counts the positive integers up to a given integer n that are relatively prime to n.
* @param {number} n - A natural number.
* @return {number} - euler's totient.
* @see https://en.wikipedia.org/wiki/Euler%27s_totient_function
* @example phi(4) = 2
* @example phi(5) = 4
*/
export const phi = (n: number): number => {
let result: number = n;
for (let i = 2; i * i <= n; i++) {
if (n % i == 0) {
while (n % i == 0) n = n / i;
result -= Math.floor(result / i);
}
}
if (n > 1) result -= Math.floor(result / n);

return result;
};
24 changes: 24 additions & 0 deletions maths/test/euler_totient.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { phi } from "../euler_totient";


const cases: [number, number][] = [
[4, 2],
[5, 4],
[7, 6],
[10, 4],
[999, 648],
[1000, 400],
[1000000, 400000],
[999999, 466560],
[999999999999878, 473684210526240],
];

describe("phi", () => {

test.each(cases)(
"phi of %i should be %i",
(num, expected) => {
expect(phi(num)).toBe(expected);
},
);
});

Back | FazBrowse Home | New Git URL