0

The task is: Write a program that prints the first n perfect numbers. Checking that the number is perfect should be done in the perfect function.

I did it like this:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 100
/*
*/
int perfect_number(long int n)
{
    long int sum=0;
    for(int j=1;j<n;j++)
    {
        long int candidate=j;
        if(n%candidate==0)
        {
            sum=sum+candidate;
        }
    }
    if(sum==n)
    {
        return n;
    }
    return 0;
}

int main()
{
    int n;
    printf("Enter how much perfect numbers you want :");
    scanf("%d",&n);

    while(n<1)
    {
        printf("Enter how much perfect numbers you want:");
        scanf("%d",&n);
    }

    int counter=0;

    for(long int i=1;counter<n;i++)
    {
        if(perfect_number(i))
        {
            printf("%ld ",i);
            counter++;
        }
    }
    return 0;
}

The problem arises when I type that I want, the first 5 perfect numbers or more. The program will print only 4 and will continue to work, it will search for numbers but will not print anything.

If I type in the first four perfect numbers, they will print 4 and finish the program, they will do everything right.

I thought the problem was in representing the fifth number, so I replaced int with long int, but that didn't help.

Laurel
  • 5,965
  • 14
  • 31
  • 57
PC Safe
  • 25
  • 5
  • So why don't you just debug it? Run the program in a debugger and see exactly what the program is doing. – kaylum Dec 24 '21 at 11:12
  • Its not a representation thing; your brute force algorithm will not lend itself well to finding the fifth number, which is 33550336 whatsoever. Remember, you're trying (and failing) *every* number between 8128 (the fourth number) and 33550336 with no bail-out clauses. Your actual ascension algorithm is O(N^2), and given the N you must finally reach before discovering the 5th number you're talking about roughly 5xE14 steps, or roughly 562812522856448 if you want a specific figure. – WhozCraig Dec 24 '21 at 11:18
  • How to fix it ? – PC Safe Dec 24 '21 at 11:30
  • I don't understand what you mean by "fix it". The algorithm you have will work, but will take a very long time once you pass the fourth number. Through 8128 the numbers are fairly trivial. You can make your algorithm somewhat more efficient by using an ascending square rather than ascending counter, adding both terms rather than one at a time, and early exiting the loop if the sum ever exceeds n, but outside of that you need a different approach. Such approaches dive quickly into some pretty heady math (mersenne primes and Euclid's discovery that `(2^(p-1))*(2^p − 1) ` is perfect. – WhozCraig Dec 24 '21 at 11:55

0 Answers0