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.
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.
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.