sub sieve {
  my $n = shift;
  my @composite;
  for my $i (2 .. int(sqrt($n))) {
    if (!$composite[$i]) {
      for (my $j = $i*$i; $j <= $n; $j += $i) {
        $composite[$j] = 1;
      }
    }
  }
  my @primes;
  for my $i (2 .. $n) {
    $composite[$i] || push @primes, $i;
  }
  @primes;
}


#include <algorithm>
#include <iostream>
#include <iterator>
#include <locale>
#include <vector>
#include "prime_sieve.hpp"

const int limit1 = 1000000;
const int limit2 = 10000000;

class prime_info {
public:
    explicit prime_info(int max) : max_print(max) {}
    void add_prime(int prime);
    void print(std::ostream& os, const char* name) const;
private:
    int max_print;
    int count1 = 0;
    int count2 = 0;
    std::vector<int> primes;
};

void prime_info::add_prime(int prime) {
    ++count2;
    if (prime < limit1)
        ++count1;
    if (count2 <= max_print)
        primes.push_back(prime);
}

void prime_info::print(std::ostream& os, const char* name) const {
    os << "First " << max_print << " " << name << " primes: ";
    std::copy(primes.begin(), primes.end(), std::ostream_iterator<int>(os, " "));
    os << '\n';
    os << "Number of " << name << " primes below " << limit1 << ": " << count1 << '\n';
    os << "Number of " << name << " primes below " << limit2 << ": " << count2 << '\n';
}

int main() {
    // find the prime numbers up to limit2
    prime_sieve sieve(limit2);

    // write numbers with groups of digits separated according to the system default locale
    std::cout.imbue(std::locale(""));

    // count and print safe/unsafe prime numbers
    prime_info safe_primes(35);
    prime_info unsafe_primes(40);
    for (int p = 2; p < limit2; ++p) {
        if (sieve.is_prime(p)) {
            if (sieve.is_prime((p - 1)/2))
                safe_primes.add_prime(p);
            else
                unsafe_primes.add_prime(p);
        }
    }
    safe_primes.print(std::cout, "safe");
    unsafe_primes.print(std::cout, "unsafe");
    return 0;
}


;Init Routine
*=$0801
	db $0E,$08,$0A,$00,$9E,$20,$28,$32,$30,$36,$34,$29,$00,$00,$00
*=$0810	;Start at $0810

	LDA #$A9		;opcode for LDA immediate
	STA smc_test

	LDA #'A'
	STA smc_test+1

	lda #$20		;opcode for JSR
	STA smc_test+2

	lda #<CHROUT
	STA smc_test+3

	lda #>CHROUT
	STA smc_test+4

smc_test:
	nop				;gets overwritten with LDA
	nop				;gets overwritten with #$41
	nop				;gets overwritten with JSR
	nop				;gets overwritten with <CHROUT
	nop				;gets overwritten with >CHROUT

	rts				;return to basic


constant limit = 1000
sequence primes = {}
sequence flags = repeat(1, limit)
for i=2 to floor(sqrt(limit)) do
    if flags[i] then
        for k=i*i to limit by i do
            flags[k] = 0
        end for
    end if
end for
for i=2 to limit do
    if flags[i] then
        primes &= i
    end if
end for
pp(primes,{pp_Maxlen,77})


isqrt = proc (s: int) returns (int)
    x0: int := s/2
    if x0=0 then return(s) end
    x1: int := (x0 + s/x0)/2
    while x1 < x0 do
        x0 := x1
        x1 := (x0 + s/x0)/2
    end
    return(x0)
end isqrt

sieve = proc (n: int) returns (array[bool])
    prime: array[bool] := array[bool]$fill(0,n+1,true)
    prime[0] := false
    prime[1] := false
    for p: int in int$from_to(2, isqrt(n)) do
        if prime[p] then
            for c: int in int$from_to_by(p*p,n,p) do
                prime[c] := false
            end
        end
    end
    return(prime)
end sieve

start_up = proc ()
    primeinfo = record [
        name: string,
        ps: array[int],
        maxps, n_1e6, n_1e7: int
    ]

    po: stream := stream$primary_output()
    prime: array[bool] := sieve(10000000)

    safe: primeinfo := primeinfo${
        name: "safe",
        ps: array[int]$[],
        maxps: 35,
        n_1e6: 0,
        n_1e7: 0
    }

    unsafe: primeinfo := primeinfo${
        name: "unsafe",
        ps: array[int]$[],
        maxps: 40,
        n_1e6: 0,
        n_1e7: 0
    }

    for p: int in int$from_to(2, 10000000) do
        if ~prime[p] then continue end
        ir: primeinfo
        if prime[(p-1)/2]
            then ir := safe
            else ir := unsafe
        end

        if array[int]$size(ir.ps) < ir.maxps then
            array[int]$addh(ir.ps,p)
        end
        if p<1000000 then ir.n_1e6 := ir.n_1e6 + 1 end
        if p<10000000 then ir.n_1e7 := ir.n_1e7 + 1 end
    end

    for ir: primeinfo in array[primeinfo]$elements(
                       array[primeinfo]$[safe, unsafe]) do
        stream$putl(po, "First " || int$unparse(ir.maxps)
                   || " " || ir.name || " primes:")
        for i: int in array[int]$elements(ir.ps) do
            stream$puts(po, int$unparse(i) || " ")
        end
        stream$putl(po, "\nThere are " || int$unparse(ir.n_1e6)
                      || " " || ir.name || " primes < 1,000,000.")
        stream$putl(po, "There are " || int$unparse(ir.n_1e7)
                      || " " || ir.name || " primes < 1,000,000.\n")
    end
end start_up


a: {print ["The result is:" 2+3]}
do a

userCode: input "Give me some code: "
do userCode


; requires AutoHotkey_H or AutoHotkey.dll
msgbox % eval("3 + 4")
msgbox % eval("4 + 4")
return

eval(expression)
{
global script
script =
(
    expression(){
    return %expression%
  }
)
renameFunction("expression", "")  ; remove any previous expressions
gosub load ; cannot use addScript inside a function yet
exp := "expression"
return %exp%()
}

load:
DllCall(A_AhkPath "\addScript","Str",script,"Uchar",0,"Cdecl UInt")
return

renameFunction(funcName, newname){
static
x%newname% := newname   ; store newname in a static variable so its memory is not freed
strput(newname, &x%newname%, strlen(newname) + 1)
if fnp := FindFunc(funcName)
  numput(&x%newname%, fnp+0, 0, "uint")
}


include ..\Utilitys.pmt

def sequence /# ( ini end [step] ) #/
    ( ) swap for 0 put endfor
enddef

1000 var limit

( 1 limit ) sequence

( 2 limit ) for >ps
    ( tps dup * limit tps ) for
        dup limit < if 0 swap set else drop endif
    endfor
    cps
endfor
( 1 limit 0 ) remove
pstack


pCache |> Seq.filter(fun n->isPrime((n-1)/2)) |> Seq.take 35 |> Seq.iter (printf "%d ")


USING: fry interpolate kernel literals math math.primes
sequences tools.memory.private ;
IN: rosetta-code.safe-primes

CONSTANT: primes $[ 10,000,000 primes-upto ]

: safe/unsafe ( -- safe unsafe )
    primes [ 1 - 2/ prime? ] partition ;

: count< ( seq n -- str ) '[ _ < ] count commas ;

: seq>commas ( seq -- str ) [ commas ] map " " join ;

: stats ( seq n -- head count1 count2 )
    '[ _ head seq>commas ] [ 1e6 count< ] [ 1e7 count< ] tri ;

safe/unsafe [ 35 ] [ 40 ] bi* [ stats ] [email protected]

[I
First 35 safe primes:
${5}
Safe prime count below  1,000,000: ${4}
Safe prime count below 10,000,000: ${3}

First 40 unsafe primes:
${2}
Unsafe prime count below  1,000,000: ${1}
Unsafe prime count below 10,000,000: ${}
I]


' version 19-01-2019
' compile with: fbc -s console

Const As UInteger max = 10000000
Dim As UInteger i, j, sc1, usc1, sc2, usc2
Dim As String safeprimes, unsafeprimes
Dim As UByte sieve()

ReDim sieve(max)
' 0 = prime, 1 = no prime
sieve(0) = 1 : sieve(1) = 1

For i = 4 To max Step 2
    sieve(i) = 1
Next
For i = 3 To Sqr(max) +1 Step 2
    If sieve(i) = 0 Then
        For j = i * i To max Step i * 2
            sieve(j) = 1
        Next
    End If
Next

usc1 = 1 : unsafeprimes = "2"
For i = 3 To 3001 Step 2
    If sieve(i) = 0 Then
        If sieve(i \ 2) = 0 Then
            sc1 += 1
            If sc1 <= 35 Then
                safeprimes += " " + Str(i)
            End If
        Else
            usc1 += 1
            If usc1 <= 40 Then
                unsafeprimes +=  " " + Str(i)
            End If
        End If
    End If
Next

For i = 3003 To max \ 10 Step 2
    If sieve(i) = 0 Then
        If sieve(i \ 2) = 0 Then
            sc1 += 1
        Else
            usc1 += 1
        End If
    End If
Next

sc2 = sc1 : usc2 = usc1
For i = max \ 10 +1 To max Step 2
    If sieve(i) = 0 Then
        If sieve(i \ 2) = 0  Then
            sc2 += 1
        Else
            usc2 += 1
        End If
    End If
Next

Print "the first 35 Safeprimes are: "; safeprimes
Print
Print "the first 40 Unsafeprimes are:  "; unsafeprimes
Print
Print "                  Safeprimes     Unsafeprimes"
Print "    Below         ---------------------------"
Print Using "##########,      ";  max \ 10; sc1; usc1
Print Using "##########,      ";  max     ; sc2; usc2

' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


100 DEF PROC graph f$
110   LOCAL x,y
120   PLOT 0,90
130   FOR x = -2 TO 2 STEP 0.02
140     LET y = VAL(f$)
150     DRAW TO x*50+100, y*50+90
160   NEXT x
170 END PROC


      expr$ = "PI^2 + 1"
      PRINT EVAL(expr$)


USER>Set cmd="Write ""Hello, World!"""
USER>Xecute cmd
Hello, World!

USER>Set fnc="(num1, num2) Set res=num1+num2 Quit res"
USER>Write $Xecute(fnc, 2, 3)
5


!run-blob !compile-string "(fake filename)" "!print \qHello world\q"


function iprimes_upto($limit)
{
    for ($i = 2; $i < $limit; $i++)
    {
	$primes[$i] = true;
    }

    for ($n = 2; $n < $limit; $n++)
    {
	if ($primes[$n])
	{
	    for ($i = $n*$n; $i < $limit; $i += $n)
	    {
		$primes[$i] = false;
	    }
	}
    }

    return $primes;
}

echo wordwrap(
    'Primes less or equal than 1000 are : ' . PHP_EOL .
    implode(' ', array_keys(iprimes_upto(1000), true, true)),
    100
);


safePrimes[end=undef] := select[primes[5,end], {|p| isPrime[(p-1)/2] }]
unsafePrimes[end=undef] := select[primes[2,end], {|p| p<5 or isPrime[(p-1)/2] }]

println["First 35 safe primes:  " + first[safePrimes[], 35]]
println["Safe primes below  1,000,000: " + length[safePrimes[1_000_000]]]
println["Safe primes below 10,000,000: " + length[safePrimes[10_000_000]]]

println["First 40 unsafe primes:  " + first[unsafePrimes[], 40]]
println["Unsafe primes below  1,000,000: " + length[unsafePrimes[1_000_000]]]
println["Unsafe primes below 10,000,000: " + length[unsafePrimes[10_000_000]]]


package main

import "fmt"

func sieve(limit uint64) []bool {
    limit++
    // True denotes composite, false denotes prime.
    c := make([]bool, limit) // all false by default
    c[0] = true
    c[1] = true
    // apart from 2 all even numbers are of course composite
    for i := uint64(4); i < limit; i += 2 {
        c[i] = true
    }
    p := uint64(3) // Start from 3.
    for {
        p2 := p * p
        if p2 >= limit {
            break
        }
        for i := p2; i < limit; i += 2 * p {
            c[i] = true
        }
        for {
            p += 2
            if !c[p] {
                break
            }
        }
    }
    return c
}

func commatize(n int) string {
    s := fmt.Sprintf("%d", n)
    if n < 0 {
        s = s[1:]
    }
    le := len(s)
    for i := le - 3; i >= 1; i -= 3 {
        s = s[0:i] + "," + s[i:]
    }
    if n >= 0 {
        return s
    }
    return "-" + s
}

func main() {
    // sieve up to 10 million
    sieved := sieve(1e7)
    var safe = make([]int, 35)
    count := 0
    for i := 3; count < 35; i += 2 {
        if !sieved[i] && !sieved[(i-1)/2] {
            safe[count] = i
            count++
        }
    }
    fmt.Println("The first 35 safe primes are:\n", safe, "\n")

    count = 0
    for i := 3; i < 1e6; i += 2 {
        if !sieved[i] && !sieved[(i-1)/2] {
            count++
        }
    }
    fmt.Println("The number of safe primes below 1,000,000 is", commatize(count), "\n")

    for i := 1000001; i < 1e7; i += 2 {
        if !sieved[i] && !sieved[(i-1)/2] {
            count++
        }
    }
    fmt.Println("The number of safe primes below 10,000,000 is", commatize(count), "\n")

    unsafe := make([]int, 40)
    unsafe[0] = 2 // since (2 - 1)/2 is not prime
    count = 1
    for i := 3; count < 40; i += 2 {
        if !sieved[i] && sieved[(i-1)/2] {
            unsafe[count] = i
            count++
        }
    }
    fmt.Println("The first 40 unsafe primes are:\n", unsafe, "\n")

    count = 1
    for i := 3; i < 1e6; i += 2 {
        if !sieved[i] && sieved[(i-1)/2] {
            count++
        }
    }
    fmt.Println("The number of unsafe primes below 1,000,000 is", commatize(count), "\n")

    for i := 1000001; i < 1e7; i += 2 {
        if !sieved[i] && sieved[(i-1)/2] {
            count++
        }
    }
    fmt.Println("The number of unsafe primes below 10,000,000 is", commatize(count), "\n")
}


