Special Number in JAVA
If we add factorial of all the digits of a number is called Krishnamurty Number.
For example 145 is krishnamurthy number
Sum of factorial of each digits 145
= 1! + 4! + 5!
= 1 + 24 + 120
= 145 which is equal the entered number.
import java.io.*;
/**
* class
KrishnamurtyNumber
* @ Khurshid Md Anwar
*/
public class KrishnamurtyNumber
{
private int n;
// instance variables
private int f;
/**
* Constructor of the class
*/
public
KrishnamurtyNumber()
{
// initialise
instance variables
n = 0;
f = 1;
}
// Factorial
method
public int
fact(int x)
{
f=1;
n=x;
for(int i=1;
i<=n; i++)
{
f=f*i;
}
return f;
}
// Start of main
method
public static void
main(String args[])throws IOException
{
int a, b, n, m, s;
// Local variable within
the main method
s=0; // Initialize of s
where we will store the summation
KrishnamurtyNumber ob=new KrishnamurtyNumber ();
InputStreamReader in=new InputStreamReader (System.in);
BufferedReader
br=new BufferedReader(in);
System.out.print("Enter a number: ");
n =
Integer.parseInt(br.readLine());
m=n; // Store the n value to m
while(n!=0)
{
a = n %
10;
b =
ob.fact(a); // Call the factorialmethod for each digit
s = s + b;
n = n /
10;
}
// Checking the
Krishnamurty number
if(m == s)
{
System.out.println ("Krishnamurty number");
}
else
{
System.out.println ("Not Krishnamurty number");
}
} // Start of main method
} // end of class
Output
Enter a number: 147
Not KrishnamurtyNumber number
Enter a number: 145
KrishnamurtyNumber number
Description of the variables and method used
Serial No.
|
Variable Name
|
Data Type
|
Purpose
|
1
|
n
|
int
|
entered number
|
2
|
f
|
int
|
For storage of factorial of the each digit
|
3
|
fact()
|
int
|
Factorial method
|
4
|
in
|
InputStreamReader
|
Object of class InputStreamReader
|
5
|
br
|
BufferedReader
|
The object of class BufferedReader
|
6
|
main()
|
static void
|
Main method
|
7
|
a, b, n, m, s
|
int
|
Main method local variable
|
8
|
ob
|
object
|
The object of KrishnamurtyNumber class
|
In the above program, I've calculated factorial and the sum that factorial. After the number becomes zero I've checked the number with sum of the factorial and if it is equal to the original number then that number is called Special or Krishnamurty number.