Recursive function For counting all the perfect number from 1 to n.


What is a perfect number?


 A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For instance, 6 has divisors 1, 2 and 3 (excluding itself), and 1 + 2 + 3 = 6, so 6 is a perfect number.




 C program to count all perfect numbers from 1to N.



#include"stdio.h"


int perfect(int num)

{

    /* function to check number is perfect or not*/


    if(num<1)

    {

        return 0;

    }

    int i, sum, n;


    sum = 0;


    n = num;


    for(i=1; i<n; i++)

    {

        /* If i is a divisor of num */

        if(n%i == 0)

        {

            sum += i;

        }

    }


    if(num==sum)

    {

        printf("number is %d\n",num);


        /* recursive call to perfect function to check next number */


        return 1+perfect(num-1);

    }

    else

    {

        return 0+perfect(num-1);

    }

}

void main()

{

    int num;

    printf("Enter the number");


    scanf("%d",&num);


    printf("counting number %d",perfect(num));


}



The output of the program:


Comments

Popular posts from this blog

ML sem 4 2021

Logistic Discriminant Analysis