Magic Number in Java
In programming, a magic number is a numeric value that is used directly in the code. It is used for identification purposes. In this section, we will discuss what is a magic number and how can we find a magic number through a Java program.
Magic Number in Programming
A magic number is a hard-coded numeric value (text value in some cases) in the code that may change at a later stage. It seems like arbitrary and has no context or meaning. It is hard to update. For example:
Using such constant can help us distinguish the files among the many other file formats. For example:
Why magic numbers should avoid?
We should not use the magic numbers in programming because it leads to an anti-pattern that makes the code difficult to understand and maintain. It also hides the intention so the use of magic numbers should be avoided. The changes in the code are also bitter harder.
It is recommended that use constant to represent values instead of using magic numbers. It improves the readability of code and provides easy modification in the code.
Magic Number in Mathematics
In mathematics, if the sum of its digits recursively is calculated till a single digit. If the single digit is 1 then the number is called a magic number. It is quite similar to the happy number.
For example, 325 is a magic number because the sum of its digits (3+2+5) is 10, and again sum up the resultant (1+0), we get a single digit (1) as the result. Hence, the number 325 is a magic number.
Some other magic numbers are 1234, 226, 10, 1, 37, 46, 55, 73, etc.
Note that if a number is a magic number then all the possible combinations of the number will also be the magic numbers.
For example, 532, 253, 325, 235, 352, 523 the sum of digits of all the numbers gives 10 and again sum up the resultant (1+0), we get a single-digit i.e. 1. Hence, we can say that the magic number and its combinations are also magic.
Let's implement the above logic in a Java program and check whether the given number is magic or not.
Java Magic Number Program
Enter a number you want to check: 325 The given number is a magic number.
Enter a number you want to check: 891 The given number is a magic number.
Let's see another logic to check the magic number.
Enter any number to check: 73 73 is a magic number.
Enter any number to check: 671 671 is not a magic number.
Magic Number vs Happy Number
The only difference between magic numbers and happy numbers is that in a magic number we sum up all the digits of the number recursively until we get a signal digit i.e. 1. While in happy number, we recursively calculate the sum of the square of digits until we get a single digit 1. If this process results in an endless cycle of numbers containing 4, then the number is called an unhappy number. For example, we have to check 19 is magic and happy number or not.
In both cases, we get 1. Hence, the number 19 is a magic number and also a happy number.