File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ Problem statement and Explanation : https://www.geeksforgeeks.org/check-if-a-number-is-a-krishnamurthy-number-or-not-2/
3
+
4
+ krishnamurthy number is a number the sum of the all fectorial of the all dights is equal to the number itself.
5
+ 145 => 1! + 4! + 5! = 1 + 24 + 120 = 145
6
+ */
7
+
8
+ // factorail utility method.
9
+ const factorial = ( n ) => {
10
+ let fact = 1
11
+ while ( n !== 0 ) {
12
+ fact = fact * n
13
+ n --
14
+ }
15
+ return fact
16
+ }
17
+
18
+ /**
19
+ * krishnamurthy number is a number the sum of the factorial of the all dights is equal to the number itself.
20
+ * @param {Number } number a number for checking is krishnamurthy number or not.
21
+ * @returns return correspond boolean vlaue, if the number is krishnamurthy number return `true` else return `false`.
22
+ * @example 145 => 1! + 4! + 5! = 1 + 24 + 120 = 145
23
+ */
24
+ const CheckKishnamurthyNumber = ( number ) => {
25
+ // firstly, check that input is a number or not.
26
+ if ( typeof number !== 'number' ) {
27
+ return new TypeError ( 'Argument is not a number.' )
28
+ }
29
+ // create a variable to store the sum of all digits factorial.
30
+ let sumOfAllDigitFactorial = 0
31
+ // convert the number to string for convenience.
32
+ String ( number ) . split ( '' ) . map ( digit => {
33
+ // split one by one digit and calculate factorial and store to the variable.
34
+ return ( sumOfAllDigitFactorial += factorial ( Number ( digit ) ) )
35
+ } )
36
+ // if the sumOftheFactorial is equal to the given number it means the number is a Krishnamurthy number.
37
+ return sumOfAllDigitFactorial === number
38
+ }
39
+
40
+ module . exports = CheckKishnamurthyNumber
You can’t perform that action at this time.
0 commit comments