Skip to content

Commit 364f014

Browse files
feat: add Krishnamurthy number algorithm
1 parent 5c39e87 commit 364f014

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎Maths/KrishnamurthyNumber.js‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @function isKrishnamurthyNumber
3+
* @description A Krishnamurthy number (also called a Strong number) is a
4+
* number whose sum of factorials of its digits equals the number itself.
5+
* For example, 145: 1! + 4! + 5! = 1 + 24 + 120 = 145.
6+
* @param {number} n - A positive integer
7+
* @returns {boolean} - True if n is a Krishnamurthy number, false otherwise
8+
* @see https://en.wikipedia.org/wiki/Krishnamurthy_number
9+
* @example isKrishnamurthyNumber(145) => true
10+
* @example isKrishnamurthyNumber(40585) => true
11+
* @example isKrishnamurthyNumber(100) => false
12+
*/
13+
const isKrishnamurthyNumber = (n) => {
14+
if (!Number.isInteger(n) || n < 1) {
15+
throw new TypeError('Input must be a positive integer')
16+
}
17+
const factorial = (num) => {
18+
if (num === 0 || num === 1) return 1
19+
let result = 1
20+
for (let i = 2; i <= num; i++) result *= i
21+
return result
22+
}
23+
const sum = String(n)
24+
.split('')
25+
.reduce((acc, d) => acc + factorial(Number(d)), 0)
26+
return sum === n
27+
}
28+
29+
export { isKrishnamurthyNumber }
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { isKrishnamurthyNumber } from '../KrishnamurthyNumber.js'
2+
3+
describe('isKrishnamurthyNumber', () => {
4+
test('1 is a Krishnamurthy number (1!=1)', () => {
5+
expect(isKrishnamurthyNumber(1)).toBe(true)
6+
})
7+
8+
test('2 is a Krishnamurthy number (2!=2)', () => {
9+
expect(isKrishnamurthyNumber(2)).toBe(true)
10+
})
11+
12+
test('145 is a Krishnamurthy number (1!+4!+5!=145)', () => {
13+
expect(isKrishnamurthyNumber(145)).toBe(true)
14+
})
15+
16+
test('40585 is a Krishnamurthy number', () => {
17+
expect(isKrishnamurthyNumber(40585)).toBe(true)
18+
})
19+
20+
test('100 is NOT a Krishnamurthy number', () => {
21+
expect(isKrishnamurthyNumber(100)).toBe(false)
22+
})
23+
24+
test('123 is NOT a Krishnamurthy number', () => {
25+
expect(isKrishnamurthyNumber(123)).toBe(false)
26+
})
27+
28+
test('10 is NOT a Krishnamurthy number', () => {
29+
expect(isKrishnamurthyNumber(10)).toBe(false)
30+
})
31+
32+
test('throws TypeError for zero', () => {
33+
expect(() => isKrishnamurthyNumber(0)).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for negative input', () => {
37+
expect(() => isKrishnamurthyNumber(-145)).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for float input', () => {
41+
expect(() => isKrishnamurthyNumber(14.5)).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)