Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

c - 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");
}
question from:https://stackoverflow.com/questions/65856544/program-to-find-perfect-number-error-in-output-perfect-number-is-number-whos

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...