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


Sum of prime numbers from 1 to N in c#


 public int SumOfPrimeNumberUptoN(int loopNumber) {
           List<string> collection = new List<string>();
           int count=0, sum = 0;
           for (int num = 1; num <= loopNumber; num++)
           {
               count = 0;
               for (int i = 2; i <= num/2; i++)
               {
                   if (num % i == 0) {
                       count++;
                       break;
                   }
               }
               if (count==0 && num !=1 )
               {
                   collection.Add(num.ToString());
                   sum = sum + num;
               }
           }
           return sum;
       }
   [TestMethod]
       public void TestSumOfPrimeNumberUptoN()
       {
           BasicProgramming basicProgramming
= new BasicProgramming();
           int output = basicProgramming
.SumOfPrimeNumberUptoN(100);
           Assert.AreEqual(1060, output);
       }

Prime number- A number that is divisible only by itself
and 1 (e.g. 2, 3, 5, 7, 11).
They must have exactly two factors.


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public int SumOfPrimeNumberUptoN(int loopNumber) {
List<string> collection = new List<string>();
int count=0, sum = 0;
for (int num = 1; num <= loopNumber; num++)
{
count = 0;
for (int i = 2; i <= num/2; i++)
{
if (num % i == 0) {
count++;
break;
}
}
if (count==0 && num !=1 )
{
collection.Add(num.ToString());
sum = sum + num;
}
}
return sum;
}

Comments

Popular posts from this blog

4 - Perfect number in c sharp