Even numbers which cannot be expressed as the sum of two twin primes

From Rosetta Code
Even numbers which cannot be expressed as the sum of two twin primes is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.


In 1742, Goldbach and Euler corresponded about what is now known as the Goldbach Conjecture: that all even integers greater than 2 can be written as the sum of two primes.
In 2000, Henry Dubner proposed a stronger conjecture: that every even integer greater than 4208 can be written as the sum of two twin primes.

At the time the Goldbach conjecture was made, 1 was considered a prime number - this is not so now. So, the Goldbach conjecture was originally that all even natural numbers could be written as the sum of two primes.

Task
  • Find and display the positive even integers that cannot be expressed as the sum of two twin primes, up to a limit of 5,000.
E.g.: The first 3 twin primes are 3, 5 and 7, so 6 (3+3), 8 (5+3) and 10 (5+5 or 7+3) can be formed but 2 and 4 cannot.
  • Show the numbers that cannot be formed by summing two twin primes when 1 is treated as a prime (and so a twin prime).



Note
  • For the purposes of this task, twin prime refers to a prime that is 2 more or less than another prime, not the pair of primes.


Stretch
  • Verify that there no more such numbers up to 10,000 or more, as you like (note it has been verified up to at least 10^9).


See also



11l

Translation of: Python
F list_primality(n)
   V result = [1B] * (n + 1)
   result[0] = result[1] = 0B
   L(i) 0 .. Int(sqrt(n))
      I result[i]
         L(j) (i * i .< result.len).step(i)
            result[j] = 0B
   R result

