cmathnumbersperfect

Displaying perfect numbers and their adders


I need help with the program to display first 4 perfect numbers in the standard output and also funciton perfect(int,int*). Arguments of this function are natural number and the adress where you neeed to write the adders (of the perfect number I suppose). Function has to return 1 if the number is perfect, and 0 if it's not. This is what I've done so far. Help please.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

int perfect(int,int*);

int main()
{
int *arr,a;
int i,j;

perfect(a,arr);
}

int perfect(int n,int *arr)
{
int lim=8128,i,sum;

for(n=1;n<=lim;n++)
{
sum=0;
for(i=1;i<n;i++)
{
if(n%i==0)
{
sum=sum+i;
}

}
if(n==sum)
printf("%d ",n);


}
}

Solution

  • I think this code is helpful for you. The perfect function returns 1 when perfect otherwise return 0. The global array divisor which is used for collecting the addr. When the perfect function returns 1 then I print the divisor array and initiate the deivisor_count =0. Please have a look:

    
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    
    int divisor[1000], deivisor_count = 0;
    
    int perfect(int n)
    {
       int sum=0, i, j = 0;
       for(i=1;i<n;i++)
        {
            if(n%i==0)
            {
               sum=sum+i;
               divisor[deivisor_count]= i;
               deivisor_count = deivisor_count + 1;
            }
        }
        if(n==sum){
            return 1;
        }
       
        return 0;
    }
    
    
    int main()
    {
       
        int i, j =0, is_perfact, n=100000, k;
        
        for (i =2 ; i<=n; i++){
             deivisor_count = 0;
             is_perfact = perfect(i);
             
             if(is_perfact == 1){
                 j = j + 1;
                 for(k = 0; k <deivisor_count; k++){
                     printf("%d", divisor[k]);
                     if (deivisor_count -1 == k){
                         printf("=");
                     }
                     else{
                         printf("+");
                     }
                 }
                 printf("%d\n", i);
             }
             if (j==4){
                 break;
             }
        }
       return 0;
    }