Search code examples
cruntime-error

program to find perfect number : error in output . perfect number is number whose sum of factors equals the given number


#include<stdio.h>
#include<math.h>

int main()
{
 int rem, num, i, sum;

 sum=0;
 num=28;

 for(i=1;i<num;i++)
 {
     if(num%i==0)
     {
         rem=num%i;
         sum=sum+rem;
     }
 }
 
 if(sum==num)
 {  
    printf("perfect number");
 }
 else
    printf("not perfect");
}

Solution

  • why are you doing this, you need to get the total sum of all the proper divisors (proper divisor of a natural number is the divisor that is strictly less than the number) of num, but what you are doing is adding rem = num%i, which is basically always 0 as num is divisible by i what you checked in your if, so what you are doing is not making any sense

    if(num%i==0)
    {
        rem=num%i;  // here `rem` is always `0` as `num%i == 0`
        sum=sum+rem;  
    }
    

    rather your logic should be like below, as the divisor is i so you should add all the divisors (representing by the i when num is divisible by i) in your sum

    if(num%i==0)
    {
        sum = sum + i;
    }