unique, ad-free, freemium downloads

20 November 2017

How To: A C Program to Print N Perfect Numbers

PERFECT NUMBERS:

A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself.These include 6,24,28,496,2016,etc.

Example:
6 = 1 + 2 + 3
24 = 1 + 2 + 3 + 6 + 12

CODE:

#include <stdio.h>
#include <stdlib.h>
int perfect(int num);//function prototype

int main()
{
    int num;
    printf("Please enter the number of perfects numbers:");
    scanf("%d",&num);
    perfect(num);
    system("pause");
}

int perfect(int num)//function definition
{
    int count=1;
    for(int a=1;count<=num;a++)//Loop for generating numbers from 1(until count>num) 
    {
        int c=0;//Necessary for updating c
        for(int b=1;b<a;b++)//Loop for generating 1 to (num-1)
        {
             if(a%b==0)//if a is multiple of b
             {
                c +=  b;// OR c = c + b;
                if (c==a)//condition for perfect numbers
                {
                count++;
                printf("%d\n",c);
                }
              }
         }
    }
}

OUTPUT:


No comments:

Post a Comment