C Program to Check Whether a Number is Magic Number or Not

  • Write a C program to check whether a number is magic number or not.
  • Algorithm to check magic number.

Here is the algorithm to check whether a number is magic number or not

  • Take a number N as input from user.
  • Find the sum of the digits of N(Lets call it digitSum).
  • Reverse the digits of digitSum(Lets call it reverse).
  • If product of digitSum and reverse is equal to the original number N, then N is magic number otherwise not a magic number.

C program to check whether a number is magic number or not

This program implements the above mentioned algorithm to check a number is magic number or not. It user two user defined helper function:

  • getReverse : Reverses the digits if passed number and returns it.
  • getSumOfDigit : Returns the sum of digits of passed number.

C Program to Check Whether a Number is Magic Number or Not

/*
* C program to check a number is magic number or not 
*/
#include<stdio.h>
#include<conio.h>
 
int getReverse(int num);
int getSumOfDigit(int num);
 
int main () {
    int num, digitSum, reverse;
 
    printf("Enter a number\n");
    scanf("%d", &num);
 
    /* get sum of digits of input number */
    digitSum = getSumOfDigit(num);
 
    /* reverse the digits of digitSum*/
    reverse = getReverse(digitSum);
 
    if ((digitSum * reverse) == num) {
        printf("%d is a Magic Number\n", num);
    } else {
        printf("%d is not a Magic Number\n", num);
    }
 
    getch();
    return 0;
  }
   
/* Function to reverse an integer  */
int getReverse(int num) {
    int r = 0;
    while (num > 0) {
        r = (r * 10) + (num % 10);
        num = num / 10;
    }
    return r;
  }
   
/* Function to calculate sum of digits of a number*/
int getSumOfDigit(int num){
    int sum = 0;
    while(num != 0){
        /* num%10 gives least significant digit of num */
        sum = sum + num%10;
        num = num/10; 
    }
    return sum;
}

Program Output

Enter a number
1234
1234 is not a Magic Number
Enter a number
1729
1729 is a Magic Number