{ }codelper
prime sievebrute forceP0068

Split into two primes

The first line gives the number of queries T, and each of the next T lines gives an even number n.
For each query print, on its own line, the number of ways to write n as a sum of two primes n = p + q with p ≤ q.
Swapping p and q is the same way (10 = 3 + 7 = 7 + 3 counts once).
p = q is allowed (6 = 3 + 3).
1 is not a prime.

Input
1 ≤ T ≤ 1,000, 4 ≤ n ≤ 9,000, n is even
Output
T lines, each with the number of ways
Example 1 · stdin
4
4
6
10
100
stdout
1
1
2
6
main.py
Input (stdin)

When you run, these lines are fed to input()/stdin in order (the program doesn't stop to ask).

$ Ready

Open this on a computer to write and run code. On mobile you can read the problem and the solutions.

In other languagesShow solutions by language · 8 languages

With 1,000 queries, testing each number by trial division is slow.
Find the primes up to 9,000 once with the sieve of Eratosthenes, then for each query try every p up to n/2 and look up whether n - p is prime in the table.
Building the sieve differs by language: Python [True] * (n + 1), JavaScript/TypeScript new Array(n + 1).fill(true), Java/C# new boolean[n + 1]/new bool[n + 1] (they start all false, so use them as a 'composite' table and skip filling), C static bool (only global/static arrays start at zero; a local array inside a function holds garbage), C++ std::vector<bool>(n + 1, true), Craykon NewList(n + 1, true).
Craykon lists hold at most 10,000 items, which is why n stops at 9,000.
Three common traps: not marking 0 and 1 as non-prime (counting 4 = 1 + 3), writing p < q and missing 6 = 3 + 3, and running p all the way to n so 3 + 7 and 7 + 3 are counted twice.

Pythonmain.py · 27 lines
import sys LIMIT = 9000 # 에라토스테네스의 체: is_prime[k]는 k가 소수인지is_prime = [True] * (LIMIT + 1)is_prime[0] = is_prime[1] = Falsei = 2while i * i <= LIMIT:    if is_prime[i]:        for j in range(i * i, LIMIT + 1, i):            is_prime[j] = False    i += 1primes = [k for k in range(2, LIMIT + 1) if is_prime[k]] data = sys.stdin.read().split()t = int(data[0])out = []for n in map(int, data[1:1 + t]):    count = 0    for p in primes:        if p > n - p:  # p <= q 인 것만 센다            break        if is_prime[n - p]:            count += 1    out.append(count)print("\n".join(map(str, out)))
JavaScriptmain.js · 22 lines
const LIMIT = 9000; // 에라토스테네스의 체: isPrime[k]는 k가 소수인지const isPrime = new Array(LIMIT + 1).fill(true);isPrime[0] = isPrime[1] = false;for (let i = 2; i * i <= LIMIT; i++) {  if (!isPrime[i]) continue;  for (let j = i * i; j <= LIMIT; j += i) isPrime[j] = false;}const primes = [];for (let k = 2; k <= LIMIT; k++) if (isPrime[k]) primes.push(k); const [t, ...ns] = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const out = ns.slice(0, t).map((n) => {  let count = 0;  for (const p of primes) {    if (p > n - p) break; // p <= q 인 것만 센다    if (isPrime[n - p]) count++;  }  return count;});console.log(out.join("\n"));
TypeScriptmain.ts · 24 lines
import { readFileSync } from "node:fs"; const LIMIT = 9000; // 에라토스테네스의 체: isPrime[k]는 k가 소수인지const isPrime: boolean[] = new Array(LIMIT + 1).fill(true);isPrime[0] = isPrime[1] = false;for (let i = 2; i * i <= LIMIT; i++) {  if (!isPrime[i]) continue;  for (let j = i * i; j <= LIMIT; j += i) isPrime[j] = false;}const primes: number[] = [];for (let k = 2; k <= LIMIT; k++) if (isPrime[k]) primes.push(k); const [t, ...ns]: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const out: number[] = ns.slice(0, t).map((n) => {  let count = 0;  for (const p of primes) {    if (p > n - p) break; // p <= q 인 것만 센다    if (isPrime[n - p]) count++;  }  return count;});console.log(out.join("\n"));
JavaMain.java · 33 lines
import java.io.BufferedReader;import java.io.InputStreamReader;import java.io.IOException;import java.util.ArrayList;import java.util.List; public class Main {    public static void main(String[] args) throws IOException {        final int LIMIT = 9000;        boolean[] composite = new boolean[LIMIT + 1]; // 모두 false로 시작한다        composite[0] = composite[1] = true;        for (int i = 2; i * i <= LIMIT; i++) {            if (composite[i]) continue;            for (int j = i * i; j <= LIMIT; j += i) composite[j] = true;        }        List<Integer> primes = new ArrayList<>();        for (int k = 2; k <= LIMIT; k++) if (!composite[k]) primes.add(k);         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));        int t = Integer.parseInt(in.readLine().trim());        StringBuilder out = new StringBuilder();        for (int q = 0; q < t; q++) {            int n = Integer.parseInt(in.readLine().trim());            int count = 0;            for (int p : primes) {                if (p > n - p) break; // p <= q 인 것만 센다                if (!composite[n - p]) count++;            }            out.append(count).append('\n');        }        System.out.print(out);    }}
C#Main.cs · 35 lines
using System;using System.Collections.Generic;using System.Text; class Program{    static void Main()    {        const int LIMIT = 9000;        bool[] composite = new bool[LIMIT + 1]; // 모두 false로 시작한다        composite[0] = composite[1] = true;        for (int i = 2; i * i <= LIMIT; i++)        {            if (composite[i]) continue;            for (int j = i * i; j <= LIMIT; j += i) composite[j] = true;        }        var primes = new List<int>();        for (int k = 2; k <= LIMIT; k++) if (!composite[k]) primes.Add(k);         int t = int.Parse(Console.ReadLine().Trim());        var sb = new StringBuilder();        for (int q = 0; q < t; q++)        {            int n = int.Parse(Console.ReadLine().Trim());            int count = 0;            foreach (int p in primes)            {                if (p > n - p) break; // p <= q 인 것만 센다                if (!composite[n - p]) count++;            }            sb.Append(count).Append('\n');        }        Console.Write(sb);    }}
C++main.cpp · 27 lines
#include <iostream>#include <vector> int main() {    const int LIMIT = 9000;    std::vector<bool> isPrime(LIMIT + 1, true);    isPrime[0] = isPrime[1] = false;    for (int i = 2; i * i <= LIMIT; i++) {        if (!isPrime[i]) continue;        for (int j = i * i; j <= LIMIT; j += i) isPrime[j] = false;    }    std::vector<int> primes;    for (int k = 2; k <= LIMIT; k++)        if (isPrime[k]) primes.push_back(k);     int t, n;    std::cin >> t;    while (t-- > 0) {        std::cin >> n;        int count = 0;        for (int p : primes) {            if (p > n - p) break; // p <= q 인 것만 센다            if (isPrime[n - p]) count++;        }        std::cout << count << "\n";    }}
Cmain.c · 29 lines
#include <stdbool.h>#include <stdio.h> #define LIMIT 9000 static bool composite[LIMIT + 1]; /* static이라 모두 false로 시작한다 */static int primes[LIMIT]; int main(void) {    int count_primes = 0;    composite[0] = composite[1] = true;    for (int i = 2; i * i <= LIMIT; i++) {        if (composite[i]) continue;        for (int j = i * i; j <= LIMIT; j += i) composite[j] = true;    }    for (int k = 2; k <= LIMIT; k++)        if (!composite[k]) primes[count_primes++] = k;     int t, n;    scanf("%d", &t);    while (t-- > 0) {        scanf("%d", &n);        int count = 0;        for (int i = 0; i < count_primes && primes[i] <= n - primes[i]; i++)            if (!composite[n - primes[i]]) count++;        printf("%d\n", count);    }    return 0;}
Craykonmain.cray · 44 lines
LIMIT = 9000; // 에라토스테네스의 체: isPrime[k]는 k가 소수인지isPrime = NewList(LIMIT + 1, true);isPrime[0] = false;isPrime[1] = false;for (i = 2; i * i <= LIMIT; i++){    if (isPrime[i])    {        for (j = i * i; j <= LIMIT; j += i)        {            isPrime[j] = false;        }    }}primes = [];for (k = 2; k <= LIMIT; k++){    if (isPrime[k])    {        primes.Add(k);    }} t = Console.ReadLine().ToNumber();for (q = 0; q < t; q++){    n = Console.ReadLine().ToNumber();    count = 0;    foreach (p in primes)    {        // p <= q 인 것만 센다        if (p > n - p)        {            break;        }        if (isPrime[n - p])        {            count += 1;        }    }    Console.WriteLine(count);}