CheckKishnamurthyNumber [克里希纳穆尔西数]
# 介绍
克里希纳穆尔西数是一个数字,其数字的阶乘之和等于该数字本身。例如,145,每个数字的阶乘之和: 1!+ 4!+ 5! = 1 + 24 + 120 = 145
。
有趣的是,我们知道的克里希纳穆尔西数字正好有四个,即 1、2、145 和 40585。
# 实现
# JavaScript
/*
Problem statement and Explanation : https://www.geeksforgeeks.org/check-if-a-number-is-a-krishnamurthy-number-or-not-2/
krishnamurthy number is a number the sum of the all factorial of the all dights is equal to the number itself.
145 => 1! + 4! + 5! = 1 + 24 + 120 = 145
*/
// factorial utility method.
const factorial = (n) => {
let fact = 1
while (n !== 0) {
fact = fact * n
n--
}
return fact
}
/**
* krishnamurthy number is a number the sum of the factorial of the all dights is equal to the number itself.
* @param {Number} number a number for checking is krishnamurthy number or not.
* @returns return correspond boolean value, if the number is krishnamurthy number return `true` else return `false`.
* @example 145 => 1! + 4! + 5! = 1 + 24 + 120 = 145
*/
const CheckKishnamurthyNumber = (number) => {
// firstly, check that input is a number or not.
if (typeof number !== 'number') {
return new TypeError('Argument is not a number.')
}
// create a variable to store the sum of all digits factorial.
let sumOfAllDigitFactorial = 0
// convert the number to string for convenience.
let newNumber = number
// Extract number digits using the remainder method.
while (newNumber > 0) {
const lastDigit = newNumber % 10
// calculate each digit factorial.
sumOfAllDigitFactorial += factorial(lastDigit)
newNumber = Math.floor(newNumber / 10)
}
// if the sumOftheFactorial is equal to the given number it means the number is a Krishnamurthy number.
return sumOfAllDigitFactorial === number
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 参考
编辑 (opens new window)
上次更新: 2022/10/19, 17:35:33