How to find the sum of all the primes below two million in C#

1 Answer

0 votes
using System;

public class Program
{
	internal static bool isPrime(int n) {
		if (n < 2 || (n % 2 == 0 && n != 2)) {
			return false;
		}

		int count = (int)Math.Floor(Math.Sqrt(n));
		for (int i = 3; i <= count; i += 2) {
			if (n % i == 0) {
				return false;
			}
		}

		return true;
	}

	public static void Main(string[] args)
	{
		long num = 2000000, sum = 0;

		for (int i = 2; i < num; i++) {
			if (isPrime(i)) {
				sum += i;
			}
		}

		Console.WriteLine("sum = " + sum);
	}
}




/*
run:
     
sum = 142913828922
     
*/

 



answered Oct 28, 2023 by avibootz

Related questions

1 answer 112 views
1 answer 141 views
1 answer 131 views
1 answer 111 views
1 answer 103 views
...