← 输入框|github.com|刷新
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Maths/KrishnamurthyNumber.js
Original file line number Diff line number Diff line change
@@ -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 }
43 changes: 43 additions & 0 deletions Maths/test/KrishnamurthyNumber.test.js
Original file line number Diff line number Diff line change
@@ -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)
})
})
Loading