(eval (list * 6 7))
   → 42
(eval '(* 6 7)) ;; quoted argument
   → 42
(eval (read-from-string "(* 6 7)"))
   → 42


import extensions'scripting;

public program()
{
    lscript.interpret("system'console.writeLine(""Hello World"")");
}


1> {ok, Tokens, _} = erl_scan:string("X + 4 * lists:sum([1,2,3,4]).").
...
2> {ok, [Form]} = erl_parse:parse_exprs(Tokens).
...
3> Bindings = erl_eval:add_binding('X', 17, erl_eval:new_bindings()).
[{'X',17}]
4> {value, Value, _} = erl_eval:expr(Form, Bindings).
{value,57,[{'X',17}]}
5> Value.
57


primes(N) = L =>
    A = new_array(N),
    foreach(I in 2..floor(sqrt(N)))
        if (var(A[I])) then
            foreach(J in I**2..I..N)
                A[J]=0
            end
         end
     end,
     L=[I : I in 2..N, var(A[I])].


import Text.Printf (printf)
import Data.Numbers.Primes (isPrime, primes)

main = do
  printf "First 35 safe primes: %s\n" (show $ take 35 safe)
  printf "There are %d safe primes below 100,000.\n" (length $ takeWhile (<1000000) safe)
  printf "There are %d safe primes below 10,000,000.\n\n" (length $ takeWhile (<10000000) safe)

  printf "First 40 unsafe primes: %s\n" (show $ take 40 unsafe)
  printf "There are %d unsafe primes below 100,000.\n" (length $ takeWhile (<1000000) unsafe)
  printf "There are %d unsafe primes below 10,000,000.\n\n" (length $ takeWhile (<10000000) unsafe)

  where safe = filter (\n -> isPrime ((n-1) `div` 2)) primes
        unsafe = filter (\n -> not (isPrime((n-1) `div` 2))) primes


public class SafePrimes {
    public static void main(String... args) {
        // Use Sieve of Eratosthenes to find primes
        int SIEVE_SIZE = 10_000_000;
        boolean[] isComposite = new boolean[SIEVE_SIZE];
        // It's really a flag indicating non-prime, but composite usually applies
        isComposite[0] = true;
        isComposite[1] = true;
        for (int n = 2; n < SIEVE_SIZE; n++) {
            if (isComposite[n]) {
                continue;
            }
            for (int i = n * 2; i < SIEVE_SIZE; i += n) {
                isComposite[i] = true;
            }
        }

        int oldSafePrimeCount = 0;
        int oldUnsafePrimeCount = 0;
        int safePrimeCount = 0;
        int unsafePrimeCount = 0;
        StringBuilder safePrimes = new StringBuilder();
        StringBuilder unsafePrimes = new StringBuilder();
        int safePrimesStrCount = 0;
        int unsafePrimesStrCount = 0;
        for (int n = 2; n < SIEVE_SIZE; n++) {
            if (n == 1_000_000) {
                oldSafePrimeCount = safePrimeCount;
                oldUnsafePrimeCount = unsafePrimeCount;
            }
            if (isComposite[n]) {
                continue;
            }
            boolean isUnsafe = isComposite[(n - 1) >>> 1];
            if (isUnsafe) {
                if (unsafePrimeCount < 40) {
                    if (unsafePrimeCount > 0) {
                        unsafePrimes.append(", ");
                    }
                    unsafePrimes.append(n);
                    unsafePrimesStrCount++;
                }
                unsafePrimeCount++;
            }
            else {
                if (safePrimeCount < 35) {
                    if (safePrimeCount > 0) {
                        safePrimes.append(", ");
                    }
                    safePrimes.append(n);
                    safePrimesStrCount++;
                }
                safePrimeCount++;
            }
        }

        System.out.println("First " + safePrimesStrCount + " safe primes: " + safePrimes.toString());
        System.out.println("Number of safe primes below 1,000,000: " + oldSafePrimeCount);
        System.out.println("Number of safe primes below 10,000,000: " + safePrimeCount);
        System.out.println("First " + unsafePrimesStrCount + " unsafe primes: " + unsafePrimes.toString());
        System.out.println("Number of unsafe primes below 1,000,000: " + oldUnsafePrimeCount);
        System.out.println("Number of unsafe primes below 10,000,000: " + unsafePrimeCount);

        return;
    }
}


IN: scratchpad "\"Hello, World!\" print" ( -- ) eval
Hello, World!
IN: scratchpad  4 5 "+" ( a b -- c ) eval
9


s" variable foo   1e fatan 4e f*" evaluate

f.      \ 3.14159...
1 foo !


package main
import (
	"fmt"
	"bitbucket.org/binet/go-eval/pkg/eval"
	"go/token"
)

func main() {
	w := eval.NewWorld();
	fset := token.NewFileSet();

	code, err := w.Compile(fset, "1 + 2")
	if err != nil {
		fmt.Println("Compile error");
		return
	}

	val, err := code.Run();
	if err != nil {
		fmt.Println("Run time error");
		return;
	}
	fmt.Println("Return value:", val) //prints, well, 3

}


(de sieve (N)
   (let Sieve (range 1 N)
      (set Sieve)
      (for I (cdr Sieve)
         (when I
            (for (S (nth Sieve (* I I)) S (nth (cdr S) I))
               (set S) ) ) )
      (filter bool Sieve) ) )


def is_prime:
  . as $n
  | if ($n < 2)         then false
    elif ($n % 2 == 0)  then $n == 2
    elif ($n % 3 == 0)  then $n == 3
    elif ($n % 5 == 0)  then $n == 5
    elif ($n % 7 == 0)  then $n == 7
    elif ($n % 11 == 0) then $n == 11
    elif ($n % 13 == 0) then $n == 13
    elif ($n % 17 == 0) then $n == 17
    elif ($n % 19 == 0) then $n == 19
    elif ($n % 23 == 0) then $n == 23
    elif ($n % 29 == 0) then $n == 29
    elif ($n % 31 == 0) then $n == 31
    else 37
         | until( (. * .) > $n or ($n % . == 0); . + 2)
         | . * . > $n
    end;

def task:

  # a helper function for keeping count:
  def record($p; counter6; counter7):
    if $p < 10000000
    then counter7 += 1
    | if $p < 1000000
      then counter6 += 1
      else .
      end
    else .
    end;

  # a helper function for recording up to $max values
  def recordValues($max; $p; a; done):
     if done then .
     elif a|length < $max
     then a += [$p] | done = ($max == (a|length))
     else .
     end;

  10000000 as $n
  | reduce (2, range(3;$n;2)) as $p ({};
      if $p|is_prime
      then if (($p - 1) / 2) | is_prime
           then recordValues(35; $p; .safeprimes; .safedone)
           | record($p; .nsafeprimes6; .nsafeprimes7)
           else  recordValues(40; $p; .unsafeprimes; .unsafedone)
           | record($p; .nunsafeprimes6; .nunsafeprimes7)
           end
      else .
      end )
  | "The first 35 safe primes are: ", .safeprimes[0:35],
    "\nThere are \(.nsafeprimes6) safe primes less than 1 million.",
    "\nThere are \(.nsafeprimes7) safe primes less than 10 million.",
    "",
    "\nThe first 40 unsafe primes are:", .unsafeprimes[0:40],
    "\nThere are \(.nunsafeprimes6) unsafe primes less than 1 million.",
    "\nThere are \(.nunsafeprimes7) unsafe primes less than 10 million."
;

task


using Primes, Formatting

function parseprimelist()
    primelist = primes(2, 10000000)
    safeprimes = Vector{Int64}()
    unsafeprimes = Vector{Int64}()
    for p in primelist
        if isprime(div(p - 1, 2))
            push!(safeprimes, p)
        else
            push!(unsafeprimes, p)
        end
    end
    println("The first 35 unsafe primes are: ", safeprimes[1:35])
    println("There are ", format(sum(map(x -> x < 1000000, safeprimes)), commas=true), " safe primes less than 1 million.")
    println("There are ", format(length(safeprimes), commas=true), " safe primes less than 10 million.")
    println("The first 40 unsafe primes are: ", unsafeprimes[1:40])
    println("There are ", format(sum(map(x -> x < 1000000, unsafeprimes)), commas=true), " unsafe primes less than 1 million.")
    println("There are ", format(length(unsafeprimes), commas=true), " unsafe primes less than 10 million.")
end

parseprimelist()


// Version 1.2.70

fun sieve(limit: Int): BooleanArray {
    // True denotes composite, false denotes prime.
    val c = BooleanArray(limit + 1) // all false by default
    c[0] = true
    c[1] = true
    // apart from 2 all even numbers are of course composite
    for (i in 4..limit step 2) c[i] = true
    var p = 3 // start from 3
    while (true) {
        val p2 = p * p
        if (p2 > limit) break
        for (i in p2..limit step 2 * p) c[i] = true
        while (true) {
            p += 2
            if (!c[p]) break
        }
    }
    return c
}

fun main(args: Array<String>) {
    // sieve up to 10 million
    val sieved = sieve(10_000_000)
    val safe = IntArray(35)
    var count = 0
    var i = 3
    while (count < 35) {
        if (!sieved[i] && !sieved[(i - 1) / 2]) safe[count++] = i
        i += 2
    }
    println("The first 35 safe primes are:")
    println(safe.joinToString(" ","[", "]\n"))

    count = 0
    for (j in 3 until 1_000_000 step 2) {
        if (!sieved[j] && !sieved[(j - 1) / 2]) count++
    }
    System.out.printf("The number of safe primes below 1,000,000 is %,d\n\n", count)

    for (j in 1_000_001 until 10_000_000 step 2) {
        if (!sieved[j] && !sieved[(j - 1) / 2]) count++
    }
    System.out.printf("The number of safe primes below 10,000,000 is %,d\n\n", count)

    val unsafe = IntArray(40)
    unsafe[0] = 2  // since (2 - 1)/2 is not prime
    count = 1
    i = 3
    while (count < 40) {
        if (!sieved[i] && sieved[(i - 1) / 2]) unsafe[count++] = i
        i += 2
    }
    println("The first 40 unsafe primes are:")
    println(unsafe.joinToString(" ","[", "]\n"))

    count = 1
    for (j in 3 until 1_000_000 step 2) {
        if (!sieved[j] && sieved[(j - 1) / 2]) count++
    }
    System.out.printf("The number of unsafe primes below 1,000,000 is %,d\n\n", count)

    for (j in 1_000_001 until 10_000_000 step 2) {
        if (!sieved[j] && sieved[(j - 1) / 2]) count++
    }
    System.out.printf("The number of unsafe primes below 10,000,000 is %,d\n\n", count)
}


10 LINE INPUT "Type an expression: ",A$
20 OPEN "CHAIN.TMP" FOR OUTPUT AS #1
30 PRINT #1, "70 LET Y=("+A$+")"
40 CLOSE #1
50 CHAIN MERGE "CHAIN.TMP",60,ALL
60 FOR X=0 TO 5
70 REM
80 PRINT X,Y
90 NEXT X
100 GOTO 10


Procedure Main()
   local bAdd := {|Label,n1,n2| Qout( Label ), QQout( n1 + n2 )}
   Eval( bAdd, "5+5 = ", 5, 5 )
   Eval( bAdd, "5-5 = ", 5, -5 )
   return

Upon execution you see:
5+5 = 10
5-5 =  0


value = XEQ( " temp = 1 + 2 + 3 ") ! value is assigned 6
! temp is undefined outside XEQ, if it was not defined before.

XEQ(" WRITE(Messagebox) 'Hello World !' ")

OPEN(FIle="my_file.txt")
READ(FIle="my_file.txt", Row=6) string
XEQ( string ) ! executes row 6 of my_file.txt


". 'a =: +/ 1 2 3' NB. execute a string to sum 1, 2 and 3 and assign to noun a


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.tools.FileObject;
import javax.tools.ForwardingJavaFileManager;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;
import javax.tools.ToolProvider;

public class Evaluator{
    public static void main(String[] args){
        new Evaluator().eval(
            "SayHello",
            "public class SayHello{public void speak(){System.out.println(\"Hello world\");}}",
            "speak"
        );
    }

    void eval(String className, String classCode, String methodName){
        Map<String, ByteArrayOutputStream> classCache = new HashMap<>();
        JavaCompiler                       compiler   = ToolProvider.getSystemJavaCompiler();

        if ( null == compiler )
            throw new RuntimeException("Could not get a compiler.");

        StandardJavaFileManager                            sfm  = compiler.getStandardFileManager(null, null, null);
        ForwardingJavaFileManager<StandardJavaFileManager> fjfm = new ForwardingJavaFileManager<StandardJavaFileManager>(sfm){
            @Override
            public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling)
                    throws IOException{
                if (StandardLocation.CLASS_OUTPUT == location && JavaFileObject.Kind.CLASS == kind)
                    return new SimpleJavaFileObject(URI.create("mem:///" + className + ".class"), JavaFileObject.Kind.CLASS){
                        @Override
                        public OutputStream openOutputStream()
                                throws IOException{
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            classCache.put(className, baos);
                            return baos;
                        }
                    };
                else
                    throw new IllegalArgumentException("Unexpected output file requested: " + location + ", " + className + ", " + kind);
            }
        };
        List<JavaFileObject> files = new LinkedList<JavaFileObject>(){{
            add(
                new SimpleJavaFileObject(URI.create("string:///" + className + ".java"), JavaFileObject.Kind.SOURCE){
                    @Override
                    public CharSequence getCharContent(boolean ignoreEncodingErrors){
                        return classCode;
                    }
                }
            );
        }};

        // Now we can compile!
        compiler.getTask(null, fjfm, null, null, null, files).call();

        try{
            Class<?> clarse = new ClassLoader(){
                @Override
                public Class<?> findClass(String name){
                    if (! name.startsWith(className))
                        throw new IllegalArgumentException("This class loader is for " + className + " - could not handle \"" + name + '"');
                    byte[] bytes = classCache.get(name).toByteArray();
                    return defineClass(name, bytes, 0, bytes.length);
                }
            }.loadClass(className);

            // Invoke a method on the thing we compiled
            clarse.getMethod(methodName).invoke(clarse.newInstance());

        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException x){
            throw new RuntimeException("Run failed: " + x, x);
        }
    }
}


