|
| 1 | +//package Maths; |
| 2 | + |
| 3 | +/* This is a program to check if a number is a Krishnamurthy number or not. |
| 4 | +A number is a Krishnamurthy number if the sum of the factorials of the digits of the number is equal to the number itself. |
| 5 | +For example, 1, 2 and 145 are Krishnamurthy numbers. |
| 6 | +Krishnamurthy number is also referred to as a Strong number. |
| 7 | +*/ |
| 8 | + |
| 9 | +import java.io.*; |
| 10 | + |
| 11 | +public class KrishnamurthyNumber |
| 12 | +{ |
| 13 | + //returns True if the number is a Krishnamurthy number and False if it is not. |
| 14 | + public static boolean isKMurthy(int n) |
| 15 | + { |
| 16 | + //initialising the variable s that will store the sum of the factorials of the digits to 0 |
| 17 | + int s=0; |
| 18 | + //storing the number n in a temporary variable tmp |
| 19 | + int tmp=n; |
| 20 | + |
| 21 | + //Krishnamurthy numbers are positive |
| 22 | + if(n<=0) |
| 23 | + { |
| 24 | + return false; |
| 25 | + } |
| 26 | + |
| 27 | + //checking if the number is a Krishnamurthy number |
| 28 | + else |
| 29 | + { |
| 30 | + while(n!=0) |
| 31 | + { |
| 32 | + //initialising the variable fact that will store the factorials of the digits |
| 33 | + int fact=1; |
| 34 | + //computing factorial of each digit |
| 35 | + for (int i=1;i<=n%10;i++) |
| 36 | + { |
| 37 | + fact=fact*i; |
| 38 | + } |
| 39 | + //computing the sum of the factorials |
| 40 | + s=s+fact; |
| 41 | + //discarding the digit for which factorial has been calculated |
| 42 | + n=n/10; |
| 43 | + } |
| 44 | + |
| 45 | + //evaluating if sum of the factorials of the digits equals the number itself |
| 46 | + if(tmp==s) |
| 47 | + { |
| 48 | + return true; |
| 49 | + } |
| 50 | + else |
| 51 | + { |
| 52 | + return false; |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + public static void main(String args[]) throws IOException |
| 57 | + { |
| 58 | + BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); |
| 59 | + System.out.println("Enter a number to check if it is a Krishnamurthy number: "); |
| 60 | + int n=Integer.parseInt(br.readLine()); |
| 61 | + if(isKMurthy(n)) |
| 62 | + { |
| 63 | + System.out.println(n+" is a Krishnamurthy number."); |
| 64 | + } |
| 65 | + else |
| 66 | + { |
| 67 | + System.out.println(n+" is NOT a Krishnamurthy number."); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments