w3resource

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


Sum of First 500 Primes

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;

// This is the beginning of the Exercise26 class
public class Exercise26
{
    // This is the main method where the program execution starts
    public static void Main() 
    {     
        Console.WriteLine("\nSum of the first 500 prime numbers: "); // Displaying a message

        int sum = 0; // Initializing a variable to hold the sum of prime numbers
        int ctr = 0; // Initializing a counter to count the prime numbers
        int n = 2; // Starting from the first prime number

        // Loop to find and sum the first 500 prime numbers
        while (ctr < 500)
        {
            if (isPrime(n)) // Checking if 'n' is a prime number by calling the 'isPrime' method
            {
                sum += n; // Adding the prime number 'n' to the sum
                ctr++; // Incrementing the counter of prime numbers found
            }
            n++; // Moving to the next number for evaluation
        }

        Console.WriteLine(sum); // Displaying the sum of the first 500 prime numbers
    }

    // Method to check if a number is prime
    public static bool isPrime(int n)
    {
        int x = (int)Math.Floor(Math.Sqrt(n)); // Calculating the square root of 'n'

        if (n == 1) return false; // 1 is not a prime number
        if (n == 2) return true; // 2 is a prime number

        // Loop to check if 'n' is divisible by any number from 2 to square root of 'n'
        for (int i = 2; i <= x; ++i)
        {
            if (n % i == 0) return false; // If 'n' is divisible by 'i', it's not a prime number
        }

        return true; // 'n' is prime if not divisible by any number except 1 and itself
    }
}

Sample Output:

Sum of the first 500 prime numbers:                   
824693 

Flowchart:

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

For more Practice: Solve these Related Problems:

  • Write a C# program to find the 500th prime and verify its primality using optimized trial division.
  • Write a C# program to generate the first 500 prime numbers using the Sieve of Eratosthenes and calculate their cumulative sum.
  • Write a C# program to count how many prime numbers between 2 and 5000 have their digits in ascending order.
  • Write a C# program to find the sum of the first 500 prime numbers that are also palindromes.

Go to:


PREV : Print Odd Numbers 1 to 99.
NEXT : Sum of Digits in Integer.

C# Sharp Code Editor:



What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.