-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathMagicnumber.java
74 lines (56 loc) · 1.96 KB
/
Magicnumber.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
64
65
66
67
68
69
70
71
72
73
/* How to determine if a number is a Magic number.
We calculate the sum of digits of the number till
we get a single digit, recursively. If the single
digit comes out to be 1, then we say that the number
is a magic number.*/
import java.util.*;
//This function checks if a number is a magic number
class Magicnumber{
static boolean magicNumber(int n){
int sum = 0;
/*We loop till the number is greater than 0 or we
get a single digit sum of the digits of the number*/
while(n>0 || sum>9){
//This is the iterating step.
if(n == 0){
n =sum;
sum = 0;
}
else{
//We find the sum of the digits of number
sum += n%10;
n = Math.floorDiv(n,10);
}
}
/*After we get a single digit sum, we check if
it 1, then it is a magic number and we return True.*/
if(sum == 1){
return true;
}
else{
return false;
}
}
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number :");
//Taking input from user
int n = scan.nextInt();
//checker
boolean check = magicNumber(n);
//If the above function returns true, it means n is Magic number
if(check == true)
System.out.println("The given number "+n+" is Magic number!");
else
System.out.println("The given number "+n+" is not Magic number!");
}
}
/*
Simple I/O :
a) Is a magic number!
Enter the number :112222
The given number 112222 is Magic number!
b) Is not a Magic number!
Enter the number :123
The given number 123 is not Magic number!
*/