Project Euler Problem 10 Solution

Do you need “Project Euler Problem 10 Solution c sharp” . We will discuss all the problems in Project Euler and try to solve them using Python or C#. I have solved Project Euler Problem 9 C Sharp as well.

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

So we have to solve this problem using C#.

Lets first of all open Visual Code.

If we analyze the problem statement given here, we can see that we are asked to find the sum of all the prime numbers below two million.

Project Euler Problem 10 Solution C Sharp 

Lets start! 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            double sum = 0;
            int count = 2;
            while(count < 2000000){
                if(isPrime(count))
                    sum += count;
                count++;
            }
            
            Console.WriteLine(sum);
            
        }
        
        static bool isPrime(int a){
            for(int i = 2; i<=Math.Sqrt(a); i++) 
                if (a % i == 0) 
                    return false;
            return true;
        }
    }
}

 

For such type of problems the first thing that hit my mind was Brute Force! Obviously!

I put a while loop from 2 (because two is the smallest prime number;) ) till count < 2 Million.

Then I made a special function to return a boolean by checking the mere condition of isPrime.

I checked for each element by brute force and got my answer right there and then.

Yaay! We got this right. Thanks for reading.

Happy coding!