F nonpairsums(include1 = 0B, limit = 20'000)
   V prim = list_primality(limit + 2)

   ‘ Even numbers which cannot be expressed as the sum of two twin primes ’
   V tpri = (0 .< limit + 2).map(i -> @prim[i] & (@prim[i - 2] | @prim[i + 2]))
   I include1
      tpri[1] = 1B
   V twinsums = [0B] * (limit * 2)
   L(i) 0 .< limit
      L(j) 0 .. limit - i
         I tpri[i] & tpri[j]
            twinsums[i + j] = 1B

   R (2 .. limit).step(2).filter(i -> !@twinsums[i])

print(‘Non twin prime sums:’)
L(p) nonpairsums()
   V k = L.index
   print(f:‘{p:6}’, end' I (k + 1) % 10 == 0 {"\n"} E ‘’)

print("\n\nNon twin prime sums (including 1):")
L(p) nonpairsums(include1' 1B)
   V k = L.index
   print(f:‘{p:6}’, end' I (k + 1) % 10 == 0 {"\n"} E ‘’)
Output:
Non twin prime sums:
     2     4    94    96    98   400   402   404   514   516
   518   784   786   788   904   906   908  1114  1116  1118
  1144  1146  1148  1264  1266  1268  1354  1356  1358  3244
  3246  3248  4204  4206  4208

Non twin prime sums (including 1):
    94    96    98   400   402   404   514   516   518   784
   786   788   904   906   908  1114  1116  1118  1144  1146
  1148  1264  1266  1268  1354  1356  1358  3244  3246  3248
  4204  4206  4208

ALGOL 68

BEGIN # find even numbers that are not the sum of two twin primes           #

    # prints the non-twin prime sum numbers                                 #
    PROC show non twin prime sums = ( STRING legend, []BOOL p2sums )VOID:
         BEGIN
            print( ( legend, ":", newline ) );
            INT count   := 0;
            INT per line = 10;
            FOR i FROM 2 BY 2 TO max number DO
                IF NOT p2sum[ i ] THEN
                    print( ( whole( i, - 6 ) ) );
                    IF ( count +:= 1 ) MOD per line = 0 THEN print( ( newline ) ) FI
                FI
            OD;
            IF count MOD per line /= 0 THEN print( ( newline ) ) FI;
            print( ( "Found ", whole( count, 0 ), newline, newline ) )
         END # print non twin primes sums # ;

    INT max number = 100 000;             # maximum number we will consider #
    [ 0 : max number ]BOOL prime;          # sieve the primes to max number #
    prime[ 0 ] := prime[ 1 ] := FALSE;
    prime[ 2 ] := TRUE;
    FOR i FROM 3 BY 2 TO UPB prime DO prime[ i ] := TRUE  OD;
    FOR i FROM 4 BY 2 TO UPB prime DO prime[ i ] := FALSE OD;
    FOR i FROM 3 BY 2 TO ENTIER sqrt( UPB prime ) DO
        IF prime[ i ] THEN
            FOR s FROM i * i BY i + i TO UPB prime DO prime[ s ] := FALSE OD
        FI
    OD;
    prime[ 2 ] := FALSE;           # restrict the sieve to twin primes only #
    FOR i FROM 3 BY 2 TO max number - 2 DO
        IF prime[ i ] AND NOT prime[ i - 2 ] AND NOT prime[ i + 2 ] THEN
            prime[ i ] := FALSE
        FI
    OD;
    # construct a table of the even numbers that can be formed by summing   #
    # two twin primes                                                       #
    [ 1 : max number ]BOOL p2sum; FOR i TO UPB p2sum DO p2sum[ i ] := FALSE OD;
    FOR i FROM 3 BY 2 TO max number DO
        IF prime[ i ] THEN
            FOR j FROM i TO ( max number + 1 ) - i DO
                IF prime[ j ] THEN p2sum[ i + j ] := TRUE FI
            OD
        FI
    OD;

    # print the even numbers which aren't the sum of 2 twin primes          #
    show non twin prime sums( "Non twin prime sums", p2sum );

    # adjust the table as if 1 was a twin prime                             #
    p2sum[ 2 ] := TRUE;
    FOR i FROM 3 BY 2 TO max number DO
        IF prime[ i ] THEN p2sum[ i + 1 ] := TRUE FI
    OD;

    # print the revised even numbers which aren't the sum of 2 twin primes  #
    show non twin prime sums( "Non twin prime sums (including 1)", p2sum )

END
Output:
Non twin prime sums:
     2     4    94    96    98   400   402   404   514   516
   518   784   786   788   904   906   908  1114  1116  1118
  1144  1146  1148  1264  1266  1268  1354  1356  1358  3244
  3246  3248  4204  4206  4208
Found 35

Non twin prime sums (including 1):
    94    96    98   400   402   404   514   516   518   784
   786   788   904   906   908  1114  1116  1118  1144  1146
  1148  1264  1266  1268  1354  1356  1358  3244  3246  3248
  4204  4206  4208
Found 33

C++

#include <iomanip>
#include <iostream>
#include <vector>

std::vector<bool> prime_sieve(int limit) {
    std::vector<bool> sieve(limit, true);
    if (limit > 0)
        sieve[0] = false;
    if (limit > 1)
        sieve[1] = false;
    for (int i = 4; i < limit; i += 2)
        sieve[i] = false;
    for (int p = 3, sq = 9; sq < limit; p += 2) {
        if (sieve[p]) {
            for (int q = sq; q < limit; q += p << 1)
                sieve[q] = false;
        }
        sq += (p + 1) << 2;
    }
    return sieve;
}

void print_non_twin_prime_sums(const std::vector<bool>& sums) {
    int count = 0;
    for (size_t i = 2; i < sums.size(); i += 2) {
        if (!sums[i]) {
            ++count;
            std::cout << std::setw(4) << i << (count % 10 == 0 ? '\n' : ' ');
        }
    }
    std::cout << "\nFound " << count << '\n';
}

int main() {
    const int limit = 100001;

    std::vector<bool> sieve = prime_sieve(limit + 2);
    // remove non-twin primes from the sieve
    for (size_t i = 0; i < limit; ++i) {
        if (sieve[i] && !((i > 1 && sieve[i - 2]) || sieve[i + 2]))
            sieve[i] = false;
    }

    std::vector<bool> twin_prime_sums(limit, false);
    for (size_t i = 0; i < limit; ++i) {
        if (sieve[i]) {
            for (size_t j = i; i + j < limit; ++j) {
                if (sieve[j])
                    twin_prime_sums[i + j] = true;
            }
        }
    }

    std::cout << "Non twin prime sums:\n";
    print_non_twin_prime_sums(twin_prime_sums);

    sieve[1] = true;
    for (size_t i = 1; i + 1 < limit; ++i) {
        if (sieve[i])
            twin_prime_sums[i + 1] = true;
    }

    std::cout << "\nNon twin prime sums (including 1):\n";
    print_non_twin_prime_sums(twin_prime_sums);
}
Output:
Non twin prime sums:
   2    4   94   96   98  400  402  404  514  516
 518  784  786  788  904  906  908 1114 1116 1118
1144 1146 1148 1264 1266 1268 1354 1356 1358 3244
3246 3248 4204 4206 4208 
Found 35

Non twin prime sums (including 1):
  94   96   98  400  402  404  514  516  518  784
 786  788  904  906  908 1114 1116 1118 1144 1146
1148 1264 1266 1268 1354 1356 1358 3244 3246 3248
4204 4206 4208 
Found 33

Delphi

Works with: Delphi version 6.0


procedure ShowSumTwinPrimes(Memo: TMemo);
var Sieve: TPrimeSieve;
var Twins: TIntegerDynArray;
var S: string;

	procedure GetTwinPrimes(WithOne: boolean);
	{Build list of twin primes - include one, WithOne is true}
	var I,P1,P2: integer;
	begin
	{Add one to list?}
	if WithOne then
		begin
		SetLength(Twins,1);
		Twins[0]:=1;
		end
	else SetLength(Twins,0);
	{Look for numbers that P-1 or P+1 are two apart}
	for I:=0 to Sieve.PrimeCount-1 do
	 if ((I>0) and ((Sieve.Primes[I]-Sieve.Primes[I-1]) = 2)) or
	    ((I<(Sieve.PrimeCount-1)) and ((Sieve.Primes[I+1]-Sieve.Primes[I]) = 2)) then
	 	begin
	 	{Store twin}
	 	SetLength(Twins,Length(Twins)+1);
	 	Twins[High(Twins)]:=Sieve.Primes[I];
	 	end;
	end;


	function IsNotTwinPrimeSum(N: integer): boolean;
	{Test if number is NOT the sum of twin primes}
	var I,J,Sum: integer;
	begin
	Result:=False;
	{Test all combination of twin-prime sums}
	for I:=0 to High(Twins) do
	 for J:=0 to High(Twins) do
		begin
		Sum:=Twins[I]+Twins[J];
	        if Sum>N then break;
	        if Sum=N then exit;
		end;
	Result:=True;
	end;


	function GetItems: string;
	{Get first 5000 non twin prime sums}
	var I,N,Cnt: integer;
	begin
	Result:=''; Cnt:=0;
	for I:=1 to (5000 div 2)-1 do
		begin
		N:=I * 2;
		if IsNotTwinPrimeSum(N) then
			begin
			Inc(Cnt);
			Result:=Result+Format('%5d',[N]);
			if (Cnt mod 10)=0 then Result:=Result+CRLF;
			end;
		end;
	end;

begin
Sieve:=TPrimeSieve.Create;
try
Sieve.Intialize(1000000);
GetTwinPrimes(False);
Memo.Lines.Add('Non twin prime sums:');
Memo.Lines.Add(GetItems);
GetTwinPrimes(True);
Memo.Lines.Add('Non twin prime sums with one:');
Memo.Lines.Add(GetItems);
finally Sieve.Free; end;
end;
Output:
Non twin prime sums:
    2    4   94   96   98  400  402  404  514  516
  518  784  786  788  904  906  908 1114 1116 1118
 1144 1146 1148 1264 1266 1268 1354 1356 1358 3244
 3246 3248 4204 4206 4208
Non twin prime sums with one:
   94   96   98  400  402  404  514  516  518  784
  786  788  904  906  908 1114 1116 1118 1144 1146
 1148 1264 1266 1268 1354 1356 1358 3244 3246 3248
 4204 4206 4208

Elapsed Time: 37.563 ms.


Go

Translation of: Wren
Library: Go-rcu
package main

import (
    "fmt"
    "rcu"
)

const limit = 100000 // say

func nonTwinSums(twins []int) []int {
    sieve := make([]bool, limit+1)
    for i := 0; i < len(twins); i++ {
        for j := i; j < len(twins); j++ {
            sum := twins[i] + twins[j]
            if sum > limit {
                break
            }
            sieve[sum] = true
        }
    }
    var res []int
    for i := 2; i < limit; i += 2 {
        if !sieve[i] {
            res = append(res, i)
        }
    }
    return res
}

func main() {
    primes := rcu.Primes(limit)[2:] // exclude 2 and 3
    twins := []int{3}
    for i := 0; i < len(primes)-1; i++ {
        if primes[i+1]-primes[i] == 2 {
            if twins[len(twins)-1] != primes[i] {
                twins = append(twins, primes[i])
            }
            twins = append(twins, primes[i+1])
        }
    }
    fmt.Println("Non twin prime sums:")
    ntps := nonTwinSums(twins)
    rcu.PrintTable(ntps, 10, 4, false)
    fmt.Println("Found", len(ntps))

    fmt.Println("\nNon twin prime sums (including 1):")
    twins = append([]int{1}, twins...)
    ntps = nonTwinSums(twins)
    rcu.PrintTable(ntps, 10, 4, false)
    fmt.Println("Found", len(ntps))
}
Output:
Non twin prime sums:
   2    4   94   96   98  400  402  404  514  516 
 518  784  786  788  904  906  908 1114 1116 1118 
1144 1146 1148 1264 1266 1268 1354 1356 1358 3244 
3246 3248 4204 4206 4208 
Found 35

Non twin prime sums (including 1):
  94   96   98  400  402  404  514  516  518  784 
 786  788  904  906  908 1114 1116 1118 1144 1146 
1148 1264 1266 1268 1354 1356 1358 3244 3246 3248 
4204 4206 4208 
Found 33

J

For this task, it's convenient to have a routine to generate a sequence of twin primes up to a given limit:

twp=: [:(#~ ] e. (+,-)&2)i.&.(p:inv)

With this, the task becomes:

   (2*1+i.2500)-.,+/~twp 5000
2 4 94 96 98 400 402 404 514 516 518 784 786 788 904 906 908 1114 1116 1118 1144 1146 1148 1264 1266 1268 1354 1356 1358 3244 3246 3248 4204 4206 4208
   (2*1+i.2500)-.,+/~1,twp 5000  NB. including 1 in list of twin primes
94 96 98 400 402 404 514 516 518 784 786 788 904 906 908 1114 1116 1118 1144 1146 1148 1264 1266 1268 1354 1356 1358 3244 3246 3248 4204 4206 4208

For the stretch goal, we count omitted sums of twin prime pairs, and compare the count with the count we get with a raised limit:

   #(2*1+i.2500)-.,+/~twp 5000
35
   #(2*1+i.2500)-.,+/~twp 1000000
35

jq

Adapted from Wren

Works with: jq

Also works with gojq, the Go implementation of jq

Infrastructure

# Produce a stream of primes <= .
def eratosthenes:
  # The array we use for the sieve only stores information for the odd integers greater than 1:
  #  index   integer
  #      0         3
  #      k   2*k + 3
  # So if we wish to mark m = 2*k + 3, the relevant index is: m - 3 / 2
  def ix:
    if . % 2 == 0 then null
    else ((. - 3) / 2)
    end;

  # erase(i) sets .[i*j] to false for odd integral j > i on the assumption that i is odd
  def erase(i):
    ((i - 3) / 2) as $k
    | (((length * 2 + 3) / i)) as $upper
    # ... only consider odd multiples from i onwards
    | reduce range(i; $upper; 2) as $j (.;
         (((i * $j) - 3) / 2) as $m
         | if .[$m] then .[$m] = false else . end);

  if . < 2 then []
  else (. + 1) as $n
  | (($n|sqrt) / 2) as $s
  | [range(3; $n; 2)|true]
  | reduce (1 + (2 * range(1; $s)) ) as $i (.; erase($i))
  | . as $sieve
  # We could at this point produce an array of primes by writing:
  # | [2] + reduce range(3; $n; 2) as $k ([]; if $sieve[$k|ix] then . + [$k] else . end)
  | 2, (range(3; $n; 2) | select($sieve[ix]))
  end ;

# Emit an array of the primes <= $limit that have twins 
def twins($limit):
  # exclude 2 and 3
  ($limit | [eratosthenes][2:]) as $primes
  | reduce range(0;$primes|length-1) as $i ([3];
      if ($primes[$i+1] - $primes[$i] == 2) 
      then if (.[-1] != $primes[$i]) then . + [$primes[$i]] else . end
      | . + [$primes[$i+1]]
      else .
      end);

# Emit an array
def nonTwinSums($limit; $twins):
  reduce range(0; $twins|length) as $i (
       { sieve: [range(0; $limit+1) | false] };
       .emit = null
       | .j = $i
       | until(.emit;
           ($twins[$i] + $twins[.j]) as $sum
           | if $sum > $limit then .emit = .sieve
             else .sieve[$sum] = true
	     end
	   | .j += 1
	   | if .j == ($twins|length) then .emit = .sieve else . end )
     )
  | .sieve as $sieve
  | reduce range(2; $limit + 1; 2) as $i ([];
        if ($sieve[$i] | not) then . + [ $i ] else . end) ;

The Task

def task($limit):
  twins($limit) as $twins
 | ( "Non twin prime sums:",
     ( nonTwinSums($limit; $twins) as $ntps
       | $ntps, " Found \($ntps|length)" ) ),
   ("\nNon twin prime sums (including 1):",
     ( nonTwinSums($limit; [1] + $twins) as $ntps
       | $ntps, " Found \($ntps|length)" )) ;

# Example:
task(100000)

Invocation: jq -nrc -f task.jq

Output:
Non twin prime sums:
[2,4,94,96,98,400,402,404,514,516,518,784,786,788,904,906,908,1114,1116,1118,1144,1146,1148,1264,1266,1268,1354,1356,1358,3244,3246,3248,4204,4206,4208]
 Found 35

Non twin prime sums (including 1):
[94,96,98,400,402,404,514,516,518,784,786,788,904,906,908,1114,1116,1118,1144,1146,1148,1264,1266,1268,1354,1356,1358,3244,3246,3248,4204,4206,4208]
 Found 33

Julia

using Primes

""" Even numbers which cannot be expressed as the sum of two twin primes """
function nonpairsums(;include1=false, limit=20_000)
    tpri = primesmask(limit + 2)
    for i in 1:limit
        tpri[i] && (i > 2 && !tpri[i - 2]) && !tpri[i + 2] && (tpri[i] = false)
    end
    tpri[2] = false
    include1 && (tpri[1] = true)
    twinsums = falses(limit * 2)
    for i in 1:limit-2, j in 1:limit-2
        if tpri[i] && tpri[j]
            twinsums[i + j] = true
        end
    end
    return [i for i in 2:2:limit if !twinsums[i]]
end

println("Non twin prime sums:")
foreach(p -> print(lpad(p[2], 6), p[1] % 10 == 0 ? "\n" : ""), pairs(nonpairsums()))

println("\n\nNon twin prime sums (including 1):")
foreach(p -> print(lpad(p[2], 6), p[1] % 10 == 0 ? "\n" : ""), pairs(nonpairsums(include1 = true)))
Output:
Non twin prime sums:
     2     4    94    96    98   400   402   404   514   516
   518   784   786   788   904   906   908  1114  1116  1118
  1144  1146  1148  1264  1266  1268  1354  1356  1358  3244
  3246  3248  4204  4206  4208

Non twin prime sums (including 1):
    94    96    98   400   402   404   514   516   518   784
   786   788   904   906   908  1114  1116  1118  1144  1146
  1148  1264  1266  1268  1354  1356  1358  3244  3246  3248
  4204  4206  4208

Nim

Translation of: Wren

Instead of using a sieve to build the list of primes, we check directly if a number is prime.

import std/[strformat, sugar]

const Limit = 100_000

func isPrime(n: Natural): bool =
  if n < 2: return false
  if (n and 1) == 0: return n == 2
  if n mod 3 == 0: return n == 3
  var k = 5
  var delta = 2
  while k * k <= n:
    if n mod k == 0: return false
    inc k, delta
    delta = 6 - delta
  result = true

let primes = collect:
               for n in countup(5, Limit, 2):
                 if n.isPrime: n

var twins = @[3]
for i in 0..<primes.high:
  if primes[i + 1] - primes[i] == 2:
    if twins[^1] != primes[i]:
      twins.add primes[i]
    twins.add primes[i + 1]

func nonTwinSums(twins: seq[int]): seq[int] =
  var sieve = newSeq[bool](Limit + 1)
  for i in 0..twins.high:
    for j in i..twins.high:
      let sum = twins[i] + twins[j]
      if sum > Limit: break
      sieve[sum] = true
  var i = 2
  while i <= Limit:
    if not sieve[i]:
      result.add i
    inc i, 2

echo "Non twin prime sums:"
var ntps = nonTwinSums(twins)
for i, n in ntps:
  stdout.write &"{n:4}"
  stdout.write if i mod 10 == 9: '\n' else: ' '
echo &"\nFound {ntps.len}.\n"

echo "Non twin prime sums (including 1):"
twins.insert(1, 0)
ntps = nonTwinSums(twins)
for i, n in ntps:
  stdout.write &"{n:4}"
  stdout.write if i mod 10 == 9: '\n' else: ' '
echo &"\nFound {ntps.len}.\n"
Output:
Non twin prime sums:
   2    4   94   96   98  400  402  404  514  516
 518  784  786  788  904  906  908 1114 1116 1118
1144 1146 1148 1264 1266 1268 1354 1356 1358 3244
3246 3248 4204 4206 4208 
Found 35.

Non twin prime sums (including 1):
  94   96   98  400  402  404  514  516  518  784
 786  788  904  906  908 1114 1116 1118 1144 1146
1148 1264 1266 1268 1354 1356 1358 3244 3246 3248
4204 4206 4208 
Found 33.

Perl

Translation of: Raku
Library: ntheory
use v5.36;
use experimental 'for_list';
use List::Util 'uniq';
use ntheory 'is_prime';

sub       X ($a, $b) { my @c; for my $aa (0..$a-1) { for my $bb (0..$b-1) { push @c, $aa, $bb } } @c }
sub   table ($c, @V) { my $t = $c * (my $w = 6); ( sprintf( ('%'.$w.'d')x@V, @V) ) =~ s/.{1,$t}\K/\n/gr }
sub display (@s)     { table 10, grep { $_ < 5000 } grep { not $s[$_] and 0==$_%2 and $_ } 0..@s }

my ($limit, @sums) = 10_000;
my @twins = uniq map { $_, $_+2 } grep { is_prime $_ and is_prime($_+2) } 3 .. $limit;
for my($i,$j) ( X ((scalar @twins) x 2) ) { ++$sums[ $twins[$i] + $twins[$j] ] }
say   "Non twin prime sums:\n"               . display @sums;
++$sums[1 + $_] for 1, @twins;
say "\nNon twin prime sums (including 1):\n" . display @sums;
Output:
Non twin prime sums:
     2     4    94    96    98   400   402   404   514   516
   518   784   786   788   904   906   908  1114  1116  1118
  1144  1146  1148  1264  1266  1268  1354  1356  1358  3244
  3246  3248  4204  4206  4208

Non twin prime sums (including 1):
    94    96    98   400   402   404   514   516   518   784
   786   788   904   906   908  1114  1116  1118  1144  1146
  1148  1264  1266  1268  1354  1356  1358  3244  3246  3248
  4204  4206  4208

Phix

with javascript_semantics
constant lim = 10000
sequence prime = repeat(false,lim),
         p2sum = repeat(false,lim)
for p in get_primes_le(lim)[2..$] do
    prime[p] = true
end for
-- restrict to twin primes only
for i=3 to lim-2 by 2 do
    if prime[i] and not prime[i-2] and not prime[i+2] then
        prime[i] := false
    end if
end for
-- flag all summables
for i=3 to lim by 2 do
    if prime[i] then
        for j=i to lim+1-i do
            if prime[j] then p2sum[i+j] = true end if
        end for
    end if
end for
sequence npts = {},
         npts1 = {}
for i=2 to lim by 2 do
    if not p2sum[i] then npts &= i end if       
end for
-- adjust table as if 1 was a twin prime
p2sum[2] = true
for i=3 to lim by 2 do
    if prime[i] then p2sum[i+1] = true end if
end for
for i=2 to lim by 2 do
    if not p2sum[i] then npts1 &= i end if      
end for
string fmt = "Non twin prime sums%s:\n%sFound %d\n\n",
       ntps = join_by(npts,1,10,"",fmt:="%6d"),
       ntps1 = join_by(npts1,1,10,"",fmt:="%6d")
printf(1,fmt,{"",ntps,length(npts)})
printf(1,fmt,{" (including 1)",ntps1,length(npts1)})
Output:
Non twin prime sums:
     2     4    94    96    98   400   402   404   514   516
   518   784   786   788   904   906   908  1114  1116  1118
  1144  1146  1148  1264  1266  1268  1354  1356  1358  3244
  3246  3248  4204  4206  4208
Found 35

Non twin prime sums (including 1):
    94    96    98   400   402   404   514   516   518   784
   786   788   904   906   908  1114  1116  1118  1144  1146
  1148  1264  1266  1268  1354  1356  1358  3244  3246  3248
  4204  4206  4208
Found 33

PL/M

Works with: 8080 PL/M Compiler

... under CP/M (or an emulator)

100H: /* FIND EVEN NUMBERS THAT ARE NOT THE SUM OF TWO TWIN PRIMES           */

   /* CP/M SYSTEM CALL AND I/O ROUTINES                                      */
   BDOS:      PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
   PR$CHAR:   PROCEDURE( C ); DECLARE C BYTE;    CALL BDOS( 2, C );  END;
   PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S );  END;
   PR$NL:     PROCEDURE;   CALL PR$CHAR( 0DH ); CALL PR$CHAR( 0AH ); END;
   PR$NUMBER: PROCEDURE( N ); /* PRINTS A NUMBER IN THE MINIMUN FIELD WIDTH  */
      DECLARE N ADDRESS;
      DECLARE V ADDRESS, N$STR ( 6 )BYTE, W BYTE;
      V = N;
      W = LAST( N$STR );
      N$STR( W ) = '$';
      N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      DO WHILE( ( V := V / 10 ) > 0 );
         N$STR( W := W - 1 ) = '0' + ( V MOD 10 );
      END;
      CALL PR$STRING( .N$STR( W ) );
   END PR$NUMBER;

   /* TASK                                                                   */

   DECLARE MAX$NUMBER LITERALLY '5001'
         , FALSE      LITERALLY '0'
         , TRUE       LITERALLY '0FFH'
         ;

   /* PRINT THE NUMBERS THAT ARE NOT THE SUM OF TWO TWIN PRIMES              */
   SHOW$NON$TWIN$PRIME$SUMS: PROCEDURE( LEGEND, P2$PTR );
      DECLARE ( LEGEND, P2$PTR ) ADDRESS;
      DECLARE P2SUM BASED P2$PTR ( 0 )BYTE;
      DECLARE ( COUNT, I )ADDRESS;
      DECLARE PER$LINE LITERALLY '10';

      CALL PR$STRING( LEGEND );CALL PR$CHAR( ':' );CALL PR$NL;
      COUNT = 0;
      DO I = 2 TO MAX$NUMBER - 1 BY 2;
         IF NOT P2SUM( I ) THEN DO;
            CALL PR$CHAR( ' ' );
            IF I < 1000 THEN CALL PR$CHAR( ' ' );
            IF I <  100 THEN CALL PR$CHAR( ' ' );
            IF I <   10 THEN CALL PR$CHAR( ' ' );
            CALL PR$CHAR( ' ' );
            CALL PR$NUMBER( I );
            IF ( COUNT := COUNT + 1 ) MOD PER$LINE = 0 THEN CALL PR$NL;
         END;
      END;
      IF COUNT MOD PER$LINE <> 0 THEN CALL PR$NL;
      CALL PR$STRING( .'FOUND $' );CALL PR$NUMBER( COUNT );CALL PR$NL;
   END SHOW$NON$TWIN$PRIME$SUMS ;

   DECLARE PRIME ( MAX$NUMBER )BYTE;   /* SIEVE THE PRIMES TO MAX$NUMBER - 1 */
   DECLARE I ADDRESS;
   PRIME( 0 ), PRIME( 1 ) = FALSE;
   PRIME( 2 ) = TRUE;
   DO I = 3 TO LAST( PRIME ) BY 2; PRIME( I ) = TRUE;  END;
   DO I = 4 TO LAST( PRIME ) BY 2; PRIME( I ) = FALSE; END;
   DO I = 3 TO LAST( PRIME ) BY 2;
      IF PRIME( I ) THEN DO;
         DECLARE S ADDRESS;
         DO S = I + I TO LAST( PRIME ) BY I;
            PRIME( S ) = FALSE;
         END;
      END;
   END;
   PRIME( 2 ) = FALSE;             /* RESTRICT THE SIEVE TO TWIN PRIMES ONLY */
   DO I = 3 TO LAST( PRIME ) - 2 BY 2;
      IF PRIME( I ) AND NOT PRIME( I - 2 ) AND NOT PRIME( I + 2 ) THEN DO;
         PRIME( I ) = FALSE;
      END;
   END;
   /* CONSTRUCT A TABLE OF EVEN NUMBERS THAT CAN BE FORMED BY SUMMING TWO    */
   /* TWIN PRIMES                                                            */
   DECLARE P2SUM ( MAX$NUMBER )BYTE;
   DO I = 0 TO LAST( P2SUM ); P2SUM( I ) = FALSE; END;
   DO I = 3 TO LAST( PRIME ) BY 2;
      IF PRIME( I ) THEN DO;
         DECLARE J ADDRESS;
         DO J = I TO LAST( P2SUM ) - I;
            IF PRIME( J ) THEN P2SUM( I + J ) = TRUE;
         END;
      END;
   END;

   /* PRINT THE EVEN NUMBERS THAT AREN'T THE SUM OF TWO TWIN PRIMES          */
   CALL SHOW$NON$TWIN$PRIME$SUMS( .'NON TWIN PRIME SUMS$', .P2SUM );
   CALL PR$NL;

   /* ADJUST THE TABLE AS IF 1 WAS A TWIN PRIME                              */
   P2SUM( 2 ) = TRUE;
   DO I = 3 TO LAST( P2SUM ) - 1 BY 2;
      IF PRIME( I ) THEN P2SUM( I + 1 ) = TRUE;
   END;

   /* PRINT THE REVISED EVEN NUMBERS THAT AREN'T THE SUM OF TWO TWIN PRIMES  */
   CALL SHOW$NON$TWIN$PRIME$SUMS( .'NON TWIN PRIME SUMS (WITH 1 AS PRIME)$'
                                , .P2SUM
                                );
EOF
Output:
NON TWIN PRIME SUMS:
     2     4    94    96    98   400   402   404   514   516
   518   784   786   788   904   906   908  1114  1116  1118
  1144  1146  1148  1264  1266  1268  1354  1356  1358  3244
  3246  3248  4204  4206  4208
FOUND 35

NON TWIN PRIME SUMS (WITH 1 AS PRIME):
    94    96    98   400   402   404   514   516   518   784
   786   788   904   906   908  1114  1116  1118  1144  1146
  1148  1264  1266  1268  1354  1356  1358  3244  3246  3248
  4204  4206  4208
FOUND 33

Python

''' rosettacode.org/wiki/Even_numbers_which_cannot_be_expressed_as_the_sum_of_two_twin_primes '''

from sympy import sieve


def nonpairsums(include1=False, limit=20_000):
    """ Even numbers which cannot be expressed as the sum of two twin primes """
    tpri = [i in sieve and (i - 2 in sieve or i + 2 in sieve)
            for i in range(limit+2)]
    if include1:
        tpri[1] = True
    twinsums = [False] * (limit * 2)
    for i in range(limit):
        for j in range(limit-i+1):
            if tpri[i] and tpri[j]:
                twinsums[i + j] = True

    return [i for i in range(2, limit+1, 2) if not twinsums[i]]


print('Non twin prime sums:')
for k, p in enumerate(nonpairsums()):
    print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')

print('\n\nNon twin prime sums (including 1):')
for k, p in enumerate(nonpairsums(include1=True)):
    print(f'{p:6}', end='\n' if (k + 1) % 10 == 0 else '')
Output:
Non twin prime sums:
     2     4    94    96    98   400   402   404   514   516
   518   784   786   788   904   906   908  1114  1116  1118
  1144  1146  1148  1264  1266  1268  1354  1356  1358  3244
  3246  3248  4204  4206  4208

Non twin prime sums (including 1):
    94    96    98   400   402   404   514   516   518   784
   786   788   904   906   908  1114  1116  1118  1144  1146
  1148  1264  1266  1268  1354  1356  1358  3244  3246  3248
  4204  4206  4208

Raku

my $threshold = 10000;

my @twins = unique flat (3..$threshold).grep(&is-prime).map: { $_, $_+2 if ($_+2).is-prime };
my @sums;

map {++@sums[$_]}, (@twins X+ @twins);
display 'Non twin prime sums:', @sums;

map {++@sums[$_]}, flat 2, (1 X+ @twins);
display "\nNon twin prime sums (including 1):", @sums;

sub display ($msg, @p) {
    put "$msg\n" ~ @p[^$threshold].kv.map(-> $k, $v { $k if ($k %% 2) && !$v })\
    .skip(1).batch(10)».fmt("%4d").join: "\n"
}
Output:
Non twin prime sums:
   2    4   94   96   98  400  402  404  514  516
 518  784  786  788  904  906  908 1114 1116 1118
1144 1146 1148 1264 1266 1268 1354 1356 1358 3244
3246 3248 4204 4206 4208

Non twin prime sums (including 1):
  94   96   98  400  402  404  514  516  518  784
 786  788  904  906  908 1114 1116 1118 1144 1146
1148 1264 1266 1268 1354 1356 1358 3244 3246 3248
4204 4206 4208

Sidef

var limit = 1e4

func display(msg, sums) {
    say msg
    2..limit -> by(2).grep{ !sums.has(_) }.each_slice(10, {|*s|
        say s.map{ '%4s' % _ }.join(' ')
    })
}

var sums = Set()
var twins = primes(3, limit).cons(2).grep{ .diffs[0] == 2 }.flat.uniq

[twins, twins].cartesian{|a,b| sums << a+b }
display("Non twin prime sums:", sums)

sums << (2, twins.map{.inc}...)
display("\nNon twin prime sums (including 1):", sums)
Output:
Non twin prime sums:
   2    4   94   96   98  400  402  404  514  516
 518  784  786  788  904  906  908 1114 1116 1118
1144 1146 1148 1264 1266 1268 1354 1356 1358 3244
3246 3248 4204 4206 4208

Non twin prime sums (including 1):
  94   96   98  400  402  404  514  516  518  784
 786  788  904  906  908 1114 1116 1118 1144 1146
1148 1264 1266 1268 1354 1356 1358 3244 3246 3248
4204 4206 4208

Wren

Library: Wren-math
Library: Wren-fmt
import "./math" for Int
import "./fmt" for Fmt

var limit = 100000 // say
var primes = Int.primeSieve(limit)[2..-1] // exclude 2 & 3

var twins = [3]
for (i in 0...primes.count-1) {
    if (primes[i+1] - primes[i] == 2) {
        if (twins[-1] != primes[i]) twins.add(primes[i])
        twins.add(primes[i+1])
    }
}

var nonTwinSums = Fn.new {
    var sieve = List.filled(limit+1, false)
    for (i in 0...twins.count) {
        for (j in i...twins.count) {
            var sum = twins[i] + twins[j]
            if (sum > limit) break
            sieve[sum] = true
        }
    }
    var res = []
    var i = 2
    while (i < limit) {
        if (!sieve[i]) res.add(i)
        i = i + 2
    }
    return res
}

System.print("Non twin prime sums:")
var ntps = nonTwinSums.call()
Fmt.tprint("$4d", ntps, 10)
System.print("Found %(ntps.count)")

System.print("\nNon twin prime sums (including 1):")
twins.insert(0, 1)
ntps = nonTwinSums.call()
Fmt.tprint("$4d", ntps, 10)
System.print("Found %(ntps.count)")
Output:
Non twin prime sums:
   2    4   94   96   98  400  402  404  514  516 
 518  784  786  788  904  906  908 1114 1116 1118 
1144 1146 1148 1264 1266 1268 1354 1356 1358 3244 
3246 3248 4204 4206 4208 
Found 35

Non twin prime sums (including 1):
  94   96   98  400  402  404  514  516  518  784 
 786  788  904  906  908 1114 1116 1118 1144 1146 
1148 1264 1266 1268 1354 1356 1358 3244 3246 3248 
4204 4206 4208 
Found 33

XPL0

func IsPrime(N);        \Return 'true' if N is prime
int  N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
    [if rem(N/I) = 0 then return false;
    I:= I+1;
    ];
return true;
];

def Limit = 1000000;            \stretch case
int TPTbl(Limit),               \Twin Prime Table
    Ints(Limit+1);
int I, J, N, Sum, TPMax, Cnt;


proc Show(Start);               \Show non twin prime sums
int  Start;
[Text(0, "Non twin prime sums");
if Start = 0 then Text(0, " (including 1 as a prime)");
Text(0, ":^m^j");
for N:= 0 to Limit do           \initialize all Ints as not a sum
    Ints(N):= false;
for I:= Start to TPMax do
    for J:= I to TPMax do
        [Sum:= TPTbl(I) + TPTbl(J);
        if Sum <= Limit then
            Ints(Sum):= true    \mark integer as "is a sum"
        else J:= TPMax;         \don't search beyond Limit
        ];
Format(5, 0);
Cnt:= 0;
for I:= 2 to Limit do
    [if Ints(I) = false then
        [RlOut(0, float(I));
        Cnt:= Cnt+1;
        if rem(Cnt/10) = 0 then CrLf(0);
        ];
    I:= I+1;                    \step 'for' loop by 2
    ];
CrLf(0);
];


[TPTbl(0):= 1;          \case where 1 = prime
I:= 1;
for N:= 2 to Limit do   \build table of primes with a twin
    if IsPrime(N) & IsPrime(N+2) then
        [TPTbl(I):= N;  I:= I+1;
         TPTbl(I):= N+2;  I:= I+1;
        ];
TPMax:= I-1;
Show(1);
Show(0);
]
Output:
Non twin prime sums:
    2    4   94   96   98  400  402  404  514  516
  518  784  786  788  904  906  908 1114 1116 1118
 1144 1146 1148 1264 1266 1268 1354 1356 1358 3244
 3246 3248 4204 4206 4208
Non twin prime sums (including 1 as a prime):
   94   96   98  400  402  404  514  516  518  784
  786  788  904  906  908 1114 1116 1118 1144 1146
 1148 1264 1266 1268 1354 1356 1358 3244 3246 3248
 4204 4206 4208

Mathematica / Wolfram Language

UpperLimit = 10000;
SmallerTwinPrimes = Select[Range[UpperLimit], (PrimeQ[#] && PrimeQ[# + 2]) &];(*Finds set of smaller twin primes up to UpperLimit*)
AllTwinPrimes = Union[SmallerTwinPrimes, SmallerTwinPrimes + 2]; (*Gives set of all twin primes up to UpperLimit*)
CheckIfNotSumOfNumbersInSet[n_, set_] := If[Intersection[(n - set), set] == {}, n, ## &[]] (*Finds elements in set_ that sum to n_, then displays them, otherwise it gives an empty set*)
ListOfNonTwinPrimeSums = Table[CheckIfNotSumOfNumbersInSet[n, AllTwinPrimes], {n, 2, UpperLimit, 2}]; (*Generates table of elements that are not sums of twin \primes*)
ListOfNonTwinPrimeSumsWith1 = Table[CheckIfNotSumOfNumbersInSet[n, Union[AllTwinPrimes, {1}]], {n, 2, UpperLimit, 2}]; (*Same as above, but treating 1 as a twin prime*)
StringTemplate["Non twin prime sums: `list`, found `length`"][<|"list" -> ListOfNonTwinPrimeSums, "length" -> Length[ListOfNonTwinPrimeSums]|>]
StringTemplate["Non twin prime sums (including 1 as a prime): `list`, found `length`"][<|"list" -> ListOfNonTwinPrimeSumsWith1, "length" -> Length[ListOfNonTwinPrimeSumsWith1]|>]
Output:
Non twin prime sums: {2, 4, 94, 96, 98, 400, 402, 404, 514, 516, 518, 784, 786, 788, 904, 906, 908, 1114, 1116, 1118, 1144, 1146, 1148, 1264, 1266, 1268, 1354, 1356, 1358, 3244, 3246, 3248, 4204, 4206, 4208}, found 35
Non twin prime sums (including 1 as a prime): {94, 96, 98, 400, 402, 404, 514, 516, 518, 784, 786, 788, 904, 906, 908, 1114, 1116, 1118, 1144, 1146, 1148, 1264, 1266, 1268, 1354, 1356, 1358, 3244, 3246, 3248, 4204, 4206, 4208}, found 33