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.
import java.util.Scanner; public class Main { public static int getSumOfDigits(int number) { int sumOfDigits = 0; while(number != 0) { sumOfDigits = sumOfDigits + (number % 10); number = number/10; } return sumOfDigits; } public static void main(String args[]) { System.out.println("Please enter the number you want to be checked."); Scanner scan = new Scanner(System.in); int number = scan.nextInt(); int savedNumber = number; while(number > 9) // while the number is more than 1 digit long. { number = getSumOfDigits(number); // recursively sum the digits of the number. } if(number == 1) { System.out.println(savedNumber + " is a Magic Number."); } else { System.out.println(savedNumber + " is NOT a Magic number."); } } }
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.
import java.util.Scanner; public class Main { public static void main(String args[]) { System.out.println("Please enter the number you want to be checked."); Scanner scan = new Scanner(System.in); int number = scan.nextInt(); if(number % 9 == 1) { System.out.println(number + " is a Magic Number."); } else { System.out.println(number + " is NOT a Magic number."); } } }
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.