CodersZone logo

Magic Number

A number is said to be a magic number, if the sum of its digits are calculated till a single digit recursively by adding the sum of the digits after every addition. If the single digit comes out to be 1,then the number is a magic number.
For example-
Number= 50113
=> 5+0+1+1+3=10
=> 1+0=1
This is a Magic Number
For example-
Number= 1234
=> 1+2+3+4=10
=> 1+0=1
This is a Magic Number The approach used brute force. The function keeps adding digits until a single digit sum is reached. To understand how I am calculating the sum up to a single digit.

Algorithm

  1. Declare an integer type variable and input a number from the user to store it in N.
  2. Get the sum of all digits of the original number and store it another variable A.
  3. Reverse the number of variable A and store into B.
  4. After that, multiply the values of variable A and B and store into C.
  5. Check whether C == N, then the number is a Magic Number.
  6. Else, the Number is not a Magic number.

Code

                def isMagic(n):
                sum = 0;
                
                # Note that the loop
                # continues if n is 0
                # and sum is non-zero.
                # It stops when n becomes
                # 0 and sum becomes single
                # digit.
                while (n > 0 or sum > 9):
                    if (n == 0):
                        n = sum;
                        sum = 0;
                    sum = sum + n % 10;
                    n = int(n / 10);
                    
                # Return true if
                # sum becomes 1.
                return True if (sum == 1) else False;
            
            # Driver code
            n = 1234;
            if (isMagic(n)):
                print("Magic Number");
            else:
                print("Not a magic Number");
             
            

Output

               
Input : 1234
Output : Magic Number
Input : 12345
Output : Not a magic Number
See the same program in Java See the same program in C