Reputation: 559
(this isn't homework, just an exercise in the book I'm using)
"An integer is said to be a perfect number if its factors, including one (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3. Write method Perfect that determines whether parameter value is a perfect number. Use this method in an app that determines and displays all the perfect numbers between 2 and 1000. Display the factors of each perfect number to confirm that the number is indeed perfect."
The problem is that it is displaying the perfect numbers twice instead of once. Why is it doing this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Perfect_Numbers2
{
class Program
{
static bool IsItPerfect(int value)
{
int x = 0;
bool IsPerfect = false;
List<int> myList = new List<int>();
for (int i = value; i == value; i++)
{
for (int j = 1; j < i; j++)
{
if (i % j == 0) // if the remainder of i divided by j is zero, then j is a factor of i
{
myList.Add(j); //add j to the list
}
}
x = myList.Sum();
// test if the sum of the factors equals the number itself (in which case it is a perfect number)
if (x == i)
{
IsPerfect = true;
foreach (int z in myList)
{
Console.Write("{0} ",z);
}
Console.WriteLine(". {0} is a perfect number", i);
}
}
return IsPerfect;
}
static void Main(string[] args)
{
bool IsItAPerfectNum = false;
for (int i = 2; i < 1001; i++)
{
IsItAPerfectNum = IsItPerfect(i);
if (IsItPerfect(i) == true)
{
Console.ReadKey(true);
}
}
}
}
}
Upvotes: 0
Views: 734
Reputation: 59035
You're calling IsItPerfect
twice, which causes it to evaluate the code in that method twice. That method writes the number to the console, so it's displaying the number twice.
You could rewrite the code as follows, which would eliminate the issue and prevent you from executing the same logic twice:
static void Main(string[] args)
{
for (int i = 2; i < 1001; i++)
{
bool IsItAPerfectNum = IsItPerfect(i);
if (IsItAPerfectNum)
{
Console.WriteLine("{0} is a perfect number", i);
Console.ReadKey(true);
}
}
}
And of course, remove the corresponding Console.WriteLine
from your ItIsPerfect
method.
Upvotes: 9
Reputation: 250
You are calling IsItPerfect(i)
twice, and it contains a Console.WriteLine()
. You need to remove the IsItPerfect(i)
before the if
. I'd also recommend removing the UI from your method altogether - its bad practice.
Upvotes: 4