# Magic Number in Java

Magic Number is a number whose sum of the digits when recursively added to the point that a single digit is obtained, comes out to be 1.

For example, consider the number 1882.

Sum of the digits in the first iteration for 1882: 1 + 8 + 8 + 2 = 19.

Sum of the digits in second iteration for 19: 1 + 9 = 10.

We have still not obtained a single digit sum. Let’s sum the digits again.

Sum of the digits in third iteration for 10: 1 + 0 = 1.

Eureka! The sum comes out to be 1. 1882 is indeed a Magic Number.

## Magic Number in Java

The following program checks if a given number is a Magic Number or not.

Output

Please enter the number you want to be checked.
123
123 is NOT a Magic number.

This program implements a function getSumOfDigits(), which takes a number as input and returns the sum of its digits. The while loop in the main function (while(number > 9)) runs until the number is less than or equal to 9, i.e., the number is single digit. It keeps on updating the number as the sum of itself, and we get a single digit number when the loop ends. The if statement in the end checks if the number we get after going through the while loop is 1, hence a Magic Number.

### Easter Egg

Another easy way to check if a given number is a Magic Number or not is to check if the number when divided by 9 yields the remainder 1.

The following program uses the aforementioned method.

The program checks if the remainder of the given number when divided by 9 is 1, if it is, the number is a Magic Number. If it’s not, the number is not a Magic Number. Simple, ain’t it?

The proof for the above method is outside the scope of this article, so put on your Mathematics Hat and try proving this on your own. A hint, it has something to do with the divisibility check for 9.

Comment down below if you have any queries related to Java magic number implementation.