如何在C中返回两个完美数字的总和

时间:2016-04-05 16:34:25

标签: c perfect-numbers

我有一个名为henry的方法,它接受两个整数参数ij,并返回ithjth完全数字的总和。例如,henry(1, 3)应返回502,因为61st perfect number4963rd perfect number6 + 496 = 502.

int henry (int i, int j)
 {
      //how do i start 
 }

我知道如何打印这样的完美数字:

int main()  
{  
    int i, j, n, sum = 0;  

    /* Reads upper limit to print perfect numbers upto */  
    printf("Enter any number to print perfect number up to: ");  
    scanf("%d", &n);  



    printf("\nAll Perfect numbers between 1 to %d:\n", n);  


    /* 
     * Iterates from 1 to n and print if it is perfect number 
     */  
    for(i=1; i<=n; i++)  
    {  
        sum = 0;  

        /* 
         * Checks whether the current number i is Perfect number or not 
         */  
        for(j=1; j<i; j++)  
        {  
            if(i%j==0)  
            {  
                sum += j;  
            }  
        }  

        /* If the current number i is Perfect number */  
        if(sum == i)  
        {  
            printf("%d is Perfect Number\n", i);  
        }  
    }  

    return 0;  
}  

请给我提示解决这个问题,谢谢。

1 个答案:

答案 0 :(得分:1)

int henry(int i,int j)
{
int count=0,k=1,s=0;
  while(count<=i || count<=j)
  {
   int sum=0;
   for(p=1; p<=k/2; p++)  
    {  
        if(k%p==0)  
        {  
            sum += p;  
        }  
    }
   if(sum==k)
   count++;
   if(count==i||count==j)
   s+=k;
   k++;
  }
if(i!=j)
return s;
else
return 2*s;
}