Prime Sum
Problem 10 Project Euler
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
Prime Check Snippet
static bool IsPrime(int n)
{
if (n == 2 || n == 3)
return true;
if (n < = 1 || n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i < = n; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
Full Code Snippet
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int t = Convert.ToInt32(Console.ReadLine());
for(int a0 = 0; a0 < t; a0++){
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(PrimeSum(n));
}
}
static long PrimeSum(int n)
{
long sum = 2;
if (n == 2) return 2;
for (var i = 3; i < = n; i+=2)
{
if (IsPrime(i))
{
sum += i;
}
}
return sum;
}
static bool IsPrime(int n)
{
if (n == 2 || n == 3)
return true;
if (n < = 1 || n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i < = n; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
}
Live Code On Ide One
static bool IsPrime(int n)
{
if (n == 2 || n == 3)
return true;
if (n < = 1 || n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i < = n; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
static void Main(String[] args) {
int t = Convert.ToInt32(Console.ReadLine());
for(int a0 = 0; a0 < t; a0++){
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(PrimeSum(n));
}
}
static long PrimeSum(int n)
{
long sum = 2;
if (n == 2) return 2;
for (var i = 3; i < = n; i+=2)
{
if (IsPrime(i))
{
sum += i;
}
}
return sum;
}
static bool IsPrime(int n)
{
if (n == 2 || n == 3)
return true;
if (n < = 1 || n % 2 == 0 || n % 3 == 0)
return false;
for (int i = 5; i * i < = n; i += 6)
{
if (n % i == 0 || n % (i + 2) == 0)
return false;
}
return true;
}
}
Comments
Post a Comment