diff --git a/Maths/EulersTotientFunction.js b/Maths/EulersTotientFunction.js new file mode 100644 index 000000000..90fd27450 --- /dev/null +++ b/Maths/EulersTotientFunction.js @@ -0,0 +1,28 @@ +/* + author sandyboypraper + + Here is the EulerTotientFunction. + it is also represented by phi + + so EulersTotientFunction(n) (or phi(n)) is the count of numbers in {1,2,3,....,n} that are relatively + prime to n, i.e., the numbers whose GCD (Greatest Common Divisor) with n is 1. +*/ + +const gcdOfTwoNumbers = (x, y) => { + // x is smaller than y + // let gcd of x and y is gcdXY + // so it devides x and y completely + // so gcdXY should also devides y%x (y = gcdXY*a and x = gcdXY*b and y%x = y - x*k so y%x = gcdXY(a - b*k)) + // and gcd(x,y) is equals to gcd(y%x , x) + return x === 0 ? y : gcdOfTwoNumbers(y % x, x) +} + +const eulersTotientFunction = (n) => { + let countOfRelativelyPrimeNumbers = 1 + for (let iterator = 2; iterator <= n; iterator++) { + if (gcdOfTwoNumbers(iterator, n) === 1) countOfRelativelyPrimeNumbers++ + } + return countOfRelativelyPrimeNumbers +} + +export { eulersTotientFunction } diff --git a/Maths/test/EulersTotientFunction.test.js b/Maths/test/EulersTotientFunction.test.js new file mode 100644 index 000000000..2b8d6c475 --- /dev/null +++ b/Maths/test/EulersTotientFunction.test.js @@ -0,0 +1,11 @@ +import { eulersTotientFunction } from '../EulersTotientFunction' + +describe('eulersTotientFunction', () => { + it('is a function', () => { + expect(typeof eulersTotientFunction).toEqual('function') + }) + it('should return the phi of a given number', () => { + const phiOfNumber = eulersTotientFunction(10) + expect(phiOfNumber).toBe(4) + }) +}) diff --git a/package-lock.json b/package-lock.json index d8c7400ba..f051f1f03 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9625,4 +9625,4 @@ } } } -} \ No newline at end of file +} diff --git a/package.json b/package.json index 3adff89e6..729e6f71b 100644 --- a/package.json +++ b/package.json @@ -27,4 +27,4 @@ "jest": "^26.4.2", "standard": "^14.3.4" } -} \ No newline at end of file +}