Magic number in Java

public class First {

/*
* A number is said to be a Magic number if the sum of its digits are
* calculated till a single digit is obtained by recursively adding the sum
* of its digits. If the single digit comes to be 1 then the number is a
* magic number. Example- 199 is a magic number as 1+9+9=19 but 19 is not a
* sigle digit number so 1+9=10 and then 1+0=1 which is a single digit
* number and also 1. Hence it is a magic number.
*/

void magicNumber(int num) {
int d, s;
int tt = num;
s = num;
// check num is greater than 9
while (s > 9) {
num = s;
s = 0;
while (num > 0) {
d = num % 10;
s = s + d;
num = num / 10;
}
}
if (s == 1)
System.out.println("magic number :- " + tt);
else
System.out.println("not a magic number :- " + tt);
}

public static void main(String[] args) {
new First().magicNumber(55);
}

}

No comments: