This blog is under construction

Tuesday, 9 July 2013

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

What is a magic number?
Example: 1729

  • Find the sum of digits of the given number.(1 + 7 + 2 + 9 => 19)
  • Reverse of digit sum output.  Reverse of 19 is 91
  • Find the product of digit sum and the reverse of digit sum.(19 X 91 = 1729)
  • If the product value and the given input are same, then the given number is a magic number.(19 X 91 <=> 1729)
  • So, 1729 is a magic number.


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


  #include <stdio.h>

  /* sum of digits of a number */
  int sumOfDigits(int num) {
        int sum = 0;
        while (num > 0) {
                sum = sum + (num % 10);
                num = num / 10;
        }
        return sum;
  }

  /* returns reverse of a given number */
  int reverse(int num) {
        int rev = 0;
        while (num > 0) {
                rev = (rev * 10) + (num % 10);
                num = num / 10;
        }
        return rev;
  }

  int main () {
        int num, sum, rev;

        /* get the input value from the user */
        printf("Enter the value for num:");
        scanf("%d", &num);

        /* find sum of digits */
        sum = sumOfDigits(num);

        /*
         * if the value is single digit, then
         * the value and its reverse are same
         */
        if (sum < 10) {
                if ((sum * sum) == num) {
                        printf("%d is a magic number\n", num);
                } else {
                        printf("%d is not a magic number\n", num);
                }
                return 0;
        }

        /* reverse of the given number */
        rev = reverse(sum);

        /* print the outputs */
        if ((sum * rev) == num) {
                printf("%d is a magic number\n", num);
        } else {
                printf("%d is not a magic number\n", num);
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the value for num:1729
  1729 is a magic number



See Also:

No comments:

Post a Comment