6 - Perfect Numbers 1 to n in c sharp
Perfect numbers from 1 to N in C#
public string CheckPerfectNumberUptoN(int loopNumber)
{
List<string> collection = new List<string>();
for (int num = 1; num <= loopNumber; num++)
{
int i = 1, sum = 0;
while (i < num)
{
if (num % i == 0)
sum = sum + i;
i++;
}
if (sum == num)
{
collection.Add(num.ToString());
}
}
return string.Join(",",collection.ToArray());
}
[TestMethod]
public void TestCheckPerfectNumberUptoN()
{
BasicProgramming basicProgramming
= new BasicProgramming();
string output = basicProgramming
.CheckPerfectNumberUptoN(30);
Assert.AreEqual("6,28", output);
}
How to check by dry run method number is perfect
number or not.
sum of its proper divisors. The smallest perfect number is 6,
which is the sum of 1, 2, and 3.
Other perfect numbers are 28, 496, and 8,128.
For ex. 6
1+2+3 =6
1 | public string CheckPerfectNumberUptoN(int loopNumber) |
Comments
Post a Comment