In this C program, we will check whether a number is magic number or not.
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.
#include<stdio.h>
int getReverse(int num);
int getSumOfDigit(int num);
int main () {
int num, digitSum, reverse;
printf("Enter a number\n");
scanf("%d", &num);
digitSum = getSumOfDigit(num);
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);
}
return 0;
}
int getReverse(int num) {
int r = 0;
while (num > 0) {
r = (r * 10) + (num % 10);
num = num / 10;
}
return r;
}
int getSumOfDigit(int num){
int sum = 0;
while(num != 0){
sum = sum + num%10;
num = num/10;
}
return sum;
}
Output
Enter a number 1234 1234 is not a Magic Number
Enter a number 1729 1729 is a Magic Number
Related Topics