diff --git a/Maths/KrishnamurthyNumber.js b/Maths/KrishnamurthyNumber.js new file mode 100644 index 0000000000..90c56538d3 --- /dev/null +++ b/Maths/KrishnamurthyNumber.js @@ -0,0 +1,29 @@ +/** + * @function isKrishnamurthyNumber + * @description A Krishnamurthy number (also called a Strong number) is a + * number whose sum of factorials of its digits equals the number itself. + * For example, 145: 1! + 4! + 5! = 1 + 24 + 120 = 145. + * @param {number} n - A positive integer + * @returns {boolean} - True if n is a Krishnamurthy number, false otherwise + * @see https://en.wikipedia.org/wiki/Krishnamurthy_number + * @example isKrishnamurthyNumber(145) => true + * @example isKrishnamurthyNumber(40585) => true + * @example isKrishnamurthyNumber(100) => false + */ +const isKrishnamurthyNumber = (n) => { + if (!Number.isInteger(n) || n < 1) { + throw new TypeError('Input must be a positive integer') + } + const factorial = (num) => { + if (num === 0 || num === 1) return 1 + let result = 1 + for (let i = 2; i <= num; i++) result *= i + return result + } + const sum = String(n) + .split('') + .reduce((acc, d) => acc + factorial(Number(d)), 0) + return sum === n +} + +export { isKrishnamurthyNumber } diff --git a/Maths/test/KrishnamurthyNumber.test.js b/Maths/test/KrishnamurthyNumber.test.js new file mode 100644 index 0000000000..585efddb03 --- /dev/null +++ b/Maths/test/KrishnamurthyNumber.test.js @@ -0,0 +1,43 @@ +import { isKrishnamurthyNumber } from '../KrishnamurthyNumber.js' + +describe('isKrishnamurthyNumber', () => { + test('1 is a Krishnamurthy number (1!=1)', () => { + expect(isKrishnamurthyNumber(1)).toBe(true) + }) + + test('2 is a Krishnamurthy number (2!=2)', () => { + expect(isKrishnamurthyNumber(2)).toBe(true) + }) + + test('145 is a Krishnamurthy number (1!+4!+5!=145)', () => { + expect(isKrishnamurthyNumber(145)).toBe(true) + }) + + test('40585 is a Krishnamurthy number', () => { + expect(isKrishnamurthyNumber(40585)).toBe(true) + }) + + test('100 is NOT a Krishnamurthy number', () => { + expect(isKrishnamurthyNumber(100)).toBe(false) + }) + + test('123 is NOT a Krishnamurthy number', () => { + expect(isKrishnamurthyNumber(123)).toBe(false) + }) + + test('10 is NOT a Krishnamurthy number', () => { + expect(isKrishnamurthyNumber(10)).toBe(false) + }) + + test('throws TypeError for zero', () => { + expect(() => isKrishnamurthyNumber(0)).toThrow(TypeError) + }) + + test('throws TypeError for negative input', () => { + expect(() => isKrishnamurthyNumber(-145)).toThrow(TypeError) + }) + + test('throws TypeError for float input', () => { + expect(() => isKrishnamurthyNumber(14.5)).toThrow(TypeError) + }) +})