forked from dharmanshu9930/Website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Krishnamurthy.java
63 lines (51 loc) · 2.07 KB
/
Krishnamurthy.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Program for Krishnamurthy number
//import required classes and packages
import Java.util.*;
import java.io.*;
import java.util.Scanner;
//create KrishnamurthyNumber class to check whether the given number is a Krishnamurthy number or not
class KrishnamurthyNumber {
// 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 that returns true when it founds number krishnamurthy
static boolean checkNumber(int number)
{
int sum = 0; //initialize sum to 0
int tempNumber = number; //create a copy of the original number
//perform operation until tempNumber will not equal to 0
while (tempNumber != 0) {
// calculate the factorial of the last digit of the tempNumber and then add it to the sum
sum = sum + fact(tempNumber % 10);
// replace the value of tempNumber by tempNumber/10
tempNumber = tempNumber / 10;
}
// Check whether the number is equal to the sum or not. If both are equal, number is krishnamurthy number
if(sum == number)
return true;
else
return false;
}
// main() method start
public static void main(String[] args)
{
int n; //initialize variable n
//create scanner class object to read data from user
Scanner sc = new Scanner(System.in);
//custom message
System.out.println("Enter any number:");
//store user entered value into variable n
n = sc.nextInt();
if (checkNumber(n))
System.out.println(n + " is a krishnamurthy number");
else
System.out.println(n + "is not a krishnamurthy number");
}
}