Krishnamurthy Number in Java

In this blog, we will learn about the Krishnamurthy Number in Java and write a program to check for the Krishnamurthy Number in Java.

What is the Krishnamurthy Number in Java?

Krishnamurthy Numbers in Java refers to the implementation and identification of numbers that meet the Krishnamurthy number criteria using the Java programming language.

A Krishnamurthy number is a non-negative integer whose factorial sum equals the number itself.

Krishnamurthy Number Example

Let’s understand Krishnamurthy Number in Java examples:

Example 1: 145

To see if 145 is a Krishnamurthy number, we add the factorials of each digit:

1! + 4! + 5! = 1 + 24 + 120 = 145

Since the sum of the factorials of its digits equals the number itself, 145 is a Krishnamurthy number. 

Example 2: 40585

Factorial sum calculation:

4! + 0! + 5! + 8! + 5! = 24 + 1 + 120 + 40320 + 120 = 40585 

Again, since the sum of its digits factorial equals the number itself, 40585 is a Krishnamurthy number.

Example 3: 123

Factorial sum:

1! + 2! + 3! = 1 + 2 + 6 = 9

 In this case, the sum of its factorials (9) does not equal the number itself (123).  As a result, 123 is not a Krishnamurthy number.

As shown in the examples, Krishnamurthy numbers have the property that the sum of their factorials equals the number itself. Identifying and comprehending these numbers can be a fun number theory exercise with practical applications in cryptography, number puzzles, and problem-solving scenarios.

Get a Complete list of Online Certification Courses in India here!

Java program to check whether a given number is a Krishnamurthy number or not

//Krishnamurthy Number in Java  
import java.util.Scanner;

public class KrishnamurthyNumEx {

   // method to Check the Krishnamurthy number
   public static boolean isKrishnamurthy(int num){

      // declare variables
      int sum = 0, lastDigit = 0;
      int tempNum = num;

      // traverse through all digits of number
      while(tempNum != 0) {
          lastDigit = tempNum % 10;
          sum += factorial(lastDigit);
          tempNum /= 10;
      }

      // compare sum and number
      if(sum == num)
          return true; 
      return false; 
   }

   // method to calculate factorial of an integer
   public static long factorial(int n) {
      long fact = 1;
      for(int i=1; i<=n; i++) {
          fact *= i;
      }
      return fact;
   }

   // main method
   public static void main(String[] args) {

      // declare variables
      int num = 0;
      boolean result = false;

      //create Scanner class object to take input
      Scanner scan = new Scanner(System.in);

      // take input from end-user
      System.out.print("Enter an integer number : ");
      num = scan.nextInt();

      // check number is Krishnamurthy number
      result = isKrishnamurthy(num);
      if(result)
          System.out.println(num +
              " is a Krishnamurthy number.");
      else
          System.out.println(num +
              " is not a Krishnamurthy number.");

      // close Scanner class object
      scan.close();
   }
}

Explanation of the code:

  • The program begins by creating a class called “KrishnamurthyNumEx.”
  • It has a method called “isKrishnamurthy” that takes an integer as input and determines whether or not it is a Krishnamurthy number.
  • Variables sum and lastDigit are declared and initialized to 0 within the “isKrishnamurthy” method, and the value of the input number is assigned to a temporary variable tempNum.
  • The program iterates through each digit of the number using a while loop. In each iteration, it extracts the last digit using the modulo operator and adds the factorial of that digit to the sum. It then divides the temporary number by ten to remove the last digit.
  • The program compares the sum to the original number after completing the loop. If they are equal, it returns true; otherwise, it returns false.
  • The program also includes a method called “factorial” that computes the factorial of a given number.
  • The program defines its main method by prompting the user to enter an integer number.
  • It reads the input into the variable “num” using a Scanner object.
  • The program then calls the “isKrishnamurthy” method with the input number and saves the result in the variable “result.”
  • Finally, based on the value of the “result” variable, it prints whether or not the input number is a Krishnamurthy number.
  • Close the Scanner object to free up system resources.

In summary, the program accepts a user-supplied integer, determines whether it is a Krishnamurthy number, and displays the result.

Output:

Enter an integer number: 145
145 is a Krishnamurthy number.

Check out our blog on Unique Number in Java here!

Java program finds and displays all the Krishnamurthy numbers in a given range

//Krishnamurthy Number in Java  
import java.util.*;   
import java.io.*;   
import java.util.Scanner;  
  
//create FindAllKrishnamurthyNumber class to get all the Krishnamurthy number in a given range  
class FindKrishnamurthyNum  
{  
    //main() method start  
    public static void main(String args[])  
    {  
        int range;  
          
        //create scanner class object  
        Scanner sc=new Scanner(System.in);  
          
        //show custom message  
        System.out.println("Enter the value of range");  
          
        //store user entered value into variable range  
        range = sc.nextInt();  
  
        for(int i = 1; i <= range; i++)  
            checkNum(i);  
    }  
  
