A Krishnamurthy number is a number whose sum of the factorial of digits is equal to the number itself.
For example, 145 is the sum of the factorial of each digit.
1! + 4! + 5! = 1 + 24 + 120 = 145
Examples:
Input : 145
Output : YES
Explanation: 1! + 4! + 5! =
1 + 24 + 120 = 145, which is equal to input,
hence YES.
Input : 235
Output : NO
Explanation: 2! + 3! + 5! =
2 + 6 + 120 = 128, which is not equal to input,
hence NO.
The idea is simple, we compute the sum of factorials of all digits and then compare the sum with n.
Time Complexity: O(n log10n) where n is a given number
Auxiliary Space: O(1)
Interestingly, there are exactly four Krishnamurthy numbers i.e. 1, 2, 145, and 40585 known to us.
Approach 2: Precomputing factorials and checking each digit of the number against the precomputed factorials.
- The declaration int factorial[10]; creates an array factorial of 10 integers to store the precomputed factorials.
- The precomputeFactorials() function calculates and stores the factorials of numbers 0 to 9 in the factorial array. It uses a for loop to iterate through each number and calculates its factorial by multiplying it with the factorial of the previous number.
- The isKrishnamurthy(int n) function takes an integer n as input and checks if it is a Krishnamurthy number or not. It first declares a variable sum to store the sum of factorials of digits in n and a variable temp to store a copy of n.
- It then enters a while loop that continues until temp becomes zero. In each iteration of the loop, it calculates the rightmost digit of temp using the modulo operator (temp % 10) and adds the factorial of that digit to sum. It then updates the value of temp by removing the rightmost digit using integer division (temp /= 10).
- After the while loop completes, the function returns true if sum is equal to n, indicating that n is a Krishnamurthy number, or false otherwise.
- In the main() function, we call precomputeFactorials() to precompute the factorials of numbers 0 to 9 and store them in the factorial array.
- We then set n to 145, which is a Krishnamurthy number, and call isKrishnamurthy(n) to check if n is a Krishnamurthy number or not.
- Finally, we use cout to print "YES" if isKrishnamurthy(n) returns true, indicating that n is a Krishnamurthy number, or "NO" otherwise. We also use endl to insert a newline character after the output.
Time Complexity: O(logN)
Auxiliary Space: O(1)