eratos: proc options (main) reorder;

dcl i  fixed bin (31);
dcl j  fixed bin (31);
dcl n  fixed bin (31);
dcl sn fixed bin (31);

dcl hbound builtin;
dcl sqrt   builtin;

dcl sysin    file;
dcl sysprint file;

get list (n);
sn = sqrt(n);

begin;
  dcl primes(n) bit (1) aligned init ((*)((1)'1'b));

  i = 2;

  do while(i <= sn);
    do j = i ** 2 by i to hbound(primes, 1);
      /* Adding a test would just slow down processing! */
      primes(j) = '0'b;
     end;

    do i = i + 1 to sn until(primes(i));
    end;
  end;

  do i = 2 to hbound(primes, 1);
    if primes(i) then
      put data(i);
  end;
end;
end eratos;


#!/bin/ksh

# Safe primes and unsafe primes

#	# Variables:
#
integer safecnt=0 safedisp=35 safecnt1M=0
integer unsacnt=0 unsadisp=40 unsacnt1M=0
typeset -a safeprime unsafeprime

#	# Functions:
#

#	# Function _isprime(n) return 1 for prime, 0 for not prime
#
function _isprime {
	typeset _n ; integer _n=$1
	typeset _i ; integer _i

	(( _n < 2 )) && return 0
	for (( _i=2 ; _i*_i<=_n ; _i++ )); do
		(( ! ( _n % _i ) )) && return 0
	done
	return 1
}

#	# Function _issafe(p) return 1 for safe prime, 0 for not
#
function _issafe {
	typeset _p ; integer _p=$1

	_isprime $(( (_p - 1) / 2 ))
	return $?
}

 ######
# main #
 ######

for ((n=3; n<=10000000; n++)); do
	_isprime ${n}
	(( ! $? )) && continue
	_issafe ${n}
	if (( $? )); then
		(( safecnt++ ))
		(( safecnt < safedisp)) && safeprime+=( ${n} )
		(( n <= 999999 )) && safecnt1M=${safecnt}
	else
		(( unsacnt++ ))
		(( unsacnt < unsadisp)) && unsafeprime+=( ${n} )
		(( n <= 999999 )) && unsacnt1M=${unsacnt}
	fi
done

print "Safe primes:\n${safeprime[*]}"
print "There are ${safecnt1M} under 1,000,000"
print "There are ${safecnt} under 10,000,000\n"

print "Unsafe primes:\n${unsafeprime[*]}"
print "There are ${unsacnt1M} under 1,000,000"
print "There are ${unsacnt} under 10,000,000"


