(これは宿題ではなく、私が使用している本の演習です)
「整数は、1 (ただし、数値自体ではない) を含む要素の合計が完全数であると言われます。たとえば、6 = 1 + 2 + 3 であるため、6 は完全数です。書き込み方法 Perfectパラメーター値が完全数かどうかを判断します。このメソッドは、2 から 1000 までのすべての完全数を判断して表示するアプリで使用します。各完全数の約数を表示して、その数が本当に完全数であることを確認してください。」
問題は、完全数が 1 回ではなく 2 回表示されることです。なぜこれを行うのですか?
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);
}
}
}
}
}