C program: perfect or not checking - wordsclank.in

Saturday 8 April 2017

C program: perfect or not checking

 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 (also known as its aliquot sum).
For example 28. Its divisor are 1, 2, 4, 7, 14, and 28. And the sum of its divisors i.e, 1+2+4+7+14 is also 28. So 28 is a perfect number


perfect number, perfect number in c


PROBLEM STATEMENT:

Write a program in C to check whether a number is perfect or not.





SOURCE CODE:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include

void main()

 {

   int i, num, sum = 0;

   printf("Enter the number:");

   scanf("%d", &num);

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

   {

         if(num % i == 0)

          sum = sum + i;

   }

   
    if( sum == num) 

    {

         printf("%d is perfect",num);

    }

    else

    {

         printf("%d not perfect",num);

    }

 }


OUTPUT

perfect number, perfect or not in c


Explanation

Here within the main() function first we declared two integer variable num and sum. We initialized sum as 0 .Then we display a message for the user for taking input and store it in the num variable. Then we are running a for loop from i=0 to iwithin which there is a conditional for loop. We are finding perfect divisor by checking if the remainder is zero i.e, num % i==0 then we are adding the value of i in sum  where i is divisor.Next again we are running a if-else loop to declared the as perfect or not .If the sum is equals to the number then we are printing the number as perfect else it is not perfect.

No comments:

Post a Comment