We are currently working on new rules for what content should and shouldn't be allowed on this website, and are looking for feedback! See Esolang:2026 topicality proposal to view and give feedback on the current draft.
Project Euler/10
Jump to navigation
Jump to search
- This article is not detailed enough and needs to be expanded. Please help us by adding some more information.
Project Euler Problem 10 is a problem related to prime numbers. The task is to find the sum of all prime numbers below 2000000.
Implementations
C++
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main() {
const int LIMIT = 2000000;
vector<bool> is_prime(LIMIT, true);
is_prime[0] = is_prime[1] = false;
int sqrt_limit = static_cast<int>(sqrt(LIMIT));
for (int i = 2; i <= sqrt_limit; ++i) {
if (is_prime[i]) {
for (int j = i * i; j < LIMIT; j += i) {
is_prime[j] = false;
}
}
}
long long sum = 0;
for (int i = 2; i < LIMIT; ++i) {
if (is_prime[i]) {
sum += i;
}
}
cout << sum << endl;
return 0;
}
C♯
using System;
class Program
{
static void Main()
{
const int Limit = 2000000;
bool[] isPrime = new bool[Limit];
for (int i = 0; i < Limit; i++) isPrime[i] = true;
isPrime[0] = isPrime[1] = false;
int sqrtLimit = (int)Math.Sqrt(Limit);
for (int i = 2; i <= sqrtLimit; i++)
{
if (isPrime[i])
{
for (int j = i * i; j < Limit; j += i)
{
isPrime[j] = false;
}
}
}
long sum = 0;
for (int i = 2; i < Limit; i++)
{
if (isPrime[i]) sum += i;
}
Console.WriteLine(sum);
}
}
JavaScript (Node.js)
function sumPrimesBelow(limit) {
const isPrime = new Uint8Array(limit);
isPrime.fill(1);
isPrime[0] = isPrime[1] = 0;
const sqrtLimit = Math.floor(Math.sqrt(limit));
for (let i = 2; i <= sqrtLimit; i++) {
if (isPrime[i]) {
for (let j = i * i; j < limit; j += i) {
isPrime[j] = 0;
}
}
}
let sum = 0n;
for (let i = 2; i < limit; i++) {
if (isPrime[i]) {
sum += BigInt(i);
}
}
return sum;
}
const result = sumPrimesBelow(2000000);
console.log(result.toString());
Python
primes=[]
sieve=[0]*2000005
for i in range(2,2000000):
if not sieve[i]:
primes.append(i)
for j in primes:
if j*i>=2000000:
break
sieve[j*i]=1
if not i%j:
break
print(sum(primes))
Polynomix
Works in theory, but very ineffective.
1=(2 2*6.)#\l l@{l/0#\s l#&.(%s=0-) s}|.
This does not work on the answer checking in Project Euler Mirror due to a bug in that site's source that makes it literally impossible to get a correct answer.