-- FUNCS:
local function T(t) return setmetatable(t, {__index=table}) end
table.filter = function(t,f) local s=T{} for _,v in ipairs(t) do if f(v) then s[#s+1]=v end end return s end
table.map = function(t,f,...) local s=T{} for _,v in ipairs(t) do s[#s+1]=f(v,...) end return s end
table.firstn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end

-- SIEVE:
local sieve, safe, unsafe, floor, N = {}, T{}, T{}, math.floor, 10000000
for i = 2,N do sieve[i]=true end
for i = 2,N do if sieve[i] then for j=i*i,N,i do sieve[j]=nil end end end
for i = 2,N do if sieve[i] then local t=sieve[floor((i-1)/2)] and safe or unsafe t[#t+1]=i end end

-- TASKS:
local function commafy(i) return tostring(i):reverse():gsub("(%d%d%d)","%1,"):reverse():gsub("^,","") end
print("First 35 safe primes        :  " .. safe:firstn(35):map(commafy):concat(" "))
print("# safe primes < 1,000,000   :  " .. commafy(#safe:filter(function(v) return v<1e6 end)))
print("# safe primes < 10,000,000  :  " .. commafy(#safe))
print("First 40 unsafe primes      :  " .. unsafe:firstn(40):map(commafy):concat(" "))
print("# unsafe primes < 1,000,000 :  " .. commafy(#unsafe:filter(function(v) return v<1e6 end)))
print("# unsafe primes < 10,000,000:  " .. commafy(#unsafe))


var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');

typeof foo; // 'object'
typeof bar; // 'string'


/* Runtime evaluation, in Jsish */
var foo = eval('{value: 42}');
eval('var bar = "Hello, world!";');

;typeof foo;
;foo.value;
;typeof bar;
;bar;

/*
=!EXPECTSTART!=
typeof foo ==> object
foo.value ==> 42
typeof bar ==> string
bar ==> Hello, world!
=!EXPECTEND!=
*/


$ kotlinc
Welcome to Kotlin version 1.2.31 (JRE 1.8.0_162-8u162-b12-0ubuntu0.16.04.2-b12)
Type :help for help, :quit for quit
>>> 20 + 22
42
>>> 5 * Math.sqrt(81.0)
45.0
>>> fun triple(x: Int) = x * 3
>>> triple(16)
48
>>> :quit


//code, fragment name, autocollect, inplaintext
local(mycode = "'Hello world, it is '+date")
sourcefile('['+#mycode+']','arbritraty_name', true, true)->invoke

'\r'

var(x = 100)
local(mycode = "Outside Lasso\r['Hello world, var x is '+var(x)]")
// autocollect (3rd param): return any output generated
// inplaintext (4th param): if true, assumes this is mixed Lasso and plain text,
//		requires Lasso code to be in square brackets or other supported code block demarkation.
sourcefile(#mycode,'arbritraty_name', true, true)->invoke

'\r'

var(y = 2)
local(mycode = "'Hello world, is there output?\r'
var(x) *= var(y)")
// autocollect (3rd param): as false, no output returned
// inplaintext (4th param): as false, assumes this is Lasso code, no mixed-mode Lasso and text.
sourcefile(#mycode,'arbritraty_name', false, false)->invoke
'var x is now: '+$x

'\r'

var(z = 3)
local(mycode = "var(x) *= var(z)")
sourcefile(#mycode,'arbritraty_name', false, false)->invoke
'var x is now: '+$x


100H:

DECLARE PRIME$MAX LITERALLY '5000';

/* CREATE SIEVE OF GIVEN SIZE */
MAKE$SIEVE: PROCEDURE(START, SIZE);
    DECLARE (START, SIZE, M, N) ADDRESS;
    DECLARE PRIME BASED START BYTE;

    PRIME(0)=0; /* 0 AND 1 ARE NOT PRIMES */
    PRIME(1)=0;
    DO N=2 TO SIZE;
        PRIME(N)=1; /* ASSUME ALL OTHERS ARE PRIME AT BEGINNING */
    END;

    DO N=2 TO SIZE;
        IF PRIME(N) THEN DO; /* IF A NUMBER IS PRIME... */
            DO M=N*N TO SIZE BY N;
                PRIME(M) = 0; /* THEN ITS MULTIPLES ARE NOT */
            END;
        END;
    END;
END MAKE$SIEVE;

/* CP/M CALLS */
BDOS: PROCEDURE(FUNC, ARG);
    DECLARE FUNC BYTE, ARG ADDRESS;
    GO TO 5;
END BDOS;

DECLARE BDOS$EXIT  LITERALLY '0',
        BDOS$PRINT LITERALLY '9';

/* PRINT A 16-BIT NUMBER */
PRINT$NUMBER: PROCEDURE(N);
    DECLARE (N, P) ADDRESS;
    DECLARE S (8) BYTE INITIAL ('.....',10,13,'$');
    DECLARE C BASED P BYTE;
    P = .S(5);
DIGIT:
    P = P - 1;
    C = (N MOD 10) + '0';
    N = N / 10;
    IF N > 0 THEN GO TO DIGIT;
    CALL BDOS(BDOS$PRINT, P);
END PRINT$NUMBER;

/* PRINT ALL PRIMES UP TO N */
PRINT$PRIMES: PROCEDURE(N, SIEVE);
    DECLARE (I, N, SIEVE) ADDRESS;
    DECLARE PRIME BASED SIEVE BYTE;
    CALL MAKE$SIEVE(SIEVE, N);
    DO I = 2 TO N;
        IF PRIME(I) THEN CALL PRINT$NUMBER(I);
    END;
END PRINT$PRIMES;

CALL PRINT$PRIMES(PRIME$MAX, .MEMORY);

CALL BDOS(BDOS$EXIT, 0);
EOF


showSafePrimes := proc(n::posint)
local prime_list, k;
prime_list := [5];
for k to n - 1 do
  prime_list := [op(prime_list), NumberTheory:-NextSafePrime(prime_list[-1])];
end do;
return prime_list;
end proc;

showUnsafePrimes := proc(n::posint)
local prime_num, k;
prime_num := [2];
for k to n-1 do
  prime_num := [op(prime_num), nextprime(prime_num[-1])];
end do;
return remove(x -> member(x, showSafePrimes(n)), prime_num);
end proc:

countSafePrimes := proc(n::posint)
local counts, prime;
counts := 0;
prime := 5;
while prime < n do prime := NumberTheory:-NextSafePrime(prime);
  counts := counts + 1;
end do;
return counts;
end proc;

countUnsafePrimes := proc(n::posint)
local safe_counts, total;
safe_counts := countSafePrimes(n);
total := NumberTheory:-PrimeCounting(n);
return total - safe_counts;
end proc;

showSafePrimes(35);
showUnsafePrimes(40);
countSafePrimes(1000000);
countSafePrimes(10000000);
countUnsafePrimes(1000000);
countUnsafePrimes(10000000);


ClearAll[SafePrimeQ, UnsafePrimeQ]
SafePrimeQ[n_Integer] := PrimeQ[n] \[And] PrimeQ[(n - 1)/2]
UnsafePrimeQ[n_Integer] := PrimeQ[n] \[And] ! PrimeQ[(n - 1)/2]

res = {};
i = 1;
While[Length[res] < 35,
 test = SafePrimeQ[Prime[i]];
 If[test, AppendTo[res, Prime[i]]];
 i++
 ]
res

Count[Range[PrimePi[10^6]], _?(Prime /* SafePrimeQ)]
Count[Range[PrimePi[10^7]], _?(Prime /* SafePrimeQ)]

res = {};
i = 1;
While[Length[res] < 40,
 test = UnsafePrimeQ[Prime[i]];
 If[test, AppendTo[res, Prime[i]]];
 i++
 ]
res

Count[Range[PrimePi[10^6]], _?(Prime /* UnsafePrimeQ)]
Count[Range[PrimePi[10^7]], _?(Prime /* UnsafePrimeQ)]


import sequtils, strutils

const N = 10_000_000

# Erathostene's Sieve. Only odd values are represented. False value means prime.
var sieve: array[N div 2 + 1, bool]
sieve[0] = true   # 1 is not prime.

for i in 1..sieve.high:
  if not sieve[i]:
    let n = 2 * i + 1
    for k in countup(n * n, N, 2 * n):
      sieve[k shr 1] = true

proc isprime(n: Positive): bool =
  ## Check if a number is prime.
  n == 2 or (n and 1) != 0 and not sieve[n shr 1]

proc classifyPrimes(): tuple[safe, unsafe: seq[int]] =
  ## Classify prime numbers in safe and unsafe numbers.
  for n in 2..N:
    if n.isprime():
      if (n shr 1).isprime():
        result[0].add n
      else:
        result[1].add n

when isMainModule:

  let (safe, unsafe) = classifyPrimes()

  echo "First 35 safe primes:"
  echo safe[0..<35].join(" ")
  echo "Count of safe primes below  1_000_000:",
      ($safe.filterIt(it < 1_000_000).len).insertSep(',').align(7)
  echo "Count of safe primes below 10_000_000:",
      ($safe.filterIt(it < 10_000_000).len).insertSep(',').align(7)

  echo "First 40 unsafe primes:"
  echo unsafe[0..<40].join(" ")
  echo "Count of unsafe primes below  1_000_000:",
      ($unsafe.filterIt(it < 1_000_000).len).insertSep(',').align(8)
  echo "Count of unsafe primes below 10_000_000:",
      ($unsafe.filterIt(it < 10_000_000).len).insertSep(',').align(8)


program Sophie;
{ Find and count Sophie Germain primes }
{ uses unit mp_prime out of mparith of Wolfgang Ehrhardt
* http://wolfgang-ehrhardt.de/misc_en.html#mparith
  http://wolfgang-ehrhardt.de/mp_intro.html }
{$APPTYPE CONSOLE}
uses
 mp_prime,sysutils;
var
  pS0,pS1:TSieve;
procedure SafeOrNoSavePrimeOut(totCnt:NativeInt;CntSafe:boolean);
var
  cnt,pr,pSG,testPr : NativeUint;
begin
  prime_sieve_reset(pS0,1);
  prime_sieve_reset(pS1,1);
  cnt := 0;
// memorize prime of the sieve, because sometimes prime_sieve_next(pS1) is to far ahead.
  testPr := prime_sieve_next(pS1);
  IF CntSafe then
  Begin
    writeln('First ',totCnt,' safe primes');
    repeat
      pr := prime_sieve_next(pS0);
      pSG := 2*pr+1;
      while testPr< pSG do
        testPr := prime_sieve_next(pS1);
      if pSG = testPr then
      begin
        write(pSG,',');
        inc(cnt);
      end;
    until cnt >= totCnt
  end
  else
  Begin
    writeln('First ',totCnt,' unsafe primes');
    repeat
      pr := prime_sieve_next(pS0);
      pSG := (pr-1) DIV 2;
      while testPr< pSG do
        testPr := prime_sieve_next(pS1);
      if pSG <> testPr then
      begin
        write(pr,',');
        inc(cnt);
      end;
    until cnt >= totCnt;
  end;
  writeln(#8,#32);
end;

function CountSafePrimes(Limit:NativeInt):NativeUint;
var
  cnt,pr,pSG,testPr : NativeUint;
begin
  prime_sieve_reset(pS0,1);
  prime_sieve_reset(pS1,1);
  cnt := 0;
  testPr := 0;
  repeat
    pr := prime_sieve_next(pS0);
    pSG := 2*pr+1;
    while testPr< pSG do
      testPr := prime_sieve_next(pS1);
    if pSG = testPr then
      inc(cnt);
  until pSG >= Limit;
  CountSafePrimes := cnt;
end;

procedure CountSafePrimesOut(Limit:NativeUint);
Begin
  writeln('there are ',CountSafePrimes(limit),' safe primes out of ',
          primepi32(limit),' primes up to ',Limit);
end;

procedure CountUnSafePrimesOut(Limit:NativeUint);
var
  prCnt: NativeUint;
Begin
  prCnt := primepi32(limit);
  writeln('there are ',prCnt-CountSafePrimes(limit),' unsafe primes out of ',
          prCnt,' primes up to ',Limit);
end;

var
  T1,T0 : INt64;
begin
  T0 :=gettickcount64;
  prime_sieve_init(pS0,1);
  prime_sieve_init(pS1,1);
//Find and display (on one line) the first  35  safe primes.
  SafeOrNoSavePrimeOut(35,true);
//Find and display the  count  of the safe primes below  1,000,000.
  CountSafePrimesOut(1000*1000);
//Find and display the  count  of the safe primes below 10,000,000.
  CountSafePrimesOut(10*1000*1000);
//Find and display (on one line) the first  40  unsafe primes.
  SafeOrNoSavePrimeOut(40,false);
//Find and display the  count  of the unsafe primes below  1,000,000.
  CountUnSafePrimesOut(1000*1000);
//Find and display the  count  of the unsafe primes below 10,000,000.
  CountUnSafePrimesOut(10*1000*1000);
  writeln;
  CountSafePrimesOut(1000*1000*1000);
  T1 :=gettickcount64;
  writeln('runtime ',T1-T0,' ms');
end.


'Dimension a numerical and string array
Dim myArray(5)
Dim myStringArray$(5)

'Fill both arrays with the appropriate data
For i = 0 To 5
    myArray(i) = i
    myStringArray$(i) = "String - " + str$(i)
Next i

'Set two variables with the names of each array
numArrayName$ = "myArray"
strArrayName$ = "myStringArray"

'Retrieve the array data by evaluating a string
'that correlates to the array
For i = 0 To 5
    Print Eval$(numArrayName$ + "(" + str$(i) + ")")
    Print Eval$(strArrayName$ + "$(" + str$(i) + ")")
Next i


f = loadstring(s) -- load a string as a function. Returns a function.

one = loadstring"return 1" -- one() returns 1

two = loadstring"return ..." -- two() returns the arguments passed to it


Module checkit {
      Module dummy {
            i++
            Print Number
      }
      \\ using Stack New { } we open a new stack for values, and old one connected back at the end
      \\ using block For This {} we erase any new definition, so we erase i (which Local make a new one)
      a$={
            Stack New {
                  For this {
                        Local i
                        for i=1 to 10 : print i : next i
                  }
            }
            If valid(k) then print k
      }
      i=500
      k=600
      Push 1000
      inline a$
      Print i=500
      Print Number=1000
      \\ eval an expression
      Print Eval("i+k")
      \\ eval a function
      Print Function("{read x : = x**2}", 2)=4
      Dim k(10)=123
      \\ eval array only
      Print array("k()", 2)=123
      Push 10, 10
      \\ call a module by make it inline first
      inline code dummy, dummy
      Print i=502
}
CheckIt


Print[ToExpression["1 + 1"]];
Print[ToExpression["Print[\"Hello, world!\"]; 10!"]];
x = 5;
Print[ToExpression["x!"]];
Print[ToExpression["Module[{x = 8}, x!]"]];
Print[MemoryConstrained[ToExpression["Range[5]"], 10000, {}]];
Print[MemoryConstrained[ToExpression["Range[10^5]"], 10000, {}]];
Print[TimeConstrained[ToExpression["Pause[1]; True"], 2, False]];
Print[TimeConstrained[ToExpression["Pause[60]; True"], 2, False]];


function testEval
    fprintf('Expressions:\n')
    x = eval('5+10^2')
    eval('y = (x-100).*[1 2 3]')
    eval('z = strcat(''my'', '' string'')')
    try
        w eval(' = 45')
    catch
        fprintf('Runtime error: interpretation of w is a function\n\n')
    end
    % eval('v') = 5
    % Invalid at compile-time as MATLAB interprets as using eval as a variable

    fprintf('Other Statements:\n')
    nl = sprintf('\n');
    eval(['for k = 1:20' nl ...
              'fprintf(''%.3f\n'', k)' nl ...
              'if k == 3' nl ...
                  'break' nl ...
              'end' nl ...
          'end'])
    true == eval('1')
    try
        true eval(' == 1')
    catch
        fprintf('Runtime error: interpretation of == 1 is of input to true\n\n')
    end

    fprintf('Programming on the fly:\n')
    userIn = true;
    codeBlock = '';
    while userIn
        userIn = input('Enter next line of code: ', 's');
        codeBlock = [codeBlock nl userIn];
    end
    eval(codeBlock)
end


CREATE OR REPLACE PACKAGE sieve_of_eratosthenes AS
  TYPE array_of_booleans IS varray(100000000) OF BOOLEAN;
  TYPE table_of_integers IS TABLE OF INTEGER;
  FUNCTION find_primes (n NUMBER) RETURN table_of_integers pipelined;
END sieve_of_eratosthenes;
/

CREATE OR REPLACE PACKAGE BODY sieve_of_eratosthenes AS
  FUNCTION find_primes (n NUMBER) RETURN table_of_integers pipelined IS
      flag array_of_booleans;
      ptr  INTEGER;
      i    INTEGER;
  BEGIN
      flag := array_of_booleans(FALSE, TRUE);
      flag.extend(n - 2, 2);
      ptr  := 1;
      << outer_loop >>
      WHILE ptr * ptr <= n LOOP
          WHILE NOT flag(ptr) LOOP
              ptr := ptr + 1;
          END LOOP;
          i := ptr * ptr;
          WHILE i <= n LOOP
              flag(i) := FALSE;
              i := i + ptr;
          END LOOP;
          ptr := ptr + 1;
      END LOOP outer_loop;
      FOR i IN 1 .. n LOOP
          IF flag(i) THEN
              pipe ROW (i);
          END IF;
      END LOOP;
      RETURN;
  END find_primes;
END sieve_of_eratosthenes;
/


use ntheory qw(forprimes is_prime);

my $upto = 1e7;
my %class = ( safe => [], unsafe => [2] );

forprimes {
    push @{$class{ is_prime(($_-1)>>1) ? 'safe' : 'unsafe' }}, $_;
} 3, $upto;

for (['safe', 35], ['unsafe', 40]) {
    my($type, $quantity) = @$_;
    print  "The first $quantity $type primes are:\n";
    print join(" ", map { comma($class{$type}->[$_-1]) } 1..$quantity), "\n";
    for my $q ($upto/10, $upto) {
        my $n = scalar(grep { $_ <= $q } @{$class{$type}});
        printf "The number of $type primes up to %s: %s\n", comma($q), comma($n);
    }
}

sub comma {
    (my $s = reverse shift) =~ s/(.{3})/$1,/g;
    $s =~ s/,(-?)$/$1/;
    $s = reverse $s;
}


with javascript_semantics
sequence safe = {}, unsafe = {}
function filter_range(integer lo, hi)
    while true do
        integer p = get_prime(lo)
        if p>hi then return lo end if
        if p>2 and is_prime((p-1)/2) then
            safe &= p
        else
            unsafe &= p
        end if
        lo += 1
    end while
end function
integer lo = filter_range(1,1_000_000),
        ls = length(safe),
        lu = length(unsafe)
{} = filter_range(lo,10_000_000)
printf(1,"The first 35 safe primes: %v\n",{safe[1..35]})
printf(1,"Count of safe primes below 1,000,000: %,d\n",ls)
printf(1,"Count of safe primes below 10,000,000: %,d\n",length(safe))
printf(1,"The first 40 unsafe primes: %v\n",{unsafe[1..40]})
printf(1,"Count of unsafe primes below 1,000,000: %,d\n",lu)
printf(1,"Count of unsafe primes below 10,000,000: %,d\n",length(unsafe))


/* Here is how to create a function and return a value at runtime. In the first example,
the function is made global, i.e. it still exists after the statement is run. In the second example, the function
is declared local. The evaluated string may read or write any variable defined before eval_string is run. */

kill(f)$

eval_string("block(f(x) := x^2 + 1, f(2))");
5

fundef(f);
/* f(x) := x^2 + 1 */

eval_string("block([f], local(f), f(x) := x^3 + 1, f(2))");
9

fundef(f);
/* f(x) := x^2 + 1 */


exec("println \"hello, world\"")
exec("a = 1\nif a = 1\nprintln \"a is 1\"\nend\nprintln \"test\"")


import ../compiler/[nimeval, llstream, ast], strformat, os

let std = findNimStdLibCompileTime()
let modules = [std, std / "pure", std / "std", std / "core"]
var intr = createInterpreter("script", modules)

#dynamic variable
let varname = commandLineParams()[0]
let expr = commandLineParams()[1]

#wrap the naked variable name and expression in a definition and proc,respectively to create valid code
#for simplicity, the variable will always be an int, but one could of course define the type at runtime
#globals and procs must be exported with * to be accessable
#we also need to import any modules needed by the runtime code
intr.evalScript(llStreamOpen(&"import math,sugar; var {varname}*:int; proc output*():auto = {expr}"))

for i in 0..2:
  #set 'varname' to a value
  intr.getGlobalValue(intr.selectUniqueSymbol(varname)).intval = i
  #evaluate the expression and get the result
  let output = intr.callRoutine(intr.selectRoutine("output"), [])
  #depending on the expression, the result could be any type
  #as an example, here we check for int,float,or string
  case output.kind
  of nkIntLit:
    echo expr, " = ", output.intval
  of nkFloatLit:
    echo expr, " = ", output.floatval
  of nkStrLit:
    echo expr, " = ", output.strval
  else:
    discard

destroyInterpreter(intr)


"[ [ $a, 12], [$b, 1.2], [ $c, [ $aaa, $bbb, $ccc ] ], [ $torun, #first ] ]" perform .s
[1] (List) [[a, 12], [b, 1.2], [c, [aaa, bbb, ccc]], [torun, #first]]

"12 13 +" perform
[1:interpreter] ExCompiler : Can't evaluate <+>


   a = .array~of(1, 2, 3)
   ins = "loop num over a; say num; end"
   interpret ins


  function ExecSeries(string s,double b,e,i) as string
  '===================================================
  '
  sys a,p
  string v,u,tab,cr,er
  '
  'PREPARE OUTPUT BUFFER
  '
  p=1
  cr=chr(13) chr(10)
  tab=chr(9)
  v=nuls 4096
  mid v,p,s+cr+cr
  p+=4+len s
  '
  double x,y,z 'shared variables
  '
  'COMPILE
  '
  a=compile s
  er=error
  if er then
    print "runtime error: "  er : exit function
  end if
  '
  'EXECUTE
  '
  for x=b to e step i
    if p+128>=len v then
      v+=nuls len(v) 'extend buffer
    end if
    call a
    u=str(x) tab str(y) cr
    mid v,p,u : p+=len u
  next
  '
  freememory a 'release compiled code
  '
  return left v,p-1 'results
  '
  end function

  '=====
  'TESTS
  '=====

  'Expression, StartVal, EndVal stepVal, Increment

  print ExecSeries "y=x*x*x", 1, 10, 1
  print ExecSeries "y=sqrt x",1, 9 , 1


use "time" // for testing
use "collections"

class Primes is Iterator[U32] // returns an Iterator of found primes...
  let _bitmask: Array[U8] = [ 1; 2; 4; 8; 16; 32; 64; 128 ]
  var _lmt: USize
  let _cmpsts: Array[U8]
  var _ndx: USize = 2
  var _curr: U32 = 2

  new create(limit: U32) ? =>
    _lmt = USize.from[U32](limit)
    let sqrtlmt = USize.from[F64](F64.from[U32](limit).sqrt())
    _cmpsts = Array[U8].init(0, (_lmt + 8) / 8) // already zeroed; bit array
    _cmpsts(0)? = 3 // mark 0 and 1 as not prime!
    if sqrtlmt < 2 then return end
    for p in Range[USize](2, sqrtlmt + 1) do
      if (_cmpsts(p >> 3)? and _bitmask(p and 7)?) == 0 then
        var s = p * p // cull start address for p * p!
        let slmt = (s + (p << 3)).min(_lmt + 1)
        while s < slmt do
          let msk = _bitmask(s and 7)?
          var c = s >> 3
          while c < _cmpsts.size() do
            _cmpsts(c)? = _cmpsts(c)? or msk
            c = c + p
          end
          s = s + p
        end
      end
    end

  fun ref has_next(): Bool val => _ndx < (_lmt + 1)

  fun ref next(): U32 ? =>
    _curr = U32.from[USize](_ndx); _ndx = _ndx + 1
    while (_ndx <= _lmt) and ((_cmpsts(_ndx >> 3)? and _bitmask(_ndx and 7)?) != 0) do
      _ndx = _ndx + 1
    end
    _curr

actor Main
  new create(env: Env) =>
    let limit: U32 = 1_000_000_000
    try
      env.out.write("Primes to 100:  ")
      for p in Primes(100)? do env.out.write(p.string() + " ") end
      var count: I32 = 0
      for p in Primes(1_000_000)? do count = count + 1 end
      env.out.print("\nThere are " + count.string() + " primes to a million.")
      let t = Time
      let start = t.millis()
      let prms = Primes(limit)?
      let elpsd = t.millis() - start
      count = 0
      for _ in prms do count = count + 1 end
      env.out.print("Found " + count.string() + " primes to " + limit.string() + ".")
      env.out.print("This took " + elpsd.string() + " milliseconds.")
    end


#MAX=10000000
Global Dim P.b(#MAX) : FillMemory(@P(),#MAX,1,#PB_Byte)
Global NewList Primes.i()
Global NewList SaveP.i()
Global NewList UnSaveP.i()

For n=2 To Sqr(#MAX)+1 : If P(n) : m=n*n : While m<=#MAX : P(m)=0 : m+n : Wend : EndIf : Next
For i=2 To #MAX : If p(i) : AddElement(Primes()) : Primes()=i : EndIf : Next

ForEach Primes()
  If P((Primes()-1)/2) And Primes()>3 : AddElement(SaveP()) : SaveP()=Primes() : If Primes()<1000000 : c1+1 : EndIf
  Else
    AddElement(UnSaveP()) : UnSaveP()=Primes() : If Primes()<1000000 : c2+1 : EndIf
  EndIf
Next

OpenConsole()
PrintN("First 35 safe primes:")
If FirstElement(SaveP())
  For i=1 To 35 : Print(Str(SaveP())+" ") : NextElement(SaveP()) : Next
EndIf
PrintN(~"\nThere are "+FormatNumber(c1,0,".","'")+" safe primes below 1'000'000")
PrintN("There are "+FormatNumber(ListSize(SaveP()),0,".","'")+" safe primes below 10'000'000")
PrintN("")
PrintN("First 40 unsafe primes:")
If FirstElement(UnSaveP())
  For i=1 To 40 : Print(Str(UnSaveP())+" ") : NextElement(UnSaveP()) : Next
EndIf
PrintN(~"\nThere are "+FormatNumber(c2,0,".","'")+" unsafe primes below 1'000'000")
PrintN("There are "+FormatNumber(ListSize(UnSaveP()),0,".","'")+" unsafe primes below 10'000'000")
Input()


declare
  %% simplest case: just evaluate expressions without bindings
  R1 = {Compiler.virtualStringToValue "{Abs ~42}"}
  {Show R1}

  %% eval expressions with additional bindings and
  %% the possibility to kill the evaluation by calling KillProc
  KillProc
  R2 = {Compiler.evalExpression "{Abs A}" unit('A':~42) ?KillProc}
  {Show R2}

  %% full control: add and remove bindings, eval expressions or
  %% statements, set compiler switches etc.
  Engine = {New Compiler.engine init}
  {Engine enqueue(setSwitch(expression false))} %% statements instead of expr.
  {Engine enqueue(mergeEnv(env('A':42 'System':System)))}
  {Engine enqueue(feedVirtualString("{System.show A}"))}


runme(f)={
  f()
};

runme( ()->print("Hello world!") )


-- demo\rosetta\Runtime_evaluation.exw
without javascript_semantics
requires("1.0.1")
include eval.e  -- (not an autoinclude, pulls in around 90% of the interpreter/compiler proper)

string code = """
integer i = 0
bool r_init = false
sequence r
if not r_init then r = {} end if
for k=1 to 4 do
    i += k
    r &= k
end for
"""
?eval(code,{"i","r"})                           -- prints {10,{1,2,3,4}}
?eval(code,{"r"},{{"r_init",true},{"r",{5}}})   -- prints {5,1,2,3,4}
?eval(code,{"i"},{{"i",15}})                    -- prints {25}
{} = eval(`puts(1,"Hello World\n")`)            -- prints Hello World


define eratostenes(n);
lvars bits = inits(n), i, j;
for i from 2 to n do
   if bits(i) = 0 then
      printf('' >< i, '%s\n');
      for j from 2*i by i to n do
         1 -> bits(j);
      endfor;
   endif;
endfor;
enddefine;


primes =[]
sp =[]
usp=[]
n = 10000000
if 2<n:
    primes.append(2)
for i in range(3,n+1,2):
    for j in primes:
        if(j>i/2) or (j==primes[-1]):
            primes.append(i)
            if((i-1)/2) in primes:
                sp.append(i)
                break
            else:
                usp.append(i)
                break
        if (i%j==0):
            break

print('First 35 safe primes are:\n' , sp[:35])
print('There are '+str(len(sp[:1000000]))+' safe primes below 1,000,000')
print('There are '+str(len(sp))+' safe primes below 10,000,000')
print('First 40 unsafe primes:\n',usp[:40])
print('There are '+str(len(usp[:1000000]))+' unsafe primes below 1,000,000')
print('There are '+str(len(usp))+' safe primes below 10,000,000')


sub comma { $^i.flip.comb(3).join(',').flip }

use Math::Primesieve;

my $sieve = Math::Primesieve.new;

my @primes = $sieve.primes(10_000_000);

my %filter = @primes.Set;

my $primes = @primes.classify: { %filter{($_ - 1)/2} ?? 'safe' !! 'unsafe' };

for 'safe', 35, 'unsafe', 40 -> $type, $quantity {
    say "The first $quantity $type primes are:";

    say $primes{$type}[^$quantity]».,

    say "The number of $type primes up to {comma $_}: ",
    comma $primes{$type}.first(* > $_, :k) // +$primes{$type} for 1e6, 1e7;

    say '';
}


<?php
  $code = 'echo "hello world"';
  eval($code);
  $code = 'return "hello world"';
  print eval($code);


program demo = compile_string(#"
    string name=\"demo\";
    string hello()
    {
       return(\"hello, i am \"+name);
    }");

demo()->hello();
Result: "hello, i am demo"


$test2plus2 = '2 + 2 -eq 4'
Invoke-Expression $test2plus2


10 $ "1 swap times [ i 1+ * ]" quackery echo


function Sieve ( [int] $num )
{
    $isprime = @{}
    2..$num | Where-Object {
        $isprime[$_] -eq $null } | ForEach-Object {
        $_
        $isprime[$_] = $true
        $i=$_*$_
        for ( ; $i -le $num; $i += $_ )
        { $isprime[$i] = $false }
    }
}


/*REXX program lists a sequence  (or a count)  of  ──safe──   or   ──unsafe──   primes. */
parse arg N kind _ . 1 . okind;     upper kind   /*obtain optional arguments from the CL*/
if N=='' | N==","  then N= 35                    /*Not specified?   Then assume default.*/
if kind=='' | kind==","  then kind= 'SAFE'       /* "      "          "     "      "    */
if _\==''                             then call ser 'too many arguments specified.'
if kind\=='SAFE'  &  kind\=='UNSAFE'  then call ser 'invalid 2nd argument: '   okind
if kind =='UNSAFE'  then safe= 0;  else safe= 1  /*SAFE  is a binary value for function.*/
w = linesize() - 1                               /*obtain the usable width of the term. */
tell= (N>0);    @.=;    N= abs(N)                /*N is negative?   Then don't display. */
!.=0;   !.1=2;  !.2=3;  !.3=5;  !.4=7;  !.5=11;  !.6=13;  !.7=17;  !.8=19;    #= 8
@.='';  @.2=1;  @.3=1;  @.5=1;  @.7=1;  @.11=1;  @.13=1;  @.17=1;  @.19=1;    start= # + 1
m= 0;                         lim=0              /*#  is the number of low primes so far*/
$=;     do i=1  for #   while lim<=N;  j= !.i    /* [↓]  find primes, and maybe show 'em*/
        call safeUnsafe;      $= strip($)        /*go see if other part of a KIND prime.*/
        end   /*i*/                              /* [↑]  allows faster loop (below).    */
                                                 /* [↓]  N:  default lists up to 35 #'s.*/
   do j=!.#+2  by 2  while  lim<N                /*continue on with the next odd prime. */
   if j // 3 == 0  then iterate                  /*is this integer a multiple of three? */
   parse var  j    ''  -1  _                     /*obtain the last decimal digit of  J  */
   if _      == 5  then iterate                  /*is this integer a multiple of five?  */
   if j // 7 == 0  then iterate                  /* "   "     "    "     "     " seven? */
   if j //11 == 0  then iterate                  /* "   "     "    "     "     " eleven?*/
   if j //13 == 0  then iterate                  /* "   "     "    "     "     "  13 ?  */
   if j //17 == 0  then iterate                  /* "   "     "    "     "     "  17 ?  */
   if j //19 == 0  then iterate                  /* "   "     "    "     "     "  19 ?  */
                                                 /* [↓]  divide by the primes.   ___    */
            do k=start  to #  while !.k * !.k<=j /*divide  J  by other primes ≤ √ J     */
            if j // !.k ==0   then iterate j     /*÷ by prev. prime?  ¬prime     ___    */
            end   /*k*/                          /* [↑]   only divide up to     √ J     */
   #= # + 1                                      /*bump the count of number of primes.  */
   !.#= j;                     @.j= 1            /*define a prime  and  its index value.*/
   call safeUnsafe                               /*go see if other part of a KIND prime.*/
   end   /*j*/
                                                 /* [↓]  display number of primes found.*/
if $\==''  then say $                            /*display any residual primes in $ list*/
say
if tell  then say commas(m)' '     kind    "primes found."
         else say commas(m)' '     kind    "primes found below or equal to "    commas(N).
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
add: m= m+1; lim= m; if \tell & j>N  then do; lim= j; m= m-1; end; else call app; return 1
app: if tell  then if length($ j)>w  then do;  say $; $ =j;   end; else $= $ j;   return 1
ser: say;  say;  say '***error***' arg(1);  say;  say;  exit 13   /*tell error message. */
commas: parse arg _;  do jc=length(_)-3  to 1  by -3; _=insert(',', _, jc); end;  return _
/*──────────────────────────────────────────────────────────────────────────────────────*/
safeUnsafe: ?= (j-1) % 2                         /*obtain the other part of KIND prime. */
            if safe  then if @.? == ''  then return 0             /*not a    safe prime.*/
                                        else return add()         /*is  "      "    "   */
                     else if @.? == ''  then return add()         /*is  an unsafe prime.*/
                                        else return 0             /*not  "   "      "   */


expr1 <- quote(a+b*c)
expr2 <- parse(text="a+b*c")[[1]]
expr3 <- call("+", quote(`a`), call("*", quote(`b`), quote(`c`)))


#lang racket
(require racket/sandbox)
(define e (make-evaluator 'racket))
(e '(define + *))
(e '(+ 10 20))
(+ 10 20)
;; (e '(delete-file "/etc/passwd"))
;; --> delete-file: `delete' access denied for /etc/passwd


use MONKEY-SEE-NO-EVAL;

my ($a, $b) = (-5, 7);
my $ans = EVAL 'abs($a * $b)';  # => 35


a: -5
b: 7
answer: do [abs a * b]     ; => 35


/*REXX program illustrates the ability to  execute code  entered  at runtime (from C.L.)*/
numeric digits 10000000                          /*ten million digits should do it.     */
bee=51
stuff= 'bee=min(-2,44);  say 13*2 "[from inside the box.]";  abc=abs(bee)'
interpret stuff
say 'bee='  bee
say 'abc='  abc
say
                                                 /* [↓]  now, we hear from the user.    */
say 'enter an expression:'
pull expression
say
say 'expression entered is:'  expression
say

interpret '?='expression

say 'length of result='length(?)
say ' left 50 bytes of result='left(?,50)"···"
say 'right 50 bytes of result=···'right(?, 50)   /*stick a fork in it,  we're all done. */


int i=2;
int maxx;
int maxy;
int max;
boolean[] sieve;

void setup() {
  size(1000, 1000);
  // frameRate(2);
  maxx=width;
  maxy=height;
  max=width*height;
  sieve=new boolean[max+1];

  sieve[1]=false;
  plot(0, false);
  plot(1, false);
  for (int i=2; i<=max; i++) {
    sieve[i]=true;
    plot(i, true);
  }
}

void draw() {
  if (!sieve[i]) {
    while (i*i<max && !sieve[i]) {
      i++;
    }
  }
  if (sieve[i]) {
    print(i+" ");
    for (int j=i*i; j<=max; j+=i) {
      if (sieve[j]) {
        sieve[j]=false;
        plot(j, false);
      }
    }
  }
  if (i*i<max) {
    i++;
  } else {
    noLoop();
    println("finished");
  }
}

void plot(int pos, boolean active) {
  set(pos%maxx, pos/maxx, active?#000000:#ffffff);
}


load "stdlib.ring"

see "working..." + nl

p = 1
num = 0
limit1 = 36
limit2 = 41
safe1 = 1000000
safe2 = 10000000

see "the first 35 Safeprimes are: " + nl
while true
      p = p + 1
      p2 = (p-1)/2
      if isprime(p) and isprime(p2)
         num = num + 1
         if num < limit1
            see " " + p
         else
            exit
         ok
      ok
end

see nl + "the first 40 Unsafeprimes are: " + nl
p = 1
num = 0
while true
      p = p + 1
      p2 = (p-1)/2
      if isprime(p) and not isprime(p2)
         num = num + 1
         if num < limit2
            see " " + p
         else
            exit
         ok
      ok
end

p = 1
num1 = 0
num2 = 0
while true
      p = p + 1
      p2 = (p-1)/2
      if isprime(p) and isprime(p2)
         if p < safe1
            num1 = num1 + 1
         ok
         if p < safe2
            num2 = num2 + 1
         else
            exit
         ok
      ok
end

see nl + "safe primes below 1,000,000: " + num1 + nl
see "safe primes below 10,000,000: " + num2 + nl

p = 1
num1 = 0
num2 = 0
while true
      p = p + 1
      p2 = (p-1)/2
      if isprime(p) and not isprime(p2)
         if p < safe1
            num1 = num1 + 1
         ok
         if p < safe2
            num2 = num2 + 1
         else
            exit
         ok
      ok
end

see "unsafe primes below 1,000,000: " + num1 + nl
see "unsafe primes below 10,000,000: " + num2 + nl

see "done..." + nl


require "prime"
class Integer
  def safe_prime? #assumes prime
    ((self-1)/2).prime?
  end
end

def format_parts(n)
  partitions = Prime.each(n).partition(&:safe_prime?).map(&:count)
  "There are %d safes and %d unsafes below #{n}."% partitions
end

puts "First 35 safe-primes:"
p Prime.each.lazy.select(&:safe_prime?).take(35).to_a
puts format_parts(1_000_000), "\n"

puts "First 40 unsafe-primes:"
p Prime.each.lazy.reject(&:safe_prime?).take(40).to_a
puts format_parts(10_000_000)


fn is_prime(n: i32) -> bool {
	for i in 2..n {
		if i * i > n {
			return true;
		}
		if n % i == 0 {
			return false;
		}
	}
	n > 1
}

fn is_safe_prime(n: i32) -> bool {
	is_prime(n) && is_prime((n - 1) / 2)
}

fn is_unsafe_prime(n: i32) -> bool {
	is_prime(n) && !is_prime((n - 1) / 2)
}

fn next_prime(n: i32) -> i32 {
	for i in (n+1).. {
		if is_prime(i) {
			return i;
		}
	}
	0
}

fn main() {
	let mut safe = 0;
	let mut unsf = 0;
	let mut p = 2;

	print!("first 35 safe primes: ");
	while safe < 35 {
		if is_safe_prime(p) {
			safe += 1;
			print!("{} ", p);
		}
		p = next_prime(p);
	}
	println!("");

	p = 2;

	print!("first 35 unsafe primes: ");
	while unsf < 35 {
		if is_unsafe_prime(p) {
			unsf += 1;
			print!("{} ", p);
		}
		p = next_prime(p);
	}
	println!("");

	p = 2;
	safe = 0;
	unsf = 0;

	while p < 1000000 {
		if is_safe_prime(p) {
			safe += 1;
		} else {
			unsf += 1;
		}
		p = next_prime(p);
	}
	println!("safe primes below 1,000,000: {}", safe);
	println!("unsafe primes below 1,000,000: {}", unsf);

	while p < 10000000 {
		if is_safe_prime(p) {
			safe += 1;
		} else {
			unsf += 1;
		}
		p = next_prime(p);
	}
	println!("safe primes below 10,000,000: {}", safe);
	println!("unsafe primes below 10,000,000: {}", unsf);
}


#!/usr/local/bin/shale

// Safe and unsafe primes.
//
// Safe prime p: (p - 1) / 2 is prime
// Unsafe prime: any prime that is not a safe prime

primes library

init dup var {
  pl sieve type primes::()
  10000000 0 pl generate primes::()
} =

isSafe dup var {
  1 - 2 / pl isprime primes::()
} =

comma dup var {
  n dup var swap =
  t dup var n 1000 / =
  b dup var n 1000 % =

  t 0 == {
    b print
  } {
    t.value comma() b ",%03d" printf
  } if
} =

go dup var {
  n var
  c1 var
  c10 var
  i var
  p var

  "The first 35 safe primes are:" print
  n 0 =
  c1 0 =
  c10 0 =
  i 0 =
  { i count pl:: < } {
    p i pl get primes::() =
    p isSafe() {
      n 35 < {
        p " %d" printf
        n++
        n 35 == { "" println } ifthen
      } ifthen

      p 1000000 < { c1++ } ifthen

      c10++
    } ifthen

    i++
  } while
  "Number of safe primes below  1,000,000 is " print c1.value comma() "" println
  "Number of safe primes below 10,000,000 is " print c10.value comma() "" println

  "The first 40 unsafe primes are:" print
  n 0 =
  c1 0 =
  c10 0 =
  i 0 =
  { i count pl:: < } {
    p i pl get primes::() =
    p isSafe() not {
      n 40 < {
        p " %d" printf
        n++
        n 40 == { "" println } ifthen
      } ifthen

      p 1000000 < { c1++ } ifthen

      c10++
    } ifthen

    i++
  } while
  "Number of unsafe primes below  1,000,000 is " print c1.value comma() "" println
  "Number of unsafe primes below 10,000,000 is " print c10.value comma() "" println
} =

init()
go()


func is_safeprime(p) {
    is_prime(p) && is_prime((p-1)/2)
}

func is_unsafeprime(p) {
    is_prime(p) && !is_prime((p-1)/2)
}

func safeprime_count(from, to) {
    from..to -> count_by(is_safeprime)
}

func unsafeprime_count(from, to) {
    from..to -> count_by(is_unsafeprime)
}

say "First 35 safe-primes:"
say (1..Inf -> lazy.grep(is_safeprime).first(35).join(' '))
say ''
say "First 40 unsafe-primes:"
say (1..Inf -> lazy.grep(is_unsafeprime).first(40).join(' '))
say ''
say "There are #{safeprime_count(1, 1e6)} safe-primes bellow 10^6"
say "There are #{unsafeprime_count(1, 1e6)} unsafe-primes bellow 10^6"
say ''
say "There are #{safeprime_count(1, 1e7)} safe-primes bellow 10^7"
say "There are #{unsafeprime_count(1, 1e7)} unsafe-primes bellow 10^7"


Eval("nOutput = 5+2*5 " )
See "5+2*5 = " + nOutput + nl
Eval("for x = 1 to 10 see x + nl next")
Eval("func test see 'message from test!' ")
test()


> (define x 37)
> (eval '(+ x 5))
42
> (eval '(+ x 5) (interaction-environment))
42
> (eval '(+ x 5) (scheme-report-environment 5)) ;; provides R5RS definitions

Error: identifier not visible x.
Type (debug) to enter the debugger.
> (display (eval (read)))
(+ 4 5) ;; this is input from the user.
9


`(4 + 5) evaluate.
`(4 + 5) evaluateIn: prototypes.


BEGIN

    CLASS BOOLARRAY(N); INTEGER N;
    BEGIN
        BOOLEAN ARRAY DATA(0:N-1);
    END BOOLARRAY;

    CLASS INTARRAY(N); INTEGER N;
    BEGIN
        INTEGER ARRAY DATA(0:N-1);
    END INTARRAY;

    REF(BOOLARRAY) PROCEDURE SIEVE(LIMIT);
        INTEGER LIMIT;
    BEGIN
        REF(BOOLARRAY) C;
        INTEGER P, P2;
        LIMIT := LIMIT+1;
        COMMENT TRUE DENOTES COMPOSITE, FALSE DENOTES PRIME. ;
        C :- NEW BOOLARRAY(LIMIT); COMMENT ALL FALSE BY DEFAULT ;
        C.DATA(0) := TRUE;
        C.DATA(1) := TRUE;
        COMMENT APART FROM 2 ALL EVEN NUMBERS ARE OF COURSE COMPOSITE ;
        FOR I := 4 STEP 2 UNTIL LIMIT-1 DO
            C.DATA(I) := TRUE;
        COMMENT START FROM 3. ;
        P := 3;
        WHILE TRUE DO BEGIN
            P2 := P * P;
            IF P2 >= LIMIT THEN BEGIN
                GO TO OUTER_BREAK;
            END;
            I := P2;
            WHILE I < LIMIT DO BEGIN
                C.DATA(I) := TRUE;
                I := I + 2 * P;
            END;
            WHILE TRUE DO BEGIN
                P := P + 2;
                IF NOT C.DATA(P) THEN BEGIN
                    GO TO INNER_BREAK;
                END;
            END;
            INNER_BREAK:
        END;
        OUTER_BREAK:
        SIEVE :- C;
    END SIEVE;

    COMMENT MAIN BLOCK ;

    REF(BOOLARRAY) SIEVED;
    REF(INTARRAY) UNSAFE, SAFE;
    INTEGER I, COUNT;

    COMMENT SIEVE UP TO 10 MILLION ;
    SIEVED :- SIEVE(10000000);

    SAFE :- NEW INTARRAY(35);
    COUNT := 0;
    I := 3;
    WHILE COUNT < 35 DO BEGIN
        IF NOT SIEVED.DATA(I) AND NOT SIEVED.DATA((I-1)//2) THEN BEGIN
            SAFE.DATA(COUNT) := I;
            COUNT := COUNT+1;
        END;
        I := I+2;
    END;
    OUTTEXT("THE FIRST 35 SAFE PRIMES ARE:");
    OUTIMAGE;
    OUTCHAR('[');
    FOR I := 0 STEP 1 UNTIL 35-1 DO BEGIN
        IF I>0 THEN OUTCHAR(' ');
        OUTINT(SAFE.DATA(I), 0);
    END;
    OUTCHAR(']');
    OUTIMAGE;
    OUTIMAGE;

    COUNT := 0;
    FOR I := 3 STEP 2 UNTIL 1000000 DO BEGIN
        IF NOT SIEVED.DATA(I) AND NOT SIEVED.DATA((I-1)//2) THEN BEGIN
            COUNT := COUNT+1;
        END;
    END;
    OUTTEXT("THE NUMBER OF SAFE PRIMES BELOW 1,000,000 IS ");
    OUTINT(COUNT, 0);
    OUTIMAGE;
    OUTIMAGE;

    FOR I := 1000001 STEP 2 UNTIL 10000000 DO BEGIN
        IF NOT SIEVED.DATA(I) AND NOT SIEVED.DATA((I-1)//2) THEN
            COUNT := COUNT+1;
    END;
    OUTTEXT("THE NUMBER OF SAFE PRIMES BELOW 10,000,000 IS ");
    OUTINT(COUNT, 0);
    OUTIMAGE;
    OUTIMAGE;

    UNSAFE :- NEW INTARRAY(40);
    UNSAFE.DATA(0) := 2; COMMENT SINCE (2 - 1)/2 IS NOT PRIME ;
    COUNT := 1;
    I := 3;
    WHILE COUNT < 40 DO BEGIN
        IF NOT SIEVED.DATA(I) AND SIEVED.DATA((I-1)//2) THEN BEGIN
            UNSAFE.DATA(COUNT) := I;
            COUNT := COUNT+1;
        END;
        I := I+2;
    END;
    OUTTEXT("THE FIRST 40 UNSAFE PRIMES ARE:");
    OUTIMAGE;
    OUTCHAR('[');
    FOR I := 0 STEP 1 UNTIL 40-1 DO BEGIN
        IF I>0 THEN OUTCHAR(' ');
        OUTINT(UNSAFE.DATA(I), 0);
    END;
    OUTCHAR(']');
    OUTIMAGE;
    OUTIMAGE;

    COUNT := 1;
    FOR I := 3 STEP 2 UNTIL 1000000 DO BEGIN
        IF NOT SIEVED.DATA(I) AND SIEVED.DATA((I-1)//2) THEN
            COUNT := COUNT+1;
    END;
    OUTTEXT("THE NUMBER OF UNSAFE PRIMES BELOW 1,000,000 IS ");
    OUTINT(COUNT, 0);
    OUTIMAGE;
    OUTIMAGE;

    FOR I := 1000001 STEP 2 UNTIL 10000000 DO BEGIN
        IF NOT SIEVED.DATA(I) AND SIEVED.DATA((I-1)//2) THEN
            COUNT := COUNT+1;
    END;
    OUTTEXT("THE NUMBER OF UNSAFE PRIMES BELOW 10,000,000 IS ");
    OUTINT(COUNT, 0);
    OUTIMAGE;

END


[
    | isSafePrime printFirstNElements |

    isSafePrime := [:p | ((p-1)//2) isPrime].
    printFirstNElements :=
        [:coll :n |
            (coll to:n)
                do:[:p | Transcript show:p]
                separatedBy:[Transcript space]
        ].
    (Iterator on:[:b | Integer primesUpTo:10000000 do:b])
        partition:isSafePrime
        into:[:savePrimes :unsavePrimes |
            |nSaveBelow1M nSaveBelow10M nUnsaveBelow1M nUnsaveBelow10M|

            nSaveBelow1M := savePrimes count:[:p | p < 1000000].
            nSaveBelow10M := savePrimes size.

            nUnsaveBelow1M := unsavePrimes count:[:p | p < 1000000].
            nUnsaveBelow10M := unsavePrimes size.

            Transcript showCR: 'first 35 safe primes:'.
            printFirstNElements value:savePrimes value:35.
            Transcript cr.

            Transcript show: 'safe primes below 1,000,000: '.
            Transcript showCR:nSaveBelow1M printStringWithThousandsSeparator.

            Transcript show: 'safe primes below 10,000,000: '.
            Transcript showCR:nSaveBelow10M printStringWithThousandsSeparator.

            Transcript showCR: 'first 40 unsafe primes:'.
            printFirstNElements value:unsavePrimes value:40.
            Transcript cr.

            Transcript show: 'unsafe primes below 1,000,000: '.
            Transcript showCR:nUnsaveBelow1M printStringWithThousandsSeparator.

            Transcript show: 'unsafe primes below 10,000,000: '.
            Transcript showCR:nUnsaveBelow10M printStringWithThousandsSeparator.
        ]
 ] benchmark:'runtime: safe primes'


import Foundation

class PrimeSieve {
    var composite: [Bool]

    init(size: Int) {
        composite = Array(repeating: false, count: size/2)
        var p = 3
        while p * p <= size {
            if !composite[p/2 - 1] {
                let inc = p * 2
                var q = p * p
                while q <= size {
                    composite[q/2 - 1] = true
                    q += inc
                }
            }
            p += 2
        }
    }

    func isPrime(number: Int) -> Bool {
        if number < 2 {
            return false
        }
        if (number & 1) == 0 {
            return number == 2
        }
        return !composite[number/2 - 1]
    }
}

func commatize(_ number: Int) -> String {
    let n = NSNumber(value: number)
    return NumberFormatter.localizedString(from: n, number: .decimal)
}

let limit1 = 1000000
let limit2 = 10000000

class PrimeInfo {
    let maxPrint: Int
    var count1: Int
    var count2: Int
    var primes: [Int]

    init(maxPrint: Int) {
        self.maxPrint = maxPrint
        count1 = 0
        count2 = 0
        primes = []
    }

    func addPrime(prime: Int) {
        count2 += 1
        if prime < limit1 {
            count1 += 1
        }
        if count2 <= maxPrint {
            primes.append(prime)
        }
    }

    func printInfo(name: String) {
        print("First \(maxPrint) \(name) primes: \(primes)")
        print("Number of \(name) primes below \(commatize(limit1)): \(commatize(count1))")
        print("Number of \(name) primes below \(commatize(limit2)): \(commatize(count2))")
    }
}

var safePrimes = PrimeInfo(maxPrint: 35)
var unsafePrimes = PrimeInfo(maxPrint: 40)

let sieve = PrimeSieve(size: limit2)

for prime in 2..<limit2 {
    if sieve.isPrime(number: prime) {
        if sieve.isPrime(number: (prime - 1)/2) {
            safePrimes.addPrime(prime: prime)
        } else {
            unsafePrimes.addPrime(prime: prime)
        }
    }
}

safePrimes.printInfo(name: "safe")
unsafePrimes.printInfo(name: "unsafe")


Imports System.Console

Namespace safety
    Module SafePrimes
        Dim pri_HS As HashSet(Of Integer) = Primes(10_000_000).ToHashSet()

        Sub Main()
            For Each UnSafe In {False, True} : Dim n As Integer = If(UnSafe, 40, 35)
                WriteLine($"The first {n} {If(UnSafe, "un", "")}safe primes are:")
                WriteLine(String.Join(" ", pri_HS.Where(Function(p) UnSafe Xor
                                                            pri_HS.Contains(p \ 2)).Take(n)))
            Next : Dim limit As Integer = 1_000_000 : Do
                Dim part = pri_HS.TakeWhile(Function(l) l < limit),
                 sc As Integer = part.Count(Function(p) pri_HS.Contains(p \ 2))
                WriteLine($"Of the primes below {limit:n0}: {sc:n0} are safe, and {part.Count() -
                          sc:n0} are unsafe.") : If limit = 1_000_000 Then limit *= 10 Else Exit Do
            Loop
        End Sub

        Private Iterator Function Primes(ByVal bound As Integer) As IEnumerable(Of Integer)
            If bound < 2 Then Return
            Yield 2
            Dim composite As BitArray = New BitArray((bound - 1) \ 2)
            Dim limit As Integer = (CInt((Math.Sqrt(bound))) - 1) \ 2
            For i As Integer = 0 To limit - 1 : If composite(i) Then Continue For
                Dim prime As Integer = 2 * i + 3 : Yield prime
                Dim j As Integer = (prime * prime - 2) \ 2
                While j < composite.Count : composite(j) = True : j += prime : End While
            Next
            For i As integer = limit To composite.Count - 1 : If Not composite(i) Then Yield 2 * i + 3
            Next
        End Function
    End Module
End Namespace


     expression = "' page ' (i + 1)"
     i = 7
     output = eval(expression)
end


set four 4
set result1 [eval "expr {$four + 5}"]           ;# string input

set result2 [eval [list expr [list $four + 5]]] ;# list input


#lang transd

MainModule : {
    str: "(textout \"eval output: \" (+ 1 1))",

    _start: (λ
        (eval str)
    )
}


For n=2 To Sqr(lim)
  If Nums(n)=0
    m=n*n
    While m<=lim
      Nums(m)=1
      m+n
    Wend
  EndIf
Next n


import "/math" for Int
import "/fmt" for Fmt

var c = Int.primeSieve(1e7, false) // need primes up to 10 million here
var safe = List.filled(35, 0)
var count = 0
var i = 3
while (count < 35) {
    if (!c[i] && !c[(i-1)/2]) {
        safe[count] = i
        count = count + 1
    }
    i = i + 2
}
System.print("The first 35 safe primes are:\n%(safe.join(" "))\n")

count = 35
while (i < 1e6) {
   if (!c[i] && !c[(i-1)/2]) count = count + 1
   i = i + 2
}
Fmt.print("The number of safe primes below 1,000,000 is $,d.\n", count)

while (i < 1e7) {
   if (!c[i] && !c[(i-1)/2]) count = count + 1
   i = i + 2
}
Fmt.print("The number of safe primes below 10,000,000 is $,d.\n", count)

var unsafe = List.filled(40, 0)
unsafe[0] = 2
count = 1
i = 3
while (count < 40) {
    if (!c[i] && c[(i-1)/2]) {
        unsafe[count] = i
        count = count + 1
    }
    i = i + 2
}
System.print("The first 40 unsafe primes are:\n%(unsafe.join(" "))\n")

count = 40
while (i < 1e6) {
   if (!c[i] && c[(i-1)/2]) count = count + 1
   i = i + 2
}
Fmt.print("The number of unsafe primes below 1,000,000 is $,d.\n", count)

while (i < 1e7) {
   if (!c[i] && c[(i-1)/2]) count = count + 1
   i = i + 2
}
Fmt.print("The number of unsafe primes below 10,000,000 is $,d.\n", count)


# writes hello world to the console
eval "out \"hello world\" endl console" console


Compiler.Compiler.compileText(
     "fcn f(text){text.len()}").f("foobar")
//-->6


def eratosthenes2(n):
    multiples = set()
    for i in range(2, n+1):
        if i not in multiples:
            yield i
            multiples.update(range(i*i, n+1, i))

print(list(eratosthenes2(100)))


proc NumOut(Num);       \Output positive integer with commas
int  Num, Dig, Cnt;
[Cnt:= [0];
Num:= Num/10;
Dig:= rem(0);
Cnt(0):= Cnt(0)+1;
if Num then NumOut(Num);
Cnt(0):= Cnt(0)-1;
ChOut(0, Dig+^0);
if rem(Cnt(0)/3)=0 & Cnt(0) then ChOut(0, ^,);
];

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;
];

int  N, SafeCnt, UnsafeCnt Unsafes(40);
[SafeCnt:= 0;  UnsafeCnt:= 0;
Text(0, "First 35 safe primes:^M^J");
for N:= 1 to 10_000_000-1 do
    [if IsPrime(N) then
        [if IsPrime( (N-1)/2 ) then
            [SafeCnt:= SafeCnt+1;
            if SafeCnt <= 35 then
                [NumOut(N);  ChOut(0, ^ )];
            ]
        else
            [Unsafes(UnsafeCnt):= N;
            UnsafeCnt:= UnsafeCnt+1;
            ];
        ];
    if N = 999_999 then
        [Text(0, "^M^JSafe primes below 1,000,000: ");
        NumOut(SafeCnt);
        Text(0, "^M^JUnsafe primes below 1,000,000: ");
        NumOut(UnsafeCnt);
        ];
    ];
Text(0, "^M^JFirst 40 unsafe primes:^M^J");
for N:= 0 to 40-1 do
    [NumOut(Unsafes(N));  ChOut(0, ^ )];
Text(0, "^M^JSafe primes below 10,000,000: ");
NumOut(SafeCnt);
Text(0, "^M^JUnsafe primes below 10,000,000: ");
NumOut(UnsafeCnt);
CrLf(0);
]


var [const] BI=Import("zklBigNum");  // libGMP
// saving 664,578 primes (vs generating them on the fly) seems a bit overkill

fcn safePrime(p){ ((p-1)/2).probablyPrime() } // p is a BigInt prime

fcn safetyList(sN,nsN){
   p,safe,notSafe := BI(2),List(),List();
   do{
      if(safePrime(p)) safe.append(p.toInt()) else notSafe.append(p.toInt());
      p.nextPrime();
   }while(safe.len()<sN or notSafe.len()<nsN);
   println("The first %d   safe primes are: %s".fmt(sN,safe[0,sN].concat(",")));
   println("The first %d unsafe primes are: %s".fmt(nsN,notSafe[0,nsN].concat(",")));
}(35,40);


  [ dup 1
    [ 2dup > while
      + 1 >>
      2dup / again ]
    drop nip ]                  is sqrt         ( n --> n )

  [ stack [ 3 ~ ] constant ]    is primes       (   --> s )

  ( If a number is prime, the corresponding bit on the
    number on the primes ancillary stack is set.
    Initially all the bits are set except for 0 and 1,
    which are not prime numbers by definition.            )

  [ bit ~
    primes take & primes put ]  is -composite   ( n -->   )

  [ bit primes share & 0 != ]   is isprime      ( n --> b )

  [ dup sqrt times
      [ i^ 1+
        dup isprime if
          [ dup 2 **
            [ dup -composite
              over +
              rot 2dup >
              dip unrot until ]
            drop ]
        drop ]
     drop ]                     is eratosthenes ( n -->   )

  100 eratosthenes

  100 times [ i^ isprime if [ i^ echo sp ] ]


sieve <- function(n) {
  if (n < 2) return(NULL)
  lmt <- sqrt(n)
  primes <- rep(TRUE, n)
  primes[1] <- FALSE
  for(i in seq(lmt)) {
    if (primes[i]) {
      primes[seq(i * i, n, by=i)] <- FALSE
    }
  }
  return(which(primes))
}

sieve(1000)


#lang racket

(define (sieve n)
  (define non-primes '())
  (define primes '())
  (for ([i (in-range 2 (add1 n))])
    (unless (member i non-primes)
      (set! primes (cons i primes))
      (for ([j (in-range (* i i) (add1 n) i)])
        (set! non-primes (cons j non-primes)))))
  (reverse primes))

(sieve 100)


sub sieve( Int $limit ) {
    my @is-prime = False, False, slip True xx $limit - 1;

    gather for @is-prime.kv -> $number, $is-prime {
        if $is-prime {
            take $number;
            loop (my $s = $number**2; $s <= $limit; $s += $number) {
                @is-prime[$s] = False;
            }
        }
    }
}

(sieve 100).join(",").say;


program prime
#
define(true,1)
define(false,0)
#
integer loop,loop2,limit,k,primes,count
integer isprime(1000)

limit = 1000
count = 0

for (loop=1; loop<=limit; loop=loop+1)
    {
       isprime(loop) = true
    }

isprime(1) = false

for (loop=2; loop<=limit; loop=loop+1)

    {
       if (isprime(loop) == true)
          {
              count = count + 1
              for (loop2=loop*loop; loop2 <= limit; loop2=loop2+loop)
                 {
                     isprime(loop2) = false
                 }
          }
    }
write(*,*)
write(*,101) count

101 format('There are ',I12,' primes.')

count = 0
for (loop=1; loop<=limit; loop=loop+1)
        if (isprime(loop) == true)
           {
               Count = count + 1
               write(*,'(I6,$)')loop
               if (mod(count,10) == 0) write(*,*)
           }
write(*,*)

end


primes: function [n [integer!]][
   poke prim: make bitset! n 1 true
   r: 2 while [r * r <= n][
      repeat q n / r - 1 [poke prim q + 1 * r true]
      until [not pick prim r: r + 1]
   ]
   collect [repeat i n [if not prim/:i [keep i]]]
]

primes 100
== [2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97]


/*REXX program generates and displays primes  via the  sieve of Eratosthenes  algorithm.*/
parse arg H .;   if H=='' | H==","  then H= 200  /*optain optional argument from the CL.*/
w= length(H);    @prime= right('prime', 20)      /*W:   is used for aligning the output.*/
@.=.                                             /*assume all the numbers are  prime.   */
#= 0                                             /*number of primes found  (so far).    */
     do j=2  for H-1;   if @.j==''  then iterate /*all prime integers up to H inclusive.*/
     #= # + 1                                    /*bump the prime number counter.       */
     say  @prime right(#,w)  " ───► " right(j,w) /*display the  prime  to the terminal. */
         do m=j*j  to H  by j;    @.m=;   end    /*strike all multiples as being ¬ prime*/
     end   /*j*/                                 /*       ───                           */
say                                              /*stick a fork in it,  we're all done. */
say  right(#, 1+w+length(@prime) )     'primes found up to and including '       H


limit = 100
sieve = list(limit)
for i = 2 to limit
    for k = i*i to limit step i
        sieve[k] = 1
    next
    if sieve[i] = 0 see "" + i + " " ok
next


def eratosthenes(n)
  nums = [nil, nil, *2..n]
  (2..Math.sqrt(n)).each do |i|
    (i**2..n).step(i){|m| nums[m] = nil}  if nums[i]
  end
  nums.compact
end

p eratosthenes(100)


input "Gimme the limit:"; limit
dim flags(limit)
for i = 2 to  limit
 for k = i*i to limit step i
  flags(k) = 1
 next k
if flags(i) = 0 then print i;", ";
next i


fn primes(n: usize) -> impl Iterator<Item = usize> {
    const START: usize = 2;
    if n < START {
        Vec::new()
    } else {
        let mut is_prime = vec![true; n + 1 - START];
        let limit = (n as f64).sqrt() as usize;
        for i in START..limit + 1 {
            let mut it = is_prime[i - START..].iter_mut().step_by(i);
            if let Some(true) = it.next() {
                it.for_each(|x| *x = false);
            }
        }
        is_prime
    }
    .into_iter()
    .enumerate()
    .filter_map(|(e, b)| if b { Some(e + START) } else { None })
}


comment
   Find primes up to the specified limit (here 1,000) using
   classic Sieve of Eratosthenes
end

$constant limit = 1000
$constant false = 0
$constant true = FFFFH

var i, k, count, col = integer
dim integer flags(limit)

print "Finding primes from 2 to";limit

rem - initialize table
for i = 1 to limit
  flags(i) = true
next i

rem - sieve for primes
for i = 2 to int(sqr(limit))
  if flags(i) = true then
     for k = (i*i) to limit step i
        flags(k) = false
     next k
next i

rem - write out primes 10 per line
count = 0
col = 1
for i = 2 to limit
   if flags(i) = true then
      begin
         print using "#####";i;
         count = count + 1
         col = col + 1
         if col > 10 then
            begin
               print
               col = 1
            end
      end
next i
print
print count; " primes were found."

end


proc iml;
start sieve(n);
    a = J(n,1);
    a[1] = 0;
    do i = 1 to n;
        if a[i] then do;
            if i*i>n then return(a);
            a[i*(i:int(n/i))] = 0;
        end;
    end;
finish;

a = loc(sieve(1000))`;
create primes from a;
append from a;
close primes;
quit;


show primes
WHERE
primes = sieve (2...)
sieve (p : x ) = p : sieve {a <- x; a REM p > 0}
?


import scala.annotation.tailrec
import scala.collection.parallel.mutable
import scala.compat.Platform

object GenuineEratosthenesSieve extends App {
  def sieveOfEratosthenes(limit: Int) = {
    val (primes: mutable.ParSet[Int], sqrtLimit) = (mutable.ParSet.empty ++ (2 to limit), math.sqrt(limit).toInt)
    @tailrec
    def prim(candidate: Int): Unit = {
      if (candidate <= sqrtLimit) {
        if (primes contains candidate) primes --= candidate * candidate to limit by candidate
        prim(candidate + 1)
      }
    }
    prim(2)
    primes
  }
  // BitSet toList is shuffled when using the ParSet version. So it has to be sorted before using it as a sequence.

  assert(sieveOfEratosthenes(15099480).size == 976729)
  println(s"Successfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}


; Tail-recursive solution :
(define (sieve n)
  (define (aux u v)
    (let ((p (car v)))
      (if (> (* p p) n)
        (let rev-append ((u u) (v v))
          (if (null? u) v (rev-append (cdr u) (cons (car u) v))))
        (aux (cons p u)
          (let wheel ((u '()) (v (cdr v)) (a (* p p)))
            (cond ((null? v) (reverse u))
                  ((= (car v) a) (wheel u (cdr v) (+ a p)))
                  ((> (car v) a) (wheel u v (+ a p)))
                  (else (wheel (cons (car v) u) (cdr v) a))))))))
  (aux '(2)
    (let range ((v '()) (k (if (odd? n) n (- n 1))))
      (if (< k 3) v (range (cons k v) (- k 2))))))

; > (sieve 100)
; (2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97)
; > (length (sieve 10000000))
; 664579


function a = sieve(n)
    a = ~zeros(n, 1)
    a(1) = %f
    for i = 1:n
        if a(i)
            j = i*i
            if j > n
                return
            end
            a(j:i:n) = %f
        end
    end
endfunction

find(sieve(100))
// [2 3 5 ... 97]

sum(sieve(1000))
// 168, the number of primes below 1000


when clicked
    broadcast: fill list with zero (0) and wait
    broadcast: put one (1) in list of multiples and wait
    broadcast: fill primes where zero (0 in list

when I receive: fill list with zero (0)
    delete all of primes
    delete all of list
    set i to 0
    set maximum to 25
    repeat maximum
        add 0 to list
        change i by 1
    {end repeat}

when I receive: put ones (1) in list of multiples
    set S to sqrt of maximum
    set i to 2
    set k to 0
    repeat S
        change J by 1
        set i to 2
        repeat until i > 100
            if not (i = J) then
                if item i of list = 0 then
                    set m to (i mod J)
                    if (m = 0) then
                        replace item i of list with 1
        {end repeat until}
        change i by 1
        set k to 1
        delete all of primes
    {end repeat}
    set J to 1

when I receive: fill primes where zeros (0) in list
    repeat maximum
        if (item k of list) = 0 then
            add k to primes
        set k to (k + 1)
    {end repeat}


$ include "seed7_05.s7i";

const func set of integer: eratosthenes (in integer: n) is func
  result
    var set of integer: sieve is EMPTY_SET;
  local
    var integer: i is 0;
    var integer: j is 0;
  begin
    sieve := {2 .. n};
    for i range 2 to sqrt(n) do
      if i in sieve then
        for j range i ** 2 to n step i do
          excl(sieve, j);
        end for;
      end if;
    end for;
  end func;

const proc: main is func
  begin
    writeln(card(eratosthenes(10000000)));
  end func;


func sieve(limit) {
    var sieve_arr = [false, false, (limit-1).of(true)...]
    gather {
        sieve_arr.each_kv { |number, is_prime|
            if (is_prime) {
                take(number)
                for i in (number**2 .. limit `by` number) {
                    sieve_arr[i] = false
                }
            }
        }
    }
}

say sieve(100).join(",")


BEGIN
    INTEGER ARRAY t(0:1000);
    INTEGER i,j,k;
    FOR i:=0 STEP 1 UNTIL 1000 DO t(i):=1;
    t(0):=0; t(1):=0;
    i:=0;
    FOR i:=i WHILE i<1000 DO
    BEGIN
        FOR i:=i WHILE i<1000 AND t(i)=0 DO i:=i+1;
        IF i<1000 THEN
        BEGIN
            j:=2;
            k:=j*i;
            FOR k:=k WHILE k<1000 DO
            BEGIN
                t(k):=0;
                j:=j+1;
                k:=j*i
            END;
            i:=i+1
        END
    END;
    FOR i:=0 STEP 1 UNTIL 999 DO
       IF t(i)<>0  THEN
       BEGIN
           OutInt(i,5); OutImage
       END
END


| potentialPrimes limit |
limit := 100.
potentialPrimes := Array new: limit.
potentialPrimes atAllPut: true.
2 to: limit sqrt do: [:testNumber |
    (potentialPrimes at: testNumber) ifTrue: [
        (testNumber * 2) to: limit by: testNumber do: [:nonPrime |
            potentialPrimes at: nonPrime put: false
        ]
    ]
].
2 to: limit do: [:testNumber |
    (potentialPrimes at: testNumber) ifTrue: [
        Transcript show: testNumber asString; cr
    ]
]


        define('sieve(n)i,j,k,p,str,res') :(sieve_end)
sieve   i = lt(i,n - 1) i + 1 :f(sv1)
        str = str (i + 1) ' ' :(sieve)
sv1     str break(' ') . j span(' ') = :f(return)
        sieve = sieve j ' '
        sieve = gt(j ^ 2,n) sieve str :s(return) ;* Opt1
        res = ''
        str (arb ' ') @p ((j ^ 2) ' ') ;* Opt2
        str len(p) . res = ;* Opt2
sv2     str break(' ') . k  span(' ') = :f(sv3)
        res = ne(remdr(k,j),0) res k ' ' :(sv2)
sv3     str = res :(sv1)
sieve_end

*       # Test and display
        output = sieve(100)
end


val segmentedSieve =  fn N =>
(* output : list of {segment=bit segment, start=number at startposition segment} *)

let

val NSegmt= 120000000;                                                                                (* segment size *)

val inf2i = IntInf.toInt ;
val i2inf = IntInf.fromInt ;
val isInt = fn m => m <= IntInf.fromInt (valOf Int.maxInt);

val sweep = fn (bits, step, k, up) =>                                                                   (* strike off bits up to limit *)
       (while (  !k < up  andalso 0 <= !k  ) do
             (  BitArray.clrBit( bits, !k ) ; k:= !k +  step ; ()) ) handle Overflow => ()

val rec nextPrimebit =                                                                                (* find next 1-bit within segment *)
     fn Bits =>
     fn pos  =>
        if pos+1 >= BitArray.length Bits
	  then    NONE
          else    ( if BitArray.sub ( Bits,pos) then SOME (i2inf pos) else nextPrimebit Bits (pos+1) );

val sieveEratosthenes =  fn n: int =>                                                             (* Eratosthenes sieve , up to+incl n *)

 let
  val nums= BitArray.bits(n,[] );
  val i=ref 2;
  val k=ref (!i * (!i) -1);

 in

  ( BitArray.complement nums;
    BitArray.clrBit( nums, 0 );
    while ( !k <n ) do (  if ( BitArray.sub (nums, !i - 1) ) then  sweep (nums, !i, k, n) else ();
      i:= !i+1;
      k:= !i * (!i) - 1
    );
    [ { start= i2inf 1, segment=nums } ]
  )

 end;

val sieveThroughSegment =

 fn ( primes : { segment:BitArray.array, start:IntInf.int } list, low : IntInf.int, up ) =>
                                                                                (* second segment and on *)
 let
  val n      = inf2i (up-low+1)
  val nums   = BitArray.bits(n,[] );
  val itdone = low div i2inf NSegmt

  val rec oldprimes = fn c =>  fn                                                                 (* use segment B to sweep current one *)
                 []                       => ()
      | ctlist as {start=st,segment=B}::t =>
       let

        val nxt  = nextPrimebit B c ;
        val p    = st +  Option.getOpt( nxt,~10)
        val modp = ( i2inf NSegmt * itdone ) mod p
        val i    = inf2i ( if( isInt( p - modp ) ) then p - modp else 0 )                               (* i = 0 breaks off *)
        val k    = ref   ( if Option.isSome nxt  then  (i - 1)  else ~2 )
        val step = if (isInt(p)) then inf2i(p) else valOf Int.maxInt                                    (* !k+maxInt > n *)

       in

          ( sweep (nums, step, k, n) ;
	    if ( p*p <= up  andalso  Option.isSome nxt )
	       then    oldprimes ( inf2i (p-st+1) ) ctlist
	       else    oldprimes 0 t                                                                    (* next segment B *)
          )

       end

 in
  (  BitArray.complement nums;
     oldprimes 0 primes;
     rev ( {start = low, segment = nums } :: rev (primes) )
  )
 end;

val rec workSegmentsDown = fn firstFn =>
    			   fn nextFns =>
			   fn sizeSeg : int =>
			   fn upLimit : IntInf.int =>
 let
   val residual = upLimit mod i2inf sizeSeg
 in

   if ( upLimit <= i2inf sizeSeg ) then firstFn (  inf2i upLimit )
   else
     if ( residual > 0 ) then
           nextFns ( workSegmentsDown firstFn nextFns sizeSeg (upLimit - residual ),     upLimit - residual      + 1, upLimit )
     else
           nextFns ( workSegmentsDown firstFn nextFns sizeSeg (upLimit - i2inf sizeSeg), upLimit - i2inf sizeSeg + 1, upLimit )
 end;

in

  workSegmentsDown  sieveEratosthenes  sieveThroughSegment  NSegmt  N

end;


prog def sieve
	args n
	clear
	qui set obs `n'
	gen long p=_n
	gen byte a=_n>1
	forv i=2/`n' {
		if a[`i'] {
			loc j=`i'*`i'
			if `j'>`n' {
				continue, break
			}
			forv k=`j'(`i')`n' {
				qui replace a=0 in `k'
			}
		}
	}
	qui keep if a
	drop a
end


import Foundation // for sqrt() and Date()

let max = 1_000_000
let maxroot = Int(sqrt(Double(max)))
let startingPoint = Date()

var isprime = [Bool](repeating: true, count: max+1 )
for i in 2...maxroot {
    if isprime[i] {
        for k in stride(from: max/i, through: i, by: -1) {
            if isprime[k] {
                isprime[i*k] = false }
        }
    }
}

var count = 0
for i in 2...max {
    if isprime[i] {
        count += 1
    }
}
print("\(count) primes found under \(max)")

print("\(startingPoint.timeIntervalSinceNow * -1) seconds")


templates sieve
  def limit: $;
  @: [ 2..$limit ];
  1 -> #
  [email protected] !

  when <[email protected]::length ?([email protected]($) * [email protected]($) <..$limit>)> do
    templates sift
      def prime: $;
      @: $prime * $prime;
      @sieve: [ [email protected] -> # ];
      when <[email protected]> do
        $ !
      when <[email protected]~..> do
        @: [email protected] + $prime;
        $ -> #
    end sift

    [email protected]($) -> sift !
    $ + 1 -> #
end sieve

1000 -> sieve ...->  '$; ' -> !OUT::write


package require Tcl 8.5

proc sieve n {
    if {$n < 2} {return {}}

    # create a container to hold the sequence of numbers.
    # use a dictionary for its speedy access (like an associative array)
    # and for its insertion order preservation (like a list)
    set nums [dict create]
    for {set i 2} {$i <= $n} {incr i} {
        # the actual value is never used
        dict set nums $i ""
    }

    set primes [list]
    while {[set nextPrime [lindex [dict keys $nums] 0]] <= sqrt($n)} {
        dict unset nums $nextPrime
        for {set i [expr {$nextPrime ** 2}]} {$i <= $n} {incr i $nextPrime} {
            dict unset nums $i
        }
        lappend primes $nextPrime
    }
    return [concat $primes [dict keys $nums]]
}

puts [sieve 100]   ;# 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97


Input "Limit:",N
N→Dim(L1)
For(I,2,N)
1→L1(I)
End
For(I,2,SQRT(N))
If L1(I)=1
Then
For(J,I*I,N,I)
0→L1(J)
End
End
End
For(I,2,N)
If L1(I)=1
Then
Disp i
End
End
ClrList L1


function primes {
  typeset -a a
  typeset i j
  a[1]=""
  for (( i = 2; i <= $1; i++ )); do
    a[$i]=$i
  done
  for (( i = 2; i * i <= $1; i++ )); do
    if [[ ! -z ${a[$i]} ]]; then
      for (( j = i * i; j <= $1; j += i )); do
        a[$j]=""
      done
    fi
  done
  printf '%s' "${a[2]}"
  printf ' %s' ${a[*]:3}
  printf '\n'
}

primes 1000


#import nat

sieve = ~<{0,1}&& iota; @NttPX ~&r->lx ^/~&rhPlC [email protected]~|@r


using Gee;

ArrayList<int> primes(int limit){
	var sieve = new ArrayList<bool>();
	var prime_list = new ArrayList<int>();

	for(int i = 0; i <= limit; i++){
		sieve.add(true);
	}

	sieve[0] = false;
	sieve[1] = false;

	for (int i = 2; i <= limit/2; i++){
		if (sieve[i] != false){
			for (int j = 2; i*j <= limit; j++){
				sieve[i*j] = false;
			}
		}
	}

	for (int i = 0; i < sieve.size; i++){
		if (sieve[i] != false){
			prime_list.add(i);
		}
	}

	return prime_list;
} // end primes

public static void main(){
	var prime_list = primes(50);

	foreach(var prime in prime_list)
		stdout.printf("%s ", prime.to_string());

	stdout.printf("\n");
}