GeeksforGeeks App
Open App
Browser
Continue

Related Articles

• Write an Interview Experience
• Mathematical Algorithms

Check if a number is a Krishnamurthy Number or not

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.
Recommended Practice

The idea is simple, we compute the sum of factorials of all digits and then compare the sum with n.

C++

 // C++ program to check if a number// is a krishnamurthy number#include using namespace std; // Function to calculate the factorial of any numberint factorial(int n){    int fact = 1;    while (n != 0) {        fact = fact * n;        n--;    }    return fact;} // function to Check if number is krishnamurthybool isKrishnamurthy(int n){    int sum = 0;     int temp = n;    while (temp != 0) {        // calculate factorial of last digit        // of temp and add it to sum        sum += factorial(temp % 10);         // replace value of temp by temp/10        temp = temp / 10;    }     // Check if number is krishnamurthy    return (sum == n);} // Driver codeint main(){    int n = 145;    if (isKrishnamurthy(n))        cout << "YES";    else        cout << "NO";    return 0;}

Java

 // Java program to check if a number// is a krishnamurthy number.import java.util.*;import java.io.*; class Krishnamurthy {    // function to calculate the factorial    // of any number    static int factorial(int n)    {        int fact = 1;        while (n != 0) {            fact = fact * n;            n--;        }        return fact;    }     // function to Check if number is krishnamurthy    static boolean isKrishnamurthy(int n)    {        int sum = 0;         int temp = n;        while (temp != 0) {            // calculate factorial of last digit            // of temp and add it to sum            sum += factorial(temp % 10);             // replace value of temp by temp/10            temp = temp / 10;        }         // Check if number is krishnamurthy        return (sum == n);    }     // Driver code    public static void main(String[] args)    {        int n = 145;        if (isKrishnamurthy(n))            System.out.println("YES");        else            System.out.println("NO");    }}

Python3

 # Python program to check if a number# is a krishnamurthy number # function to calculate the factorial# of any numberdef factorial(n) :    fact = 1    while (n != 0) :        fact = fact * n        n = n - 1    return fact # function to Check if number is# krishnamurthy/specialdef isKrishnamurthy(n) :    sum = 0    temp = n    while (temp != 0) :         # calculate factorial of last digit        # of temp and add it to sum        rem = temp%10        sum = sum + factorial(rem)         # replace value of temp by temp / 10        temp = temp // 10             # Check if number is krishnamurthy    return (sum == n) # Driver coden = 145if (isKrishnamurthy(n)) :    print("YES")else :    print("NO")  # This code is contributed by Prashant Aggarwal



C#

 // C# program to check if a number// is a krishnamurthy number.using System; class GFG {         // function to calculate the    // factorial of any number    static int factorial(int n)    {        int fact = 1;                 while (n != 0) {            fact = fact * n;            n--;        }                 return fact;    }     // function to Check if number is    // krishnamurthy    static bool isKrishnamurthy(int n)    {        int sum = 0;         int temp = n;        while (temp != 0) {                         // calculate factorial of            // last digit of temp and            // add it to sum            sum += factorial(temp % 10);             // replace value of temp            // by temp/10            temp = temp / 10;        }         // Check if number is        // krishnamurthy        return (sum == n);    }     // Driver code    public static void Main()    {        int n = 145;        if (isKrishnamurthy(n))            Console.Write("YES");        else            Console.Write("NO");    }} // This code is contributed by nitin mittal.

PHP



Output

YES

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.

1.   The declaration int factorial[10]; creates an array factorial of 10 integers to store the precomputed factorials.
2.   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.
3.   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.
4.   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).
5.   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.
6.    In the main() function, we call precomputeFactorials() to precompute the factorials of numbers 0 to 9 and store them in the factorial array.
7.    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.
8.    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.

C++

 #include using namespace std; int factorial[10]; void precomputeFactorials() {    factorial[0] = 1;    for (int i = 1; i < 10; i++) {        factorial[i] = i * factorial[i-1];    }} bool isKrishnamurthy(int n) {    int sum = 0;    int temp = n;    while (temp > 0) {        int digit = temp % 10;        sum += factorial[digit];        temp /= 10;    }    return (sum == n);} int main() {    precomputeFactorials();    int n = 145;    if (isKrishnamurthy(n)) {        cout <<"YES" << endl;    } else {        cout <<"NO" << endl;    }    return 0;}

Java

 // This is the Java code which checks if a given// number is a Krishnamurthy number or not.//A Krishnamurthy number is a number whose sum of factorials// of its digits is equal to the number itself import java.util.Arrays; public class KrishnamurthyNumber {     // Declare an array to store factorials of digits 0-9    static int[] factorial = new int[10];     // Function to precompute the factorials and store them    // in the array    public static void precomputeFactorials()    {        factorial[0] = 1;        for (int i = 1; i < 10; i++) {            factorial[i] = i * factorial[i - 1];        }    }     // Function to check if a given number is a    // Krishnamurthy number or not    public static boolean isKrishnamurthy(int n)    {        int sum = 0;        int temp = n;        // Compute the sum of factorials of digits of the        // number        while (temp > 0) {            int digit = temp % 10;            sum += factorial[digit];            temp /= 10;        }        // Check if the sum of factorials is equal to the        // input number        return (sum == n);    }     public static void main(String[] args)    {        // Compute the factorials using        // precomputeFactorials() function        precomputeFactorials();        int n = 145;        // Check if 145 is a Krishnamurthy number using        // isKrishnamurthy() function        if (isKrishnamurthy(n)) {            System.out.println("YES");        }        else {            System.out.println("NO");        }    }}

Python3

 # Precompute factorials of digits 0-9factorial = [1] * 10def precompute_factorials():    for i in range(1, 10):        factorial[i] = i * factorial[i-1] precompute_factorials() # Check if a number is a Krishnamurthy numberdef is_krishnamurthy(n):    # Compute sum of factorials of digits    sum = 0    temp = n    while temp > 0:        digit = temp % 10        sum += factorial[digit]        temp //= 10     # Check if sum equals the original number    return (sum == n) # Test if a given number is a Krishnamurthy numbern = 145if is_krishnamurthy(n):    print("YES")else:    print("NO")

C#

 using System; namespace KrishnamurthyNumber{    class Program    {        static int[] factorial = new int[10];         static void precomputeFactorials()        {            factorial[0] = 1;            for (int i = 1; i < 10; i++)            {                factorial[i] = i * factorial[i - 1];            }        }         static bool isKrishnamurthy(int n)        {            int sum = 0;            int temp = n;            while (temp > 0)            {                int digit = temp % 10;                sum += factorial[digit];                temp /= 10;            }            return (sum == n);        }         static void Main(string[] args)        {            precomputeFactorials();            int n = 145;            if (isKrishnamurthy(n))            {                Console.WriteLine("YES");            }            else            {                Console.WriteLine("NO");            }        }    }}

Javascript

 let factorial = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]; function precomputeFactorials() {for (let i = 1; i < 10; i++) {factorial[i] = i * factorial[i-1];}} function isKrishnamurthy(n) {let sum = 0;let temp = n;while (temp > 0) {let digit = temp % 10;sum += factorial[digit];temp = Math.floor(temp / 10);}return (sum === n);} precomputeFactorials();let n = 145;if (isKrishnamurthy(n)) {console.log("YES");} else {console.log("NO");}

Output

YES

Time Complexity: O(logN)
Auxiliary Space: O(1)

This article is contributed by DANISH KALEEM. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.