# Algorithm and Flowchart to check whether a given number is magic number or not

[1275 views]

### What are magic numbers?

A magic number is a number in which the sum of its digits when calculated recursively is equal to one. It is important to note that if a number is magic number, then all possible combinations of that number are also magic numbers.

For example:
Let us consider the number: 3214
Sum of the digits: 3+2+1+4 = 10 = 1+0 = 1
Therefore, 3214 is a magic number.
1234, 2143, 1432, etc. will also be magic numbers.

Let us consider another number: 524
Sum of the digits: 5+2+4 = 11 = 1+1 = 2
Therefore, 524 is not a magic number.

Now let’s take a look at the algorithm and flowchart to check whether a given number is a magic number or not, with the help of an algorithm and flowchart, for better understanding.

## Algorithm to check whether a number is magic number or not:

Step 1: Start Step 2: Read the number to be checked as input from the user, say ‘n’ Step 3: Initialize sum = 0 Step 4: WHILE n > 9, Step 5: Do: 5.1: WHILE n > 0, 5.2: Do: 5.2.1: rem = n % 10 5.2.2: sum = sum + rem 5.2.3: n = n / 10 5.3: End WHILE 5.4: n = sum 5.5: sum = 0 Step 6: End WHILE Step 7: IF n = 1, THEN: 7.1: Print “Magic Number” Step 8: ELSE: 8.1: Print “Not Magic Number” Step 9: End IF-ELSE Step 10: Stop

## Explanation:

To check whether a given number is a magic number or not, we have to calculate the sum of the digits of the number recursively, that is, we have to keep adding the digits of the number until we get the sum as a one-digit number. Once we calculate that, we need to check whether the final sum is equal to 1 or not.

We start this algorithm by taking the number to be checked as input from the user. Let us store it in a variable, say n. We then initialize the sum of digits as zero. To check whether the sum of digits is a one-digit number or not, we start a loop that will run until n is greater than 9. Inside this loop, we start another loop to calculate the sum of the digits of n. This loop runs until n is not equal to 0. We extract the last digit of n by doing: rem = n % 10. We then add this remainder to the sum. This remainder is removed from the original number.

This process continues until the sum of the digits, stored in n becomes a one-digit number. We then check whether n is equal to one or not. If this condition satisfies, we display that the number is a magic number. If not, we display that the number is not a magic number.

## Flowchart to check whether a number is magic number or not: ### Having Difficulty understanding above Algorithm and Flowchart? Buy our Notes

#### Are You Good enough in Algorithms?

##### Below Offers ends in   