C Program to Print all Magic Number till N

This article shows the result of how to display all the magic numbers between 1 to nth number in C programming.

What is Magic Number?

A number is said to be a Magic Number if the sum of the digits of that number, when multiplied by the reverse number of the sum of its digits, is equal to the original number.

Example: 1729 is a magic number.

magic number

C Program to print all Magic Numbers till N.

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int num, temp, i;

  printf("Enter the last number you want to check between 1 to:");
  scanf("%d", &num);

  //loop to check all the number
  for (i = 1; i <= num; i++)
  {
    int revnum = 0;
    int sumOfDigits = 0;
    temp = i;

    //calculate sum of the digits
    while (temp > 0)
    {
      sumOfDigits += temp % 10;
      temp = temp / 10;
    }

    //reversing the digits
    temp = sumOfDigits;
    while (temp > 0)
    {
      revnum = revnum *10 + temp % 10;
      temp = temp / 10;
    }

    //displaying the result
    if (revnum *sumOfDigits == i)
      printf(" %d", i);

  }

  return 0;
}

The output of magic Number in C: