This blog is under construction

Sunday, 23 June 2013

C program to print the perfect numbers from 1 to N

What is a Perfect Number?
If the sum of positive divisors of a number(excluding the number itself) equals the same number, then the number is said to be a perfect number.

Example: 6
1, 2, 3 are the divisors of 6.
1 + 2 + 3 = 6.  So, 6 is a perfect number.

Example: 28
1, 2, 4, 7, 14 are the divisors of 28
1 + 2 + 4 + 7 + 14 = 28.  So, 28 is a perfect number.


Write a C program to print the perfect numbers from 1 to N.


  #include <stdio.h>
  int main () {
        int n, i, j, sum = 0;

        /* get the input from the user */
        printf("Enter your input:");
        scanf("%d", &n);

        /* check whether the given input is perfect no or not */
        for (i = 1; i <= n; i++) {
                for (j = 1; j <= i/2; j++) {
                        if (i % j == 0) {
                                sum = sum + j;
                        }
                }

                /* print perfect numbers alone */
                if (sum == i)
                        printf("%d ", i);

                sum = 0;
        }

        printf("\n");
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter your input:9999
  6 28 496 8128 



No comments:

Post a Comment