Reputation: 9
I'm trying to create a program that will find the first five perfect numbers. It almost works but for some reason the numbers 24 and 2016 also get mixed in. I have no idea why. Heres the code:
int perfectNums, amount = 5, tries;
bool check;
public void Run()
{
perfectNums = 0;
for (int i = 1; perfectNums < amount; i++)
{
check = isPerfectNum(i);
if (check == true)
{
perfectNums++;
Console.WriteLine(i);
}
}
}
public static bool isPerfectNum(int num)
{
bool isPerfect = false;
int sum = 0;
for (int i = 1; i < num; i++)
{
if (num % i == 0)
{
sum = sum + i;
}
if (sum == num)
{
isPerfect = true;
}
}
return isPerfect;
}
}
}
Upvotes: 0
Views: 300
Reputation: 1063499
You can't deduce whether it is a perfect number until you have finished calculating the aliquot sum;
For example:
public static bool IsPerfectNum(int num)
{
int aliquotSum = 0;
for (int i = 1; i < num; i++)
{
if (num % i == 0)
{ // is a divisor
aliquotSum += i;
}
}
return aliquotSum == num;
}
(you could also probably half the number of tests - there won't be any divisors above num/2
)
Upvotes: 1
Reputation: 568
The check:
if (sum == num)
{
isPerfect = true;
}
should be outside the loop, at the bottom of your method; otherwise at a certain iteration you would get 1+2+3+4+6+8=24 but you are still processing, and the final check would have been 1+2+3+4+6+8+12!=24. Btw, I agree to just debug your code step by step in order to get the faulty part.
Upvotes: 0