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.
Perfect number, a positive integer that is equal to the
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  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());
}

Comments

Popular posts from this blog

7 - Sum of prime numbers 1 to N in c sharp

4 - Perfect number in c sharp