20_10

Write C code to check the number is a Perfect Number. A function isPerfect is used here.

 Source code:

/*A perfect number is a positive integer which is equal to the sum of it's positive divisors excluding the number itself e.g 6 is first perfect number because it's proper divisors are 1,2 and 3 so sum 1+2+3=6.  Using a function, write C code to check the number is a Perfect Number. A function isPerfect is used here.  */


#include <stdio.h>

int isPerfect(int num);

int isPerfect(int num)

{

    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;

        }

    }

    return (num == sum);

}


int main()

{

int num;

printf("Enter a number:");

    scanf("%d", &num);

    

    if(isPerfect(num))

    {

        printf("%d is Perfect Number", num);

    }

    else

    {

        printf("%d is not Perfect Number", num);

    }

    return 0;

}

Output:


No comments:

Post a Comment

Write a program in C to convert a decimal number to binary using recursion.

 Source code: //Write a program in C to convert a decimal number to binary using recursion. #include<stdio.h> long convertB_to_D(int d...