How to find Magic Number in Java

In this article, we are going to learn to find Magic Number using Java.

Let’s first understand, what is Magic Number?

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

Output:

It is a magic number

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.

Output

It is not a magic number

That’s all about magic number in java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *