Thursday, April 10, 2014

Project Euler Solution using C#: Problem 10: Summation Of Primes

Problem:

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.
My Solution:

  1. static void Main(string[] args)
  2. {
  3. bool isPrime = false;
  4. long limit = 2000000;
  5. long ans = 2;
  6. for (long i = 3; i < limit; i += 2)
  7. {
  8. for (long j = 2; j < i; j++)
  9. {
  10. if (i % j != 0 && i != j)
  11. {
  12. isPrime = true;
  13. }
  14. else
  15. {
  16. isPrime = false;
  17. break;
  18. }
  19. }
  20.  
  21. if (isPrime)
  22. {
  23. Console.Clear();
  24. ans += i;
  25. Console.WriteLine(ans);
  26. }
  27. }
  28. Console.WriteLine("The sum of all the primes below " + limit + " is : " + ans);
  29. Console.ReadLine();
  30. }

Note: You can simplifies the coding :)

No comments:

Post a Comment