    // create fact() method to calculate the factorial of the number   
    static int fact(int number)   
    {   
        int f = 1;   
        while (number != 0) {   
            f = f * number;   
            number--;   
        }   
        return f;   
    }   
  
    // create checkNumber() method to check krishnamurthy number  
    static void checkNum(int num)   
    {   
        int sum = 0;    //initialize sum to 0   
          
        int tempNum = num;    //create a copy of the original number   
          
        //perform operation until tempNumber will not equal to 0  
        while (tempNum != 0) {   
            // calculate the factorial of the last digit of the tempNumber and then add it to the sum  
            sum = sum + fact(tempNum % 10);   
  
            // replace the value of tempNumber by tempNumber/10   
            tempNum = tempNum / 10;   
        }   
  
        // Check whether the number is equal to the sum or not. If both are equal, the number is Krishnamurthy number  
        if(sum == num)  
            System.out.println(num + " is a krishnamurthy number");   
    }  
}  

Explanation of the code:

The program begins by importing the necessary classes and packages.

It defines a class named “FindKrishnamurthyNum” to find the Krishnamurthy numbers.

Inside the class, the main method is defined, which serves as the entry point for the program.

The program prompts the user to enter the value of the range.

It reads the input using a Scanner object and stores it in the variable “range”.

The program then iterates from 1 to the given range.

For each number, it calls the “checkNum” method to check if it is a Krishnamurthy number.

The “checkNum” method accepts an integer as input and does the following:

a. It sets the variable “sum” to 0.

b. It stores a duplicate of the original number in the variable “tempNum.”

c. It calculates the factorial of the last digit of “tempNum” and adds it to the sum using a while loop.

d. It then removes the last digit from the value of “tempNum” by dividing it by 10.

e. After the loop finishes, compare the sum to the original number. If they are equal, print the number as a Krishnamurthy number.

All numbers in the given range repeat this process.

The console displays a number if it is identified as a Krishnamurthy number.

The program has come to an end.

In summary, the program accepts a user-supplied range and finds all Krishnamurthy numbers within that range, displaying them on the console.

Output:

Enter the value of range600
1 is a krishnamurthy number
2 is a krishnamurthy number
145 is a krishnamurthy number

Also, read our blog on ISBN Number in Java!

10 Tips and Tricks for Krishnamurthy in Java

Here are 10 Tips and Tricks for the effective implementation of Krishnamurthy in Java mentioned below:

Understand the Definition: Before you begin, familiarise yourself with the definition of Krishnamurthy numbers and their properties. This ensures that your code is clear and accurate. 

Use Modular Functions: Break down the problem into modular functions to improve code readability and maintainability. Separate functions for calculating factorials, summing digits, and checking Krishnamurthy conditions will help to organize the code.

Optimize Factorial Calculations: To avoid unnecessary computations, use efficient factorial calculation techniques. Consider using memoization or dynamic programming to save and reuse factorial values.

Handle Edge Cases: Take into account edge cases such as zero and single-digit numbers, which are referred to as Krishnamurthy numbers. Implement specific conditions in your code to handle these cases appropriately.

Validate Input: Use input validation to ensure that the number entered is not a negative integer. To handle invalid input gracefully, use exception handling or conditional statements.

Implement Recursion: Utilize recursion when calculating the sum of factorials of digits. Recursion simplifies the code and handles the repetitive nature of the problem effectively.

Consider Data Types: When storing and manipulating numbers, also select appropriate data types. When dealing with large numbers, use long or BigInteger to avoid overflow errors.

Test with a Variety of Inputs: Put your implementation through its paces with a variety of inputs, including both Krishnamurthy and non-Krishnamurthy numbers. This will validate the correctness of your code and ensure that it correctly handles all scenarios.

Code Optimization: Examine your code for potential optimizations. Look for redundant calculations or loop iterations that can be moreover optimized to improve your implementation’s efficiency.

Record Your Code: In your code, include clear and concise comments that explain the logic and steps involved. Documenting your code will make it easier in the future for others (including yourself) to understand and maintain the implementation.

To conclude, this blog explored the concept of Krishnamurthy numbers in Java and provided a comprehensive understanding of their properties and implementation. It presented a Java program to check if a given number is a Krishnamurthy number, along with a program to find all Krishnamurthy numbers in a given range. Additionally, it offered ten tips and tricks for the effective implementation of Krishnamurthy numbers in Java. By following these guidelines, developers can enhance their code’s readability, correctness, and performance when dealing with Krishnamurthy numbers.

We hoped that our blog post on “Krishnamurthy Number in Java” would be informative and aid in your learning of Java programming. Explore our website Newtum to find more such coding-related blogs and courses, and keep learning with us!

About The Author

Leave a Reply