Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

C# Sharp Exercises: Compute the sum of the first 500 prime numbers

C# Sharp Basic: Exercise-26 with Solution

Write a C# program to compute the sum of the first 500 prime numbers.

C# Sharp Exercises: Compute the sum of the first 500 prime numbers

Sample Solution:-

C# Sharp Code:

using System;  
public class Exercise26
{  
    public static void Main() 
      {     
          Console.WriteLine("\nSum of the first 500 prime numbers: ");
           long sum = 0;
            int ctr = 0;
            int n = 2;
            while (ctr < 500)
              {
                if (isPrime(n))
                {
                    sum += n;
                    ctr++;
                }
                n++;
            }

            Console.WriteLine(sum.ToString());
                    
    }
     public static bool isPrime(int n)
        {
            int x = (int)Math.Floor(Math.Sqrt(n));

            if (n == 1) return false;
            if (n == 2) return true;

            for (int i = 2; i <= x; ++i)
            {
                if (n % i == 0) return false;
            }

            return true;
        }
}

Sample Output:

Sum of the first 500 prime numbers:                   
824693 

Flowchart:

Flowchart: C# Sharp Exercises - Compute the sum of the first 500 prime numbers

C# Sharp Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a C# program to print the odd numbers from 1 to 99. Prints one number per line.
Next: Write a C# program and compute the sum of the digits of an integer.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.