In this article, we are going to learn to find Magic Number using Java.
Table of Contents
What is a Magic Number?
A number which leaves 1 as a result after a sequence of steps and in each step number is replaced by the sum of its digits. For example, if we check whether 163 is a Magic Number, then sequence of steps are
Step 1: 1+6+3 = 10 // Sum of square of each digit
Step 2: 1+0 = 1 (A Magic Number)
To calculate magic number, we have two approaches either using recursive approach or simple a shorthand logic. Let’s see the examples.
Algorithm for Magic Number
Step 1: Take two variables, sum for storing a sum of square and number for holding the value.
Step 2: Repeat till number greater than 0 or sum is greater than 9.
Step 3: If number is equal to 0, replace the number with the sum of the digits and set sum = 0.
Step 4: Calculate the sum of each digit present in the number and add it to the variable sum.
Step 5: If result sum is equal to 1, then the number is a Magic Number.
Step 6: Else the number is not Magic Number.
Example to find Magic Number
|
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 |
public class Main{ public static void main(String[] args) { int number = 1000; // Number to check int sum = 0; while (number > 0 || sum > 9) { if (number == 0) { number = sum; sum = 0; } sum += number % 10; number /= 10; } // If sum = 1, it is magic number if(sum == 1) { System.out.println("It is a magic number"); }else { System.out.println("It is not a magic number"); } } } |
Output:
Another Example To find Magic Number
There is another approach to find Magic Number. In this approach, we can get Magic Number after dividing a number by 9. This is a shortcut method to verify Magic Number. If we get remainder 1 after dividing a number by 9 then the number is a magic number. It is based on the concept of divisibility rule of 9 which says that if a number is divisible by 9, then sum of its all digits are also divisible by 9. An addition of 1 in the original number will increase the ultimate value by 1, making it 10 and the ultimate sum will be 1, which makes a number a magic number. See the example below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class Main{ public static void main(String[] args) { int number = 10001; // Number to check if(number % 9 == 1) { System.out.println("It is a magic number"); }else { System.out.println("It is not a magic number"); } } } |
Output
That’s all about magic number in java.