                           000F4240  0000     1 n=1000*1000
                               0000  0000     2 .entry	main,0
                            7E 7CFD  0002     3 	clro	-(sp)			;result buffer
                            5E   DD  0005     4 	pushl	sp			;pointer to buffer
                            10   DD  0007     5 	pushl	#16			;descriptor -> len of buffer
                                     0009     6
                            02   DD  0009     7 	pushl	#2			;1st candidate
                                     000B     8 test:
                 09 46'AF   6E   E1  000B     9 	bbc	(sp), b^bits, found	;bc - bit clear
                                     0010    10 next:
           F3 6E   000F4240 8F   F2  0010    11         aoblss  #n, (sp), test		;+1: limit,index
                                 04  0018    12         ret
                                     0019    13 found:
                         04 AE   7F  0019    14 	pushaq	4(sp)			;-> descriptor by ref
                         04 AE   DF  001C    15 	pushal	4(sp)			;-> prime on stack by ref
              00000000'GF   02   FB  001F    16 	calls	#2, g^ots$cvt_l_ti	;convert integer to string
                         04 AE   7F  0026    17 	pushaq	4(sp)			;
              00000000'GF   01   FB  0029    18 	calls	#1, g^lib$put_output	;show result
                                     0030    19
                       53   6E   D0  0030    20 	movl	(sp), r3
                                     0033    21 mult:
    0002 53   6E   000F4240 8F   F1  0033    22 	acbl    #n, (sp), r3, set_mult	;limit,add,index
                            D1   11  003D    23 	brb	next
                                     003F    24 set_mult:				;set bits for multiples
                 EF 46'AF   53   E2  003F    25 	bbss	r3, b^bits, mult	;branch on bit set & set
                            ED   11  0044    26 	brb	mult
                                     0046    27
                           0001E892  0046    28 bits:	.blkl	<n+2+31>/32
                                     E892    29 .end	main


 Sub primes()
'BRRJPA
'Prime calculation for VBA_Excel
'p is the superior limit of the range calculation
'This example calculates from 2 to 100000 and print it
'at the collum A

p = 100000

Dim nprimes(1 To 100000) As Integer
b = Sqr(p)

For n = 2 To b

    For k = n * n To p Step n
        nprimes(k) = 1

    Next k
Next n

For a = 2 To p
    If nprimes(a) = 0 Then
      c = c + 1
      Range("A" & c).Value = a

    End If
 Next a

End Sub


    Dim sieve()
	If WScript.Arguments.Count>=1 Then
	    n = WScript.Arguments(0)
	Else
	    n = 99
	End If
    ReDim sieve(n)
    For i = 1 To n
        sieve(i) = True
    Next
    For i = 2 To n
        If sieve(i) Then
            For j = i * 2 To n Step i
                sieve(j) = False
            Next
        End If
    Next
    For i = 2 To n
        If sieve(i) Then WScript.Echo i
    Next


#10 = Get_Num("Enter number to search to: ", STATLINE)
Buf_Switch(Buf_Free)                    // Use edit buffer as flags array
Ins_Text("--")                          // 0 and 1 are not primes
Ins_Char('P', COUNT, #10-1)             // init rest of the flags to "prime"
for (#1 = 2; #1*#1 < #10; #1++) {
    Goto_Pos(#1)
    if (Cur_Char=='P') {                // this is a prime number
        for (#2 = #1*#1; #2 <= #10; #2 += #1) {
            Goto_Pos(#2)
            Ins_Char('-', OVERWRITE)
        }
    }
}


Sub Eratost()
    Dim sieve() As Boolean
    Dim n As Integer, i As Integer, j As Integer
    n = InputBox("limit:", n)
    ReDim sieve(n)
    For i = 1 To n
        sieve(i) = True
    Next i
    For i = 2 To n
        If sieve(i) Then
            For j = i * 2 To n Step i
                sieve(j) = False
            Next j
        End If
    Next i
    For i = 2 To n
        If sieve(i) Then Debug.Print i
    Next i
End Sub 'Eratost


Dim n As Integer, k As Integer, limit As Integer
Console.WriteLine("Enter number to search to: ")
limit = Console.ReadLine
Dim flags(limit) As Integer
For n = 2 To Math.Sqrt(limit)
    If flags(n) = 0 Then
        For k = n * n To limit Step n
            flags(k) = 1
        Next k
    End If
Next n

' Display the primes
For n = 2 To limit
    If flags(n) = 0 Then
        Console.WriteLine(n)
    End If
Next n


fn main() {
    limit := 201 // means sieve numbers < 201

    // sieve
    mut c := []bool{len: limit} // c for composite.  false means prime candidate
    c[1] = true              // 1 not considered prime
    mut p := 2
    for {
        // first allowed optimization:  outer loop only goes to sqrt(limit)
        p2 := p * p
        if p2 >= limit {
            break
        }
        // second allowed optimization:  inner loop starts at sqr(p)
        for i := p2; i < limit; i += p {
            c[i] = true // it's a composite
        }
        // scan to get next prime for outer loop
        for {
            p++
            if !c[p] {
                break
            }
        }
    }

    // sieve complete.  now print a representation.
    for n in 1..limit {
        if c[n] {
            print("  .")
        } else {
            print("${n:3}")
        }
        if n%20 == 0 {
            println("")
        }
    }
}


self.print_primes = method(m){
   p = new()
   p.fill(0, m, 1, true)

   count = 0
   i = 2
   while(i < m){
      if(p[i] == true){
         p.fill(i+i, m, i, false)
         count = count + 1
      }
      i = i + 1
   }
   ('primes: ' + count + ' in ' + m).print()
   for(i = 2, i < m, i = i + 1){
      if(p[i] == true){
         ('' + i + ', ').put()
      }
   }
   ''.print()
}

self.print_primes(100)


(module
 (import "js" "print" (func $print (param i32)))
 (memory 4096)

 (func $sieve (export "sieve") (param $n i32)
   (local $i i32)
   (local $j i32)

   (set_local $i (i32.const 0))
   (block $endLoop
     (loop $loop
       (br_if $endLoop (i32.ge_s (get_local $i) (get_local $n)))
       (i32.store8 (get_local $i) (i32.const 1))
       (set_local $i (i32.add (get_local $i) (i32.const 1)))
       (br $loop)))

   (set_local $i (i32.const 2))
   (block $endLoop
     (loop $loop
       (br_if $endLoop (i32.ge_s (i32.mul (get_local $i) (get_local $i))
                                 (get_local $n)))
       (if (i32.eq (i32.load8_s (get_local $i)) (i32.const 1))
         (then
           (set_local $j (i32.mul (get_local $i) (get_local $i)))
           (block $endInnerLoop
             (loop $innerLoop
               (i32.store8 (get_local $j) (i32.const 0))
               (set_local $j (i32.add (get_local $j) (get_local $i)))
               (br_if $endInnerLoop (i32.ge_s (get_local $j) (get_local $n)))
               (br $innerLoop)))))
       (set_local $i (i32.add (get_local $i) (i32.const 1)))
       (br $loop)))

   (set_local $i (i32.const 2))
   (block $endLoop
     (loop $loop
       (if (i32.eq (i32.load8_s (get_local $i)) (i32.const 1))
         (then
           (call $print (get_local $i))))
       (set_local $i (i32.add (get_local $i) (i32.const 1)))
       (br_if $endLoop (i32.ge_s (get_local $i) (get_local $n)))
       (br $loop)))))


Dim limit, prime, i As Integer
Dim s As String
Dim t As Double
Dim sieve(100000000) As Boolean

REM Get the maximum number
While limit<1 Or limit > 100000000
  Print("Max number? [1 to 100000000]")
  s = Input
  limit = CDbl(s)
Wend

REM Do the calculations
t = Microseconds
prime = 2
While prime^2 < limit
  For i = prime*2 To limit Step prime
    sieve(i) = True
  Next
  Do
    prime = prime+1
  Loop Until Not sieve(prime)
Wend
t = Microseconds-t
Print("Compute time = "+Str(t/1000000)+" sec")
Print("Press Enter...")
s = Input

REM Display the prime numbers
For i = 1 To limit
  If Not sieve(i) Then Print(Str(i))
Next
s = Input


(sieve(n = /0 -> int; limit = /0 -> int; is_prime = [/0] -> *)) *
    i<@>range(n*n, limit+1, n)
        is_prime = is_prime[$]i,False
    <*>is_prime

(primes_upto(limit = 4 -> int)) list(int)
    primes = [] -> list
    f = [False, False] -> list(bool)
    t = [True] -> list(bool)
    u = limit - 1 -> int
    tt = t * u -> list(bool)
    is_prime = flatten(f[^]tt) -> list(bool)
    limit_sqrt = limit ** 0.5 -> float
    iter1 = int(limit_sqrt + 1.5) -> int

    n<@>range(iter1)
        is_prime[n]<?>is_prime = sieve(n, limit, is_prime)

    i,prime<@>enumerate(is_prime)
        prime<?>primes = primes[^]i
    <*>primes


var sieveOfE = Fn.new { |n|
    if (n < 2) return []
    var comp = List.filled(n-1, false)
    var p = 2
    while (true) {
        var p2 = p * p
        if (p2 > n) break
        var i = p2
        while (i <= n) {
            comp[i-2] = true
            i = i + p
        }
        while (true) {
            p = p + 1
            if (!comp[p-2]) break
        }
    }
    var primes = []
    for (i in 0..n-2) {
        if (!comp[i]) primes.add(i+2)
    }
    return primes
}

System.print(sieveOfE.call(100))


include c:\cxpl\codes;                  \intrinsic 'code' declarations
int  Size, Prime, I, Kill;
char Flag;
[Size:= IntIn(0);
Flag:= Reserve(Size+1);
for I:= 2 to Size do Flag(I):= true;
for I:= 2 to Size do
    if Flag(I) then                     \found a prime
        [Prime:= I;
        IntOut(0, Prime);  CrLf(0);
        Kill:= Prime + Prime;           \first multiple to kill
        while Kill <= Size do
                [Flag(Kill):= false;    \zero a non-prime
                Kill:= Kill + Prime;    \next multiple
                ];
        ];
]


#!/usr/bin/yabasic

// ---------------------------
// Prime Sieve Benchmark --
// "Shootout" Version    --
// ---------------------------
// usage:
//     yabasic sieve8k.yab 90000

SIZE = 8192
ONN = 1 : OFF = 0
dim flags(SIZE)

sub main()

    cmd = peek("arguments")
    if cmd = 1 then
       iterations = val(peek$("argument"))
       if iterations = 0 then print "Argument wrong. Done 1000." : iterations = 1000 end if
    else
       print "1000 iterations."
       iterations = 1000
    end if

    for iter = 1 to iterations
        count = 0
        for n= 1 to SIZE : flags(n) = ONN: next n
        for i = 2 to SIZE
            if flags(i) = ONN then
               let k = i + i
               if k < SIZE then
                 for k = k to SIZE step i
                    flags(k) = OFF
                 next k
               end if
               count = count + 1
            end if
        next i
    next iter
    print "Count: ", count  // 1028
end sub

clear screen

print "Prime Sieve Benchmark\n"

main()

t = val(mid$(time$,10))

print "time: ", t, "\n"
print peek("millisrunning")


const std = @import("std");
const stdout = std.io.getStdOut().outStream();

pub fn main() !void {
    try sieve(1000);
}

// using a comptime limit ensures that there's no need for dynamic memory.
fn sieve(comptime limit: usize) !void {
    var prime = [_]bool{true} ** limit;
    prime[0] = false;
    prime[1] = false;
    var i: usize = 2;
    while (i*i < limit) : (i += 1) {
        if (prime[i]) {
            var j = i*i;
            while (j < limit) : (j += i)
                prime[j] = false;
        }
    }
    var c: i32 = 0;
    for (prime) |yes, p|
        if (yes) {
            c += 1;
            try stdout.print("{:5}", .{p});
            if (@rem(c, 10) == 0)
                try stdout.print("\n", .{});
        };
    try stdout.print("\n", .{});
}


fcn sieve(limit){
   composite:=Data(limit+1).fill(1);  // bucket of bytes set to 1 (prime)
   (2).pump(limit.toFloat().sqrt()+1, Void,  // Void==no results, just loop
       composite.get, Void.Filter,	// if prime, zero multiples
      'wrap(n){ [n*n..limit,n].pump(Void,composite.set.fp1(0)) }); //composite[n*p]=0
   (2).filter(limit-1,composite.get); // bytes still 1 are prime
}
sieve(53).println();


PROC eval_with_x = (STRING code, INT a, b)STRING:
	(INT x=a; evaluate(code) ) + (INT x=b; evaluate(code));
print((eval_with_x("2 ** x", 3, 5), new line))


on task_with_x(pgrm, x1, x2)
	local rslt1, rslt2
	set rslt1 to run script pgrm with parameters {x1}
	set rslt2 to run script pgrm with parameters {x2}
	rslt2 - rslt1
end task_with_x


msgbox % first := evalWithX("x + 4", 5)
msgbox % second := evalWithX("x + 4", 6)
msgbox % second - first
return

evalWithX(expression, xvalue)
{
global script
script =
(
    expression(){
    x = %xvalue%  ; := would need quotes
    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")
}


      expression$ = "x^2 - 7"
      one = FN_eval_with_x(expression$, 1.2)
      two = FN_eval_with_x(expression$, 3.4)
      PRINT two - one
      END

      DEF FN_eval_with_x(expr$, x)
      = EVAL(expr$)


( ( eval-with-x
  =   code a b argument
    .   !arg:((=?code),?a,?b,?argument)
      &   (!b:?x&!code$!argument)
        + -1*(!a:?x&!code$!argument)
  )
& out$(eval-with-x$((='(.$x^!arg)),3,5,2))
& out$(eval-with-x$((='(.$x^!arg)),12,13,2))
);


(def ^:dynamic x nil)

(defn eval-with-x [program a b]
  (- (binding [x b] (eval program))
     (binding [x a] (eval program))))


(defun eval-with-x (program a b)
  (let ((at-a (eval `(let ((x ',a)) ,program)))
        (at-b (eval `(let ((x ',b)) ,program))))
    (- at-b at-a)))


local fib n:
	if <= n 1:
		n
	else:
		+ fib - n 1 fib - n 2

local :code !compile-string dup "-- fib x" #one less than the xth fibonacci number

!run-blob-in { :fib @fib :x 4 } code
!run-blob-in { :fib @fib :x 6 } code
!. -


# Constructing an environment has to be done by way of evaluation
#for historical reasons which will hopefully be entirely eliminated soon.
def bindX(value) {
  def [resolver, env] := e`    # bind x and capture its resolver and the
    def x                      # resulting environment
  `.evalToPair(safeScope)
  resolver.resolve(value)      # set the value
  return env
}

def evalWithX(program, a, b) {
  def atA := program.eval(bindX(a))
  def atB := program.eval(bindX(b))
  return atB - atA
}


(define (eval-with-x prog x)
    (eval prog (environment-new (list (list 'x x)))))

(define prog '( + 1 (* x x)))

(eval-with-x prog 10) → 101
(eval-with-x prog 1000) → 1000001
(- (eval-with-x prog 1000) (eval-with-x prog 10)) → 999900

;; check x is unbound (no global)
x
😖 error: #|user| : unbound variable : x


import extensions;
import extensions'scripting;

public program()
{
    var text := program_arguments[1];
    var arg := program_arguments[2];

    var program := lscript.interpret(text);
    console.printLine(
        text,",",arg," = ",program.eval(arg.toReal()));
}


-module( runtime_evaluation ).

-export( [evaluate_form/2, form_from_string/1, task/0] ).

evaluate_form( Form, {Variable_name, Value} ) ->
	Bindings = erl_eval:add_binding( Variable_name, Value, erl_eval:new_bindings() ),
	{value, Evaluation, _} = erl_eval:expr( Form, Bindings ),
	Evaluation.

form_from_string( String ) ->
	{ok, Tokens, _} = erl_scan:string( String ),
	{ok, [Form]} = erl_parse:parse_exprs( Tokens ),
	Form.

task() ->
	Form = form_from_string( "X." ),
	Variable1 = evaluate_form( Form, {'X', 1} ),
	io:fwrite( "~p~n", [Variable1] ),
	Variable2 = evaluate_form( Form, {'X', 2} ),
	io:fwrite( "~p~n", [Variable2] ),
	io:fwrite( "~p~n", [Variable2 - Variable1] ).


USE: eval
: [email protected] ( a b program -- n )
    tuck [ ( y -- z ) eval ] [email protected] - ;


: f-" ( a b snippet" -- )
  [char] " parse   ( code len )
  2dup 2>r evaluate
  swap 2r> evaluate
  - . ;

2 3 f-" dup *"   \ 5  (3*3 - 2*2)


defmacro add100() (+ x 100)

var x 23
var firstresult (add100)
x = 1000
print
    + firstresult (add100)


package main

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

func main() {
    // an expression on x
    squareExpr := "x*x"

    // parse to abstract syntax tree
    fset := token.NewFileSet()
    squareAst, err := parser.ParseExpr(squareExpr)
    if err != nil {
        fmt.Println(err)
        return
    }
    // create an environment or "world"
    w := eval.NewWorld()

    // allocate a variable
    wVar := new(intV)

    // bind the variable to the name x
    err = w.DefineVar("x", eval.IntType, wVar)
    if err != nil {
        fmt.Println(err)
        return
    }
    // bind the expression AST to the world
    squareCode, err := w.CompileExpr(fset, squareAst)
    if err != nil {
        fmt.Println(err)
        return
    }
    // directly manipulate value of variable within world
    *wVar = 5
    // evaluate
    r0, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    // change value
    *wVar--
    // revaluate
    r1, err := squareCode.Run()
    if err != nil {
        fmt.Println(err)
        return
    }
    // print difference
    fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil))
}

// int value implementation.
type intV int64

func (v *intV) String() string              { return fmt.Sprint(*v) }
func (v *intV) Get(*eval.Thread) int64      { return int64(*v) }
func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) }
func (v *intV) Assign(t *eval.Thread, o eval.Value) {
    *v = intV(o.(eval.IntValue).Get(t))
}


def cruncher = { x1, x2, program ->
   Eval.x(x1, program) - Eval.x(x2, program)
}


import java.io.File;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.Arrays;
import javax.tools.JavaCompiler;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;

public class Eval {
    private static final String CLASS_NAME = "TempPleaseDeleteMe";

    private static class StringCompiler
            extends SimpleJavaFileObject {
        final String m_sourceCode;

        private StringCompiler( final String sourceCode ) {
            super( URI.create( "string:///" + CLASS_NAME + Kind.SOURCE.extension ), Kind.SOURCE );
            m_sourceCode = sourceCode;
        }

        @Override
        public CharSequence getCharContent( final boolean ignoreEncodingErrors ) {
            return m_sourceCode;
        }

        private boolean compile() {
            final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();

            return javac.getTask( null, javac.getStandardFileManager( null, null, null ),
                null, null, null, Arrays.asList( this )
            ).call();
        }

        private double callEval( final double x )
                throws Exception {
            final Class<?> clarse = Class.forName( CLASS_NAME );
            final Method   eval   = clarse.getMethod( "eval", double.class );

            return ( Double ) eval.invoke( null, x );
        }
    }

    public static double evalWithX( final String code, final double x )
            throws Exception {
        final StringCompiler sc = new StringCompiler(
            "class "
                + CLASS_NAME
                + "{public static double eval(double x){return ("
                + code
                + ");}}"
            );

        if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" );
        return sc.callEval( x );
    }

    public static void main( final String [] args )
            throws Exception /* lazy programmer */ {
        final String expression = args [ 0 ];
        final double x1         = Double.parseDouble( args [ 1 ] );
        final double x2         = Double.parseDouble( args [ 2 ] );

        System.out.println(
            evalWithX( expression, x1 )
            - evalWithX( expression, x2 )
        );
    }
}


function evalWithX(expr, a, b) {
    var x = a;
    var atA = eval(expr);
    x = b;
    var atB = eval(expr);
    return atB - atA;
}


/* Runtime evaluation in an environment, in Jsish */
function evalWithX(expr, a, b) {
    var x = a;
    var atA = eval(expr);
    x = b;
    var atB = eval(expr);
    return atB - atA;
}

;evalWithX('Math.exp(x)', 0, 1);
;evalWithX('Math.exp(x)', 1, 0);

/*
=!EXPECTSTART!=
evalWithX('Math.exp(x)', 0, 1) ==> 1.71828182845905
evalWithX('Math.exp(x)', 1, 0) ==> -1.71828182845905
=!EXPECTEND!=
*/


macro evalwithx(expr, a, b)
    return quote
        x = $a
        tmp = $expr
        x = $b
        return $expr - tmp
    end
end

@evalwithx(2 ^ x, 3, 5)     # raw expression (AST)


// Kotlin JS version 1.1.4-3

fun evalWithX(expr: String, a: Double, b: Double) {
    var x = a
    val atA = eval(expr)
    x = b
    val atB = eval(expr)
    return atB - atA
}

fun main(args: Array<String>) {
    println(evalWithX("Math.exp(x)", 0.0, 1.0))
}


 expression$ = "x^2 - 7"
Print (EvaluateWithX(expression$, 5) - EvaluateWithX(expression$, 3))
End

Function EvaluateWithX(expression$, x)
    EvaluateWithX = Eval(expression$)
End Function


code = loadstring"return x^2" --this doesn't really need to be input, does it?
val1 = setfenv(code, {x = io.read() + 0})()
val2 = setfenv(code, {x = io.read() + 0})()
print(val2 - val1)


Input source code is "10 x" , X is locally bound to 3 & 2 and the resulting expressions evaluated.
(10 x /. x -> 3 ) - (10 x /. x -> 2 )
-> 10


function r = calcit(f, val1, val2)
  x = val1;
  a = eval(f);
  x = val2;
  b = eval(f);
  r = b-a;
end


vardef evalit(expr s, va, vb) =
save x,a,b; x := va; a := scantokens s;
x := vb; b := scantokens s; a-b
enddef;

show(evalit("2x+1", 5, 3));
end


import macros, strformat

macro eval(s, x: static[string]): untyped =
  parseStmt(&"let x={x}\n{s}")

echo(eval("x+1", "3.1"))


say evalWithX("x**2", 2)
say evalWithX("x**2", 3.1415926)

::routine evalWithX
  use arg expression, x

  -- X now has the value of the second argument
  interpret "return" expression


declare
   fun {EvalWithX Program A B}
      {Compiler.evalExpression Program env('X':B) _}
      -
      {Compiler.evalExpression Program env('X':A) _}
   end
in
   {Show {EvalWithX "{Exp X}" 0.0 1.0}}


sub eval_with_x
   {my $code = shift;
    my $x = shift;
    my $first = eval $code;
    $x = shift;
    return eval($code) - $first;}

print eval_with_x('3 * $x', 5, 10), "\n"; # Prints "15".


without javascript_semantics
requires("1.0.1")
include eval.e

function eval_with_x(string expr, integer a, b)
    return eval(expr,{"x"},{{"x",b}})[1] -
           eval(expr,{"x"},{{"x",a}})[1]
end function

?eval_with_x("integer x = power(2,x)",3,5)


<?php
function eval_with_x($code, $a, $b) {
    $x = $a;
    $first = eval($code);
    $x = $b;
    $second = eval($code);
    return $second - $first;
}

echo eval_with_x('return 3 * $x;', 5, 10), "\n"; # Prints "15".
?>


(let Expression '(+ X (* X X))            # Local expression
   (println
      (+
         (let X 3
            (eval Expression) )
         (let X 4
            (eval Expression) ) ) )
   (let Function (list '(X) Expression)   # Build a local function
      (println
         (+
            (Function 3)
            (Function 4) ) ) ) )


> int x=10;
Result: 10
> x * 5;
Result: 50
> dump wrapper
Last compiled wrapper:
001: mapping(string:mixed) ___hilfe = ___Hilfe->variables;
002: # 1
003: mixed ___HilfeWrapper() { return (([mapping(string:int)](mixed)___hilfe)->x) * 5; ; }
004:
>


>>> def eval_with_x(code, a, b):
	return eval(code, {'x':b}) - eval(code, {'x':a})

>>> eval_with_x('2 ** x', 3, 5)
24


evalWithAB <- function(expr, var, a, b) {
  env <- new.env()           # provide a separate env, so that the choosen
  assign(var, a, envir=env)  # var name do not collide with symbols inside
                             # this function (e.g. it could be even "env")
  atA <- eval(parse(text=expr), env)
                             # and then evaluate the expression inside this
                             # ad hoc env-ironment
  assign(var, b, envir=env)
  atB <- eval(parse(text=expr), env)
  return(atB - atA)
}

print(evalWithAB("2*x+1", "x", 5, 3))
print(evalWithAB("2*y+1", "y", 5, 3))
print(evalWithAB("2*y+1", "x", 5, 3)) # error: object "y" not found


#lang racket
(define ns (make-base-namespace))
(define (eval-with-x code a b)
  (define (with v) (eval `(let ([x ',v]) ,code) ns))
  (- (with b) (with a)))


use MONKEY-SEE-NO-EVAL;
sub eval_with_x($code, *@x) { [R-] @x.map: -> \x { EVAL $code } }

say eval_with_x('3 * x', 5, 10);      # Says "15".
say eval_with_x('3 * x', 5, 10, 50);  # Says "105".


prog: [x * 2]
fn: func [x] [do bind prog 'x]
a: fn 2
b: fn 4
subtract b a


/*REXX program demonstrates a run─time evaluation of an expression (entered at run─time)*/
say '──────── enter the 1st expression to be evaluated:'

parse pull x                                     /*obtain an expression from the console*/
y.1= x                                           /*save the provided expression for  X. */
say

say '──────── enter the 2nd expression to be evaluated:'

parse pull x                                     /*obtain an expression from the console*/
y.2= x                                           /*save the provided expression for  X. */

say
say '────────  1st expression entered is: '  y.1
say '────────  2nd expression entered is: '  y.2
say

interpret 'say "──────── value of the difference is: "' y.2  "-"  '('y.1")"  /* ◄─────┐ */
                                                                             /*       │ */
                                                                             /*       │ */
                                                 /*subtract 1st exp. from the 2nd──►──┘ */

drop x                                           /*X var. is no longer a global variable*/
exit 0                                           /*stick a fork in it,  we're all done. */


expression = "return pow(x,2) - 7"
one = evalwithx(expression, 1.2)
two = evalwithx(expression, 3.4)
see "one = " + one + nl + "two = " + two + nl

func evalwithx expr, x
     return eval(expr)


def bind_x_to_value(x)
  binding
end

def eval_with_x(code, a, b)
  eval(code, bind_x_to_value(b)) - eval(code, bind_x_to_value(a))
end

puts eval_with_x('2 ** x', 3, 5) # Prints "24"


object Eval extends App {

  def evalWithX(expr: String, a: Double, b: Double)=
    {val x = b; eval(expr)} - {val x = a; eval(expr)}

  println(evalWithX("Math.exp(x)", 0.0, 1.0))

}


(define (eval-with-x prog a b)
  (let ((at-a (eval `(let ((x ',a)) ,prog)))
        (at-b (eval `(let ((x ',b)) ,prog))))
    (- at-b at-a)))


func eval_with_x(code, x, y) {
    var f = eval(code);
    x = y;
    eval(code) - f;
}

say eval_with_x(x: 3, y: 5, code: '2 ** x');   # => 24


BEGIN

    CLASS ENV;
    BEGIN

        CLASS ITEM(N, X); TEXT N; REAL X;
        BEGIN
            REF(ITEM) NEXT; NEXT :- HEAD; HEAD :- THIS ITEM;
        END ITEM;

        REF(ITEM) HEAD;

        REF(ITEM) PROCEDURE LOOKUP(V); TEXT V;
        BEGIN
            REF(ITEM) I; BOOLEAN FOUND; I :- HEAD;
            WHILE NOT FOUND DO
                IF I == NONE OR ELSE I.N = V
                THEN FOUND := TRUE
                ELSE I :- I.NEXT;
            LOOKUP :- I;
        END LOOKUP;

        REF(ENV) PROCEDURE SET(V, X); TEXT V; REAL X;
        BEGIN
            REF(ITEM) I; I :- LOOKUP(V);
            IF I == NONE THEN I :- NEW ITEM(V, X) ELSE I.X := X;
            SET :- THIS ENV;
        END SET;

        REAL PROCEDURE GET(V); TEXT V;
            GET := LOOKUP(V).X;

    END ENV;

    CLASS EXPR(EV); REF(ENV) EV;
    BEGIN

        REAL PROCEDURE POP;
        BEGIN
            IF STACKPOS > 0 THEN
            BEGIN STACKPOS := STACKPOS - 1; POP := STACK(STACKPOS); END;
        END POP;

        PROCEDURE PUSH(NEWTOP); REAL NEWTOP;
        BEGIN
            STACK(STACKPOS) := NEWTOP;
            STACKPOS := STACKPOS + 1;
        END PUSH;

        REAL PROCEDURE CALC(OPERATOR, ERR); CHARACTER OPERATOR; LABEL ERR;
        BEGIN
            REAL X, Y; X := POP; Y := POP;
            IF      OPERATOR = '+' THEN PUSH(Y + X)
            ELSE IF OPERATOR = '-' THEN PUSH(Y - X)
            ELSE IF OPERATOR = '*' THEN PUSH(Y * X)
            ELSE IF OPERATOR = '/' THEN BEGIN
                                            IF X = 0 THEN
                                            BEGIN
                                                EVALUATEDERR :- "DIV BY ZERO";
                                                GOTO ERR;
                                            END;
                                            PUSH(Y / X);
                                        END
            ELSE IF OPERATOR = '^' THEN PUSH(Y ** X)
            ELSE
            BEGIN
                EVALUATEDERR :- "UNKNOWN OPERATOR";
                GOTO ERR;
            END
        END CALC;

        PROCEDURE READCHAR(CH); NAME CH; CHARACTER CH;
        BEGIN
            IF T.MORE THEN CH := T.GETCHAR ELSE CH := EOT;
        END READCHAR;

        PROCEDURE SKIPWHITESPACE(CH); NAME CH; CHARACTER CH;
        BEGIN
            WHILE (CH = SPACE) OR (CH = TAB) OR (CH = CR) OR (CH = LF) DO
                READCHAR(CH);
        END SKIPWHITESPACE;

        PROCEDURE BUSYBOX(OP, ERR); INTEGER OP; LABEL ERR;
        BEGIN
            CHARACTER OPERATOR;
            REAL NUMBR;
            BOOLEAN NEGATIVE;

            SKIPWHITESPACE(CH);

            IF OP = EXPRESSION THEN
            BEGIN

                NEGATIVE := FALSE;
                WHILE (CH = '+') OR (CH = '-') DO
                BEGIN
                    IF CH = '-' THEN NEGATIVE :=  NOT NEGATIVE;
                    READCHAR(CH);
                END;

                BUSYBOX(TERM, ERR);

                IF NEGATIVE THEN
                BEGIN
                    NUMBR := POP; PUSH(0 - NUMBR);
                END;

                WHILE (CH = '+') OR (CH = '-') DO
                BEGIN
                    OPERATOR := CH; READCHAR(CH);
                    BUSYBOX(TERM, ERR); CALC(OPERATOR, ERR);
                END;

            END
            ELSE IF OP = TERM THEN
            BEGIN

                BUSYBOX(FACTOR, ERR);
                WHILE (CH = '*') OR (CH = '/') DO
                BEGIN
                    OPERATOR := CH; READCHAR(CH);
                    BUSYBOX(FACTOR, ERR); CALC(OPERATOR, ERR)
                END

            END
            ELSE IF OP = FACTOR THEN
            BEGIN

                BUSYBOX(POWER, ERR);
                WHILE CH = '^' DO
                BEGIN
                    OPERATOR := CH; READCHAR(CH);
                    BUSYBOX(POWER, ERR); CALC(OPERATOR, ERR)
                END

            END
            ELSE IF OP = POWER THEN
            BEGIN

                IF (CH = '+') OR (CH = '-') THEN
                    BUSYBOX(EXPRESSION, ERR)
                ELSE IF (CH >= '0') AND (CH <= '9') THEN
                    BUSYBOX(NUMBER, ERR)
                ELSE IF (CH >= 'A') AND (CH <= 'Z') THEN
                    BUSYBOX(VARIABLE, ERR)
                ELSE IF CH = '(' THEN
                BEGIN
                    READCHAR(CH);
                    BUSYBOX(EXPRESSION, ERR);
                    IF CH = ')' THEN READCHAR(CH) ELSE GOTO ERR;
                END
                ELSE GOTO ERR;

            END
            ELSE IF OP = VARIABLE THEN
            BEGIN

                TEXT VARNAM;
                VARNAM :- BLANKS(32);
                WHILE (CH >= 'A') AND (CH <= 'Z')
                   OR (CH >= '0') AND (CH <= '9') DO
                BEGIN
                    VARNAM.PUTCHAR(CH);
                    READCHAR(CH);
                END;
                PUSH(EV.GET(VARNAM.STRIP));

            END
            ELSE IF OP = NUMBER THEN
            BEGIN

                NUMBR := 0;
                WHILE (CH >= '0') AND (CH <= '9') DO
                BEGIN
                    NUMBR := 10 * NUMBR + RANK(CH) - RANK('0'); READCHAR(CH);
                END;
                IF CH = '.' THEN
                BEGIN
                    REAL FAKTOR;
                    READCHAR(CH);
                    FAKTOR := 10;
                    WHILE (CH >= '0') AND (CH <= '9') DO
                    BEGIN
                        NUMBR := NUMBR + (RANK(CH) - RANK('0')) / FAKTOR;
                        FAKTOR := 10 * FAKTOR;
                        READCHAR(CH);
                    END;
                END;
                PUSH(NUMBR);

            END;

            SKIPWHITESPACE(CH);

        END BUSYBOX;

        BOOLEAN PROCEDURE EVAL(INP); TEXT INP;
        BEGIN
            EVALUATEDERR :- NOTEXT;
            STACKPOS := 0;
            T :- COPY(INP.STRIP);
            READCHAR(CH);
            BUSYBOX(EXPRESSION, ERRORLABEL);
            IF NOT T.MORE AND STACKPOS = 1 AND CH = EOT THEN
            BEGIN
                EVALUATED := POP;
                EVAL := TRUE;
                GOTO NOERRORLABEL;
            END;
    ERRORLABEL:
            EVAL := FALSE;
            IF EVALUATEDERR = NOTEXT THEN
                EVALUATEDERR :- "INVALID EXPRESSION: " & INP;
    NOERRORLABEL:
        END EVAL;

        REAL PROCEDURE RESULT;
            RESULT := EVALUATED;

        TEXT PROCEDURE ERR;
            ERR :- EVALUATEDERR;

        INTEGER EXPRESSION, TERM, FACTOR, POWER, NUMBER, VARIABLE;
        CHARACTER TAB, LF, CR, SPACE, EOT, CH;
        REAL ARRAY STACK(0:31);
        INTEGER STACKPOS;
        REAL EVALUATED;
        TEXT EVALUATEDERR, T;

        EXPRESSION := 1;
        TERM := 2;
        FACTOR := 3;
        POWER := 4;
        NUMBER := 5;
        VARIABLE := 6;

        TAB := CHAR(9);
        LF := CHAR(10);
        CR := CHAR(13);
        SPACE := CHAR(32);
        EOT := CHAR(0);

    END EXPR;

    REF(EXPR) EXA, EXB;
    EXA :- NEW EXPR(NEW ENV.SET("X", 3));
    EXB :- NEW EXPR(NEW ENV.SET("X", 5));
    IF EXA.EVAL("2 ^ X") THEN
    BEGIN
        IF EXB.EVAL("2 ^ X")
        THEN OUTFIX(EXB.RESULT - EXA.RESULT, 3, 10)
        ELSE OUTTEXT(EXB.ERR)
    END ELSE OUTTEXT(EXA.ERR);
    OUTIMAGE;

END.


     compiled = code(' define("triple(x)") :(a);triple triple = 3 * x :(return)')  :<compiled>
a    x = 1
     first = triple(x)
     x = 3
     output = triple(x) - first
end


proc eval_twice {func a b} {
    set x $a
    set 1st [expr $func]
    set x $b
    set 2nd [expr $func]
    expr {$2nd - $1st}
}

puts [eval_twice {2 ** $x} 3 5] ;# ==> 24


evalx(prog, a, b)
Func
  Local x,eresult1,eresult2
  a→x
  expr(prog)→eresult1
  b→x
  expr(prog)→eresult2
  Return eresult2-eresult1
EndFunc

■ evalx("ℯ^x", 0., 1)
                      1.71828


#lang transd

MainModule: {
    code: "(+ 5 x)",

    _start: (lambda (textout
        (- (to-Int (with x 100 (snd (eval code))))
           (to-Int (with x 1 (snd (eval code)))))
        ))
}


(defun eval-subtract-for-two-values-of-x (code-fragment x1 x0)
  (- (eval ^(let ((x ,x1)) ,code-fragment))
     (eval ^(let ((x ,x0)) ,code-fragment))))

(eval-subtract-for-two-values-of-x 1 2) ;; yields -4.67077427047161


eval_with_x() {
	set -- "`x=$2; eval "$1"`" "`x=$3; eval "$1"`"
	expr "$2" - "$1"
}

eval_with_x '
	# compute 2 ** $x
	p=1
	while test $x -gt 0; do
		p=`expr $p \* 2`
		x=`expr $x - 1`
	done
	echo $p
' 3 5
# Prints '24'


import "meta" for Meta

var x
Meta.eval("x = 2")
System.print("First  x = %(x)")
var y = x // save this value

Meta.eval("x = 5")
System.print("Second x = %(x)")

Meta.eval("x = x - y")
System.print("Delta  x = %(x)")


fcn evalWithX(text,x) {
   f:=Compiler.Compiler.compileText(text);
   f.x = x; // set free var in compiled blob
   f.__constructor(); // run blob
   vm.regX   // compiler sets the VMs X register for cases like this
}
const TEXT="var x; x*2"; // variables need to be declared
evalWithX(TEXT,5) - evalWithX(TEXT,3) #--> 4


V n = BigInt(‘9516311845790656153499716760847001433441357’)
V e = BigInt(65537)
V d = BigInt(‘5617843187844953170308463622230283376298685’)

V txt = ‘Rosetta Code’

print(‘Plain text:             ’txt)

V txtN = txt.reduce(BigInt(0), (a, b) -> a * 256 + b.code)
print(‘Plain text as a number: ’txtN)

V enc = pow(txtN, e, n)
print(‘Encoded:                ’enc)

V dec = pow(enc, d, n)
print(‘Decoded:                ’dec)

V decTxt = ‘’
L dec != 0
   decTxt ‘’= Char(code' dec % 256)
   dec I/= 256

print(‘Decoded number as text: ’reversed(decTxt))


WITH GMP, GMP.Integers, Ada.Text_IO, GMP.Integers.Aliased_Internal_Value, Interfaces.C;
USE GMP, Gmp.Integers, Ada.Text_IO, Interfaces.C;

PROCEDURE Main IS
   FUNCTION "+" (U : Unbounded_Integer) RETURN Mpz_T IS (Aliased_Internal_Value (U));
   FUNCTION "+" (S : String) RETURN Unbounded_Integer IS (To_Unbounded_Integer (S));
   FUNCTION Image_Cleared (M : Mpz_T) RETURN String IS (Image (To_Unbounded_Integer (M)));
   N                 : Unbounded_Integer := +"9516311845790656153499716760847001433441357";
   E                 : Unbounded_Integer := +"65537";
   D                 : Unbounded_Integer := +"5617843187844953170308463622230283376298685";
   Plain_Text        : CONSTANT String := "Rosetta Code";
   M, M_C, M_D       : Mpz_T;
-- We import two C functions from the GMP library which are not in the specs of the gmp package
   PROCEDURE Mpz_Import
     (Rop   : Mpz_T; Count : Size_T; Order : Int; Size : Size_T; Endian : Int;
      Nails : Size_T; Op : Char_Array);
   PRAGMA Import (C, Mpz_Import, "__gmpz_import");

   PROCEDURE Mpz_Export
     (Rop    : OUT Char_Array; Count : ACCESS Size_T; Order : Int; Size : Size_T;
      Endian : Int; Nails : Size_T; Op : Mpz_T);
   PRAGMA Import (C, Mpz_Export, "__gmpz_export");
BEGIN
   Mpz_Init (M);
   Mpz_Init (M_C);
   Mpz_Init (M_D);
   Mpz_Import (M, Plain_Text'Length + 1, 1, 1, 0, 0, To_C (Plain_Text));
   Mpz_Powm (M_C, M, +E, +N);
   Mpz_Powm (M_D, M_C, +D, +N);
   Put_Line ("Encoded plain text: " & Image_Cleared (M));
   DECLARE Decrypted : Char_Array (1 .. Mpz_Sizeinbase (M_C, 256));
   BEGIN
      Put_Line ("Encryption of this encoding: " & Image_Cleared (M_C));
      Mpz_Export (Decrypted, NULL, 1, 1, 0, 0, M_D);
      Put_Line ("Decryption of the encoding: " & Image_Cleared (M_D));
      Put_Line ("Final decryption: " &  To_Ada (Decrypted));
   END;
END Main;


COMMENT
   First cut.  Doesn't yet do blocking and deblocking.  Also, as
   encryption and decryption are identical operations but for the
   reciprocal exponents used, only one has been implemented below.

   A later release will address these issues.
COMMENT

BEGIN
   PR precision=1000 PR
   MODE LLI = LONG LONG INT;    CO For brevity CO
   PROC mod power = (LLI base, exponent, modulus) LLI :
   BEGIN
      LLI result := 1, b := base, e := exponent;
      IF exponent < 0
      THEN
	 put (stand error, (("Negative exponent", exponent, newline)))
      ELSE
	 WHILE e > 0
	 DO
	    (ODD e | result := (result * b) MOD modulus);
	    e OVERAB 2; b := (b * b) MOD modulus
	 OD
      FI;
      result
   END;
   PROC modular inverse = (LLI a, m) LLI :
   BEGIN
      PROC extended gcd = (LLI x, y) []LLI :
      BEGIN
	 LLI v := 1, a := 1, u := 0, b := 0, g := x, w := y;
	 WHILE w>0
	 DO
	    LLI q := g % w, t := a - q * u;
	    a := u; u := t;
	    t := b - q * v;
	    b := v; v := t;
	    t := g - q * w;
	    g := w; w := t
	 OD;
	 a PLUSAB (a < 0 | u | 0);
	 (a, b, g)
      END;
      [] LLI egcd = extended gcd (a, m);
      (egcd[3] > 1 | 0 | egcd[1] MOD m)
   END;
   PROC number to string = (LLI number) STRING :
   BEGIN
      [] CHAR map = (blank + "ABCDEFGHIJKLMNOPQRSTUVWXYZ")[@0];
      LLI local number := number;
      INT length := SHORTEN SHORTEN ENTIER long long log(number) + 1;
      (ODD length | length PLUSAB 1);
      [length % 2] CHAR text;
      FOR i FROM length % 2 BY -1 TO 1
      DO
	 INT index = SHORTEN SHORTEN (local number MOD 100);
	 text[i] := (index > 26 | "?" | map[index]);
	 local number := local number % 100
      OD;
      text
   END;
CO The parameters of a particular RSA cryptosystem CO
   LLI p = 3490529510847650949147849619903898133417764638493387843990820577;
   LLI q = 32769132993266709549961988190834461413177642967992942539798288533;
   LLI n = p * q;
   LLI phi n = (p-1) * (q-1);
   LLI e = 9007;
   LLI d = modular inverse (e, phi n);
CO A ciphertext CO
   LLI cipher text = 96869613754622061477140922254355882905759991124574319874695120930816298225145708356931476622883989628013391990551829945157815154;
CO Print out the corresponding plain text CO
   print (number to string (mod power (ciphertext, d, n)))
END


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gmp.h>

int main(void)
{
    mpz_t n, d, e, pt, ct;

    mpz_init(pt);
    mpz_init(ct);
    mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10);
    mpz_init_set_str(e, "65537", 10);
    mpz_init_set_str(d, "5617843187844953170308463622230283376298685", 10);

    const char *plaintext = "Rossetta Code";
    mpz_import(pt, strlen(plaintext), 1, 1, 0, 0, plaintext);

    if (mpz_cmp(pt, n) > 0)
        abort();

    mpz_powm(ct, pt, e, n);
    gmp_printf("Encoded:   %Zd\n", ct);

    mpz_powm(pt, ct, d, n);
    gmp_printf("Decoded:   %Zd\n", pt);

    char buffer[64];
    mpz_export(buffer, NULL, 1, 1, 0, 0, pt);
    printf("As String: %s\n", buffer);

    mpz_clears(pt, ct, n, e, d, NULL);
    return 0;
}


using System;
using System.Numerics;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        BigInteger n = BigInteger.Parse("9516311845790656153499716760847001433441357");
        BigInteger e = 65537;
        BigInteger d = BigInteger.Parse("5617843187844953170308463622230283376298685");

        const string plaintextstring = "Hello, Rosetta!";
        byte[] plaintext = ASCIIEncoding.ASCII.GetBytes(plaintextstring);
        BigInteger pt = new BigInteger(plaintext);
        if (pt > n)
            throw new Exception();

        BigInteger ct = BigInteger.ModPow(pt, e, n);
        Console.WriteLine("Encoded:  " + ct);

        BigInteger dc = BigInteger.ModPow(ct, d, n);
        Console.WriteLine("Decoded:  " + dc);

        string decoded = ASCIIEncoding.ASCII.GetString(dc.ToByteArray());
        Console.WriteLine("As ASCII: " + decoded);
    }
}


(defparameter *n* 9516311845790656153499716760847001433441357)
(defparameter *e* 65537)
(defparameter *d* 5617843187844953170308463622230283376298685)

;; magic
(defun encode-string (message)
  (parse-integer (reduce #'(lambda (x y) (concatenate 'string x y))
     (loop for c across message collect (format nil "~2,'0d" (- (char-code c) 32))))))

;; sorcery
(defun decode-string (message) (coerce (loop for (a b) on
  (loop for char across (write-to-string message) collect char)
    by #'cddr collect (code-char (+ (parse-integer (coerce (list a b) 'string)) 32))) 'string))

;; ACTUAL RSA ALGORITHM STARTS HERE ;;

;; fast modular exponentiation: runs in O(log exponent)
;; acc is initially 1 and contains the result by the end
(defun mod-exp (base exponent modulus acc)
  (if (= exponent 0) acc
    (mod-exp (mod (* base base) modulus) (ash exponent -1) modulus
	     (if (= (mod exponent 2) 1) (mod (* acc base) modulus) acc))))

;; to encode a message, we first convert it to its integer form.
;; then, we raise it to the *e* power, modulo *n*
(defun encode-rsa (message)
  (mod-exp (encode-string message) *e* *n* 1))

;; to decode a message, we raise it to *d* power, modulo *n*
;; and then convert it back into a string
(defun decode-rsa (message)
  (decode-string (mod-exp message *d* *n* 1)))


void main() {
    import std.stdio, std.bigint, std.algorithm, std.string, std.range,
           modular_exponentiation;

    immutable txt = "Rosetta Code";
    writeln("Plain text:             ", txt);

    // A key set big enough to hold 16 bytes of plain text in
    // a single block (to simplify the example) and also big enough
    // to demonstrate efficiency of modular exponentiation.
    immutable BigInt n = "2463574872878749457479".BigInt *
                         "3862806018422572001483".BigInt;
    immutable BigInt e = 2 ^^ 16 + 1;
    immutable BigInt d = "5617843187844953170308463622230283376298685";

    // Convert plain text to a number.
    immutable txtN = reduce!q{ (a << 8) | uint(b) }(0.BigInt, txt);
    if (txtN >= n)
        return writeln("Plain text message too long.");
    writeln("Plain text as a number: ", txtN);

    // Encode a single number.
    immutable enc = txtN.powMod(e, n);
    writeln("Encoded:                ", enc);

    // Decode a single number.
    auto dec = enc.powMod(d, n);
    writeln("Decoded:                ", dec);

    // Convert number to text.
    char[] decTxt;
    for (; dec; dec >>= 8)
        decTxt ~= (dec & 0xff).toInt;
    writeln("Decoded number as text: ", decTxt.retro);
}


program RSA_code;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  Velthuis.BigIntegers;

type
  TRSA = record
  private
    n, e, d: BigInteger;
    class function PlainTextAsNumber(data: AnsiString): BigInteger; static;
    class function NumberAsPlainText(Num: BigInteger): AnsiString; static;
  public
    constructor Create(n, e, d: string);
    function Encode(data: AnsiString): string;
    function Decode(code: string): AnsiString;
  end;

function EncodeRSA(data: AnsiString): string;
var
  n, e, d, bb, ptn, etn, dtn: BigInteger;
begin
    // a key set big enough to hold 16 bytes of plain text in
    // a single block (to simplify the example) and also big enough
    // to demonstrate efficiency of modular exponentiation.
  n := '9516311845790656153499716760847001433441357';
  e := '65537';
  d := '5617843187844953170308463622230283376298685';

  for var c in data do
  begin
    bb := ord(c);
    ptn := (ptn shl 8) or bb;
  end;

  if BigInteger.Compare(ptn, n) >= 0 then
  begin
    Writeln('Plain text message too long');
    exit;
  end;
  writeln('Plain text as a number:', ptn.ToString);
  writeln(ptn.ToString);

  // encode a single number
  etn := BigInteger.ModPow(ptn, e, n);
  Writeln('Encoded:               ', etn.ToString);

  // decode a single number
  dtn := BigInteger.ModPow(etn, d, n);
  Writeln('Decoded:               ', dtn.ToString);

  // convert number to text
  var db: AnsiString;
  var bff: BigInteger := $FF;
  while dtn.BitLength > 0 do
  begin
    db := ansichar((dtn and bff).AsInteger) + db;
    dtn := dtn shr 8;
  end;
  Write('Decoded number as text:"', db, '"');
end;

const
  pt = 'Rosetta Code';

{ TRSA }

constructor TRSA.Create(n, e, d: string);
begin
  self.n := n;
  self.e := e;
  self.d := d;
end;

function TRSA.Decode(code: string): AnsiString;
var
  etn, dtn: BigInteger;
begin
   // decode a single number
  etn := code;
  dtn := BigInteger.ModPow(etn, d, n);
  Result := NumberAsPlainText(dtn);
end;

function TRSA.Encode(data: AnsiString): string;
var
  ptn: BigInteger;
begin
  ptn := PlainTextAsNumber(data);

  // encode a single number
  Result := BigInteger.ModPow(ptn, e, n).ToString;
end;

class function TRSA.NumberAsPlainText(Num: BigInteger): AnsiString;
var
  bff: BigInteger;
begin
  // convert number to text
  bff := $FF;
  Result := '';
  while Num.BitLength > 0 do
  begin
    Result := ansichar((Num and bff).AsInteger) + Result;
    Num := Num shr 8;
  end;
end;

class function TRSA.PlainTextAsNumber(data: AnsiString): BigInteger;
var
  c: AnsiChar;
  bb, n: BigInteger;
begin
  Result := 0;
  n := '9516311845790656153499716760847001433441357';
  for c in data do
  begin
    bb := ord(c);
    Result := (Result shl 8) or bb;
  end;

  if BigInteger.Compare(Result, n) >= 0 then
    raise Exception.Create('Plain text message too long');
end;

var
  RSA: TRSA;
  Encoded: string;

const
  n = '9516311845790656153499716760847001433441357';
  e = '65537';
  d = '5617843187844953170308463622230283376298685';
  TEST_WORD = 'Rosetta Code';

begin
  RSA := TRSA.Create(n, e, d);
  Encoded := RSA.Encode(TEST_WORD);
  writeln('Plain text:            ', TEST_WORD);
  writeln('Encoded:               ', Encoded);
  writeln('Decoded:               ', RSA.Decode(Encoded));
  Readln;
end.


%%% @author Tony Wallace <[email protected]>
%%% @doc
%%% For details of the algorithms used see
%%% https://en.wikipedia.org/wiki/Modular_exponentiation
%%% @end
%%% Created : 21 Jul 2021 by Tony Wallace <[email protected]>

-module mod.
-export [mod_mult/3,mod_exp/3,binary_exp/2,test/0].

mod_mult(I1,I2,Mod) when
      I1 > Mod,
      is_integer(I1), is_integer(I2), is_integer(Mod) ->
    mod_mult(I1 rem Mod,I2,Mod);
mod_mult(I1,I2,Mod) when
      I2 > Mod,
      is_integer(I1), is_integer(I2), is_integer(Mod) ->
    mod_mult(I1,I2 rem Mod,Mod);
mod_mult(I1,I2,Mod) when
      is_integer(I1), is_integer(I2), is_integer(Mod) ->
    (I1 * I2) rem Mod.

mod_exp(Base,Exp,Mod) when
      is_integer(Base),
      is_integer(Exp),
      is_integer(Mod),
      Base > 0,
      Exp > 0,
      Mod > 0 ->
    binary_exp_mod(Base,Exp,Mod);
mod_exp(_,0,_) -> 1.

binary_exp(Base,Exponent) when
      is_integer(Base),
      is_integer(Exponent),
      Base > 0,
      Exponent > 0 ->
    binary_exp(Base,Exponent,1);
binary_exp(_,0) ->
    1.

binary_exp(_,0,Result) ->
    Result;
binary_exp(Base,Exponent,Acc) ->
    binary_exp(Base*Base,Exponent bsr 1,Acc * exp_factor(Base,Exponent)).

binary_exp_mod(Base,Exponent,Mod) ->
    binary_exp_mod(Base rem Mod,Exponent,Mod,1).
binary_exp_mod(_,0,_,Result) ->
   Result;
binary_exp_mod(Base,Exponent,Mod,Acc) ->
    binary_exp_mod((Base*Base) rem Mod,
		   Exponent bsr 1,Mod,(Acc * exp_factor(Base,Exponent))rem Mod).

exp_factor(_,0) ->
    1;
exp_factor(Base,1) ->
    Base;
exp_factor(Base,Exponent) ->
    exp_factor(Base,Exponent band 1).

test() ->
    445 = mod_exp(4,13,497),
    %% Rosetta code example:
    R = 1527229998585248450016808958343740453059 =
	mod_exp(2988348162058574136915891421498819466320163312926952423791023078876139,
		2351399303373464486466122544523690094744975233415544072992656881240319,
		binary_exp(10,40)),
    R.

%%%-------------------------------------------------------------------
%%% @author Tony Wallace <[email protected]>
%%% @doc
%%% Blocking not implemented.  Runtime exception if message too long
%%% Not a practical issue as RSA usually limited to symmetric key exchange
%%% However as a key exchange tool no advantage in compressing plaintext
%%% so that is not done either.
%%% @end
%%% Created : 24 Jul 2021 by Tony Wallace <[email protected]>
%%%-------------------------------------------------------------------

-module rsa.
-export([key_gen/2,encrypt/2,decrypt/2,test/0]).
-type key() :: {integer(),integer()}.
key_gen({N,D},E) ->
    {{E,N},{D,N}}.
-spec encrypt(key(),integer()) -> integer().
encrypt({E,N},MessageInt)
  when MessageInt < N ->
    mod:mod_exp(MessageInt,E,N).
-spec decrypt(key(),integer()) -> integer().
decrypt({D,N},Message) ->
    mod:mod_exp(Message,D,N).
test() ->
    PlainText=10722935,
    N = 9516311845790656153499716760847001433441357,
    E = 65537,
    D = 5617843187844953170308463622230283376298685,
    {PublicKey,PrivateKey} = key_gen({N,D},E),
    PlainText =:= decrypt(PrivateKey,
			  encrypt(PublicKey,PlainText)).


//Nigel Galloway February 12th., 2018
let RSA n g l = bigint.ModPow(l,n,g)
let encrypt = RSA 65537I 9516311845790656153499716760847001433441357I
let m_in = System.Text.Encoding.ASCII.GetBytes "The magic words are SQUEAMISH OSSIFRAGE"|>Array.chunkBySize 16|>Array.map(Array.fold(fun n g ->(n*256I)+(bigint(int g))) 0I)
let n = Array.map encrypt m_in
let decrypt = RSA 5617843187844953170308463622230283376298685I 9516311845790656153499716760847001433441357I
let g = Array.map decrypt n
let m_out = Array.collect(fun n->Array.unfold(fun n->if n>0I then Some(byte(int (n%256I)),n/256I) else None) n|>Array.rev) g|>System.Text.Encoding.ASCII.GetString
printfn "'The magic words are SQUEAMISH OSSIFRAGE' as numbers -> %A\nEncrypted -> %A\nDecrypted -> %A\nAs text -> %A" m_in n g m_out


' version 17-01-2017
' compile with: fbc -s console

#Include Once "gmp.bi"

Dim As Mpz_ptr e, d, n, pt, ct

e  = Allocate(Len(__mpz_struct))
d  = Allocate(Len(__mpz_struct))
n  = Allocate(Len(__mpz_struct))
pt = Allocate(Len(__mpz_struct)) : mpz_init(pt)
ct = Allocate(Len(__mpz_struct)) : mpz_init(ct)

mpz_init_set_str(e, "65537", 10)
mpz_init_set_str(d, "5617843187844953170308463622230283376298685", 10)
mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10)

Dim As ZString Ptr plaintext : plaintext = Allocate(1000)
Dim As ZString Ptr text      : text      = Allocate(1000)
*plaintext = "Rosetta Code"

mpz_import(pt, Len(*plaintext), 1, 1, 0, 0, plaintext)

If mpz_cmp(pt, n) > 0 Then GoTo clean_up

mpz_powm(ct, pt, e, n)
gmp_printf(!"  Encoded: %Zd\n", ct)

mpz_powm(pt, ct, d, n)
gmp_printf(!"  Decoded: %Zd\n", pt)

mpz_export(text, NULL, 1, 1, 0, 0, pt)
Print "As string: "; *text

clean_up:
DeAllocate(plaintext) : DeAllocate(text)
mpz_clear(e) : mpz_clear(d) : mpz_clear(n)
mpz_clear(pt) : mpz_clear(ct)

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


INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit
INCLUDE "H6:REALMATH.ACT"

DEFINE PTR="CARD"

REAL one,two,four,six

PROC Init()
  IntToReal(1,one)
  IntToReal(2,two)
  IntToReal(4,four)
  IntToReal(6,six)
RETURN

PROC Fun=*(REAL POINTER x,y,res)
  DEFINE JSR="$20"
  DEFINE RTS="$60"
  [JSR $00 $00 ;JSR to address set by SetFun
   RTS]

PROC SetFun(PTR p)
  PTR addr

  addr=Fun+1 ;location of address of JSR
  PokeC(addr,p)
RETURN

PROC Rate(REAL POINTER x,y,res)
  REAL tmp

  Sqrt(y,tmp)         ;tmp=sqrt(y)
  RealMult(x,tmp,res) ;res=x*sqrt(y)
RETURN

PROC RK4(PTR f REAL POINTER dx,x,y,res)
  REAL k1,k2,k3,k4,dx2,k12,k22,tmp1,tmp2,tmp3

  SetFun(f)
  Fun(x,y,tmp1)        ;tmp1=f(x,y)
  RealMult(dx,tmp1,k1) ;k1=dx*f(x,y)

  RealDiv(dx,two,dx2)  ;dx2=dx/2
  RealDiv(k1,two,k12)  ;k12=k1/2
  RealAdd(x,dx2,tmp1)  ;tmp1=x+dx/2
  RealAdd(y,k12,tmp2)  ;tmp2=y+k1/2
  Fun(tmp1,tmp2,tmp3)  ;tmp3=f(x+dx/2,y+k1/2)
  RealMult(dx,tmp3,k2) ;k2=dx*f(x+dx/2,y+k1/2)

  RealDiv(k2,two,k22)  ;k22=k2/2
  RealAdd(y,k22,tmp2)  ;tmp2=y+k2/2
  Fun(tmp1,tmp2,tmp3)  ;tmp3=f(x+dx/2,y+k2/2)
  RealMult(dx,tmp3,k3) ;k3=dx*f(x+dx/2,y+k2/2)

  RealAdd(x,dx,tmp1)   ;tmp1=x+dx
  RealAdd(y,k3,tmp2)   ;tmp2=y+k3
  Fun(tmp1,tmp2,tmp3)  ;tmp3=f(x+dx,y+k3)
  RealMult(dx,tmp3,k4) ;k4=dx*f(x+dx,y+k3)

  RealAdd(k2,k3,tmp1)     ;tmp1=k2+k3
  RealMult(two,tmp1,tmp2) ;tmp2=2*k2+2*k3
  RealAdd(k1,tmp2,tmp1)   ;tmp3=k1+2*k2+2*k3
  RealAdd(tmp1,k4,tmp2)   ;tmp2=k1+2*k2+2*k3+k4
  RealDiv(tmp2,six,tmp1)  ;tmp1=(k1+2*k2+2*k3+k4)/6
  RealAdd(y,tmp1,res)     ;res=y+(k1+2*k2+2*k3+k4)/6
RETURN

PROC Calc(REAL POINTER x,res)
  REAL tmp1,tmp2

  RealMult(x,x,tmp1)      ;tmp1=x*x
  RealDiv(tmp1,four,tmp2) ;tmp2=x*x/4
  RealAdd(tmp2,one,tmp1)  ;tmp1=x*x/4+1
  Power(tmp1,two,res)     ;res=(x*x/4+1)^2
RETURN

PROC RelError(REAL POINTER a,b,res)
  REAL tmp

  RealDiv(a,b,tmp)     ;tmp=a/b
  RealSub(tmp,one,res) ;res=a/b-1
RETURN

PROC Main()
  REAL x0,x1,x,dx,y,y2,err,tmp1,tmp2
  CHAR ARRAY s(20)
  INT i,n

  Put(125) PutE() ;clear the screen
  MathInit()
  Init()
  PrintF("%-2S %-11S %-8S%E","x","y","rel err")

  IntToReal(0,x0)
  IntToReal(10,x1)
  ValR("0.1",dx)

  RealSub(x1,x0,tmp1)    ;tmp1=x1-x0
  RealDiv(tmp1,dx,tmp2)  ;tmp2=(x1-x0)/dx
  n=RealToInt(tmp2)      ;n=(x1-x0)/dx
  i=0
  IntToReal(1,y)
  DO
    IntToReal(i,tmp1)      ;tmp1=i
    RealMult(dx,tmp1,tmp2) ;tmp2=i*dx
    RealAdd(x0,tmp2,x)     ;x=x0+i*dx

    IF i MOD 10=0 THEN
      Calc(x,y2)
      RelError(y,y2,err)
      StrR(x,s) PrintF("%-2S ",s)
      StrR(y,s) PrintF("%-11S ",s)
      StrR(err,s) PrintF("%-8S%E",s)
    FI

    i==+1
    IF i>n THEN EXIT FI

    RK4(rate,dx,x,y,tmp1)  ;tmp1=rk4(rate,dx,x0+dx*(i-1),y)
    RealAssign(tmp1,y)     ;y=rk4(rate,dx,x0+dx*(i-1),y)
  OD
RETURN


with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
procedure RungeKutta is
   type Floaty is digits 15;
   type Floaty_Array is array (Natural range <>) of Floaty;
   package FIO is new Ada.Text_IO.Float_IO(Floaty); use FIO;
   type Derivative is access function(t, y : Floaty) return Floaty;
   package Math is new Ada.Numerics.Generic_Elementary_Functions (Floaty);
   function calc_err (t, calc : Floaty) return Floaty;

   procedure Runge (yp_func : Derivative; t, y : in out Floaty_Array;
                    dt : Floaty) is
      dy1, dy2, dy3, dy4 : Floaty;
   begin
      for n in t'First .. t'Last-1 loop
         dy1 := dt * yp_func(t(n), y(n));
         dy2 := dt * yp_func(t(n) + dt / 2.0, y(n) + dy1 / 2.0);
         dy3 := dt * yp_func(t(n) + dt / 2.0, y(n) + dy2 / 2.0);
         dy4 := dt * yp_func(t(n) + dt, y(n) + dy3);
         t(n+1) := t(n) + dt;
         y(n+1) := y(n) + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0;
      end loop;
   end Runge;

   procedure Print (t, y : Floaty_Array; modnum : Positive) is begin
      for i in t'Range loop
         if i mod modnum = 0 then
            Put("y(");   Put (t(i), Exp=>0, Fore=>0, Aft=>1);
            Put(") = "); Put (y(i), Exp=>0, Fore=>0, Aft=>8);
            Put(" Error:"); Put (calc_err(t(i),y(i)), Aft=>5);
            New_Line;
         end if;
      end loop;
   end Print;

   function yprime (t, y : Floaty) return Floaty is begin
      return t * Math.Sqrt (y);
   end yprime;
   function calc_err (t, calc : Floaty) return Floaty is
      actual : constant Floaty := (t**2 + 4.0)**2 / 16.0;
   begin return abs(actual-calc);
   end calc_err;

   dt : constant Floaty := 0.10;
   N : constant Positive := 100;
   t_arr, y_arr : Floaty_Array(0 .. N);
begin
   t_arr(0) := 0.0;
   y_arr(0) := 1.0;
   Runge (yprime'Access, t_arr, y_arr, dt);
   Print (t_arr, y_arr, 10);
end RungeKutta;


package main

import (
    "fmt"
    "math/big"
)

func main() {
    var n, e, d, bb, ptn, etn, dtn big.Int
    pt := "Rosetta Code"
    fmt.Println("Plain text:            ", pt)

    // a key set big enough to hold 16 bytes of plain text in
    // a single block (to simplify the example) and also big enough
    // to demonstrate efficiency of modular exponentiation.
    n.SetString("9516311845790656153499716760847001433441357", 10)
    e.SetString("65537", 10)
    d.SetString("5617843187844953170308463622230283376298685", 10)

    // convert plain text to a number
    for _, b := range []byte(pt) {
        ptn.Or(ptn.Lsh(&ptn, 8), bb.SetInt64(int64(b)))
    }
    if ptn.Cmp(&n) >= 0 {
        fmt.Println("Plain text message too long")
        return
    }
    fmt.Println("Plain text as a number:", &ptn)

    // encode a single number
    etn.Exp(&ptn, &e, &n)
    fmt.Println("Encoded:               ", &etn)

    // decode a single number
    dtn.Exp(&etn, &d, &n)
    fmt.Println("Decoded:               ", &dtn)

    // convert number to text
    var db [16]byte
    dx := 16
    bff := big.NewInt(0xff)
    for dtn.BitLen() > 0 {
        dx--
        db[dx] = byte(bb.And(&dtn, bff).Int64())
        dtn.Rsh(&dtn, 8)
    }
    fmt.Println("Decoded number as text:", string(db[dx:]))
}


module RSAMaker
   where
import Data.Char ( chr )

encode :: String -> [Integer]
encode s = map (toInteger . fromEnum ) s

rsa_encode :: Integer -> Integer -> [Integer] -> [Integer]
rsa_encode n e numbers = map (\num -> mod ( num ^ e ) n ) numbers

rsa_decode :: Integer -> Integer -> [Integer] -> [Integer]
rsa_decode d n ciphers = map (\c -> mod ( c ^ d ) n ) ciphers

decode :: [Integer] -> String
decode encoded = map ( chr . fromInteger ) encoded

divisors :: Integer -> [Integer]
divisors n = [m | m <- [1..n] , mod n m == 0 ]

isPrime :: Integer -> Bool
isPrime n = divisors n == [1,n]

totient :: Integer -> Integer -> Integer
totient prime1 prime2 = (prime1 - 1 ) * ( prime2 - 1 )

myE :: Integer -> Integer
myE tot = head [n | n <- [2..tot - 1] , gcd n tot == 1]

myD :: Integer -> Integer -> Integer  -> Integer
myD e n phi = head [d | d <- [1..n] , mod ( d * e ) phi == 1]

main = do
   putStrLn "Enter a test text!"
   text <- getLine
   let primes = take 90 $ filter isPrime [1..]
       p1     = last primes
       p2     = last $ init primes
       tot    = totient p1 p2
       e      =  myE tot
       n   = p1  * p2
       rsa_encoded  =  rsa_encode n e $ encode text
       d  =  myD e n tot
       encrypted = concatMap show rsa_encoded
       decrypted = decode $ rsa_decode d n rsa_encoded
   putStrLn ("Encrypted: " ++ encrypted )
   putStrLn ("And now decrypted: " ++ decrypted )


BEGIN
   PROC rk4 = (PROC (REAL, REAL) REAL f, REAL y, x, dx) REAL :
   BEGIN  CO Fourth-order Runge-Kutta method CO
      REAL dy1 = dx * f(x, y);
      REAL dy2 = dx * f(x + dx / 2.0, y + dy1 / 2.0);
      REAL dy3 = dx * f(x + dx / 2.0, y + dy2 / 2.0);
      REAL dy4 = dx * f(x + dx, y + dy3);
      y + (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0
   END;
   REAL x0 = 0, x1 = 10, y0 = 1.0;			CO Boundary conditions. CO
   REAL dx = 0.1;					CO Step size. CO
   INT num points = ENTIER ((x1 - x0) / dx + 0.5);	CO Add 0.5 for rounding errors. CO
   [0:num points]REAL y;   y[0] := y0;			CO Grid and starting point.CO
   PROC dy by dx = (REAL x, y) REAL : x * sqrt(y);	CO Differential equation. CO
   FOR i TO num points
   DO
      y[i] := rk4 (dy by dx, y[i-1], x0 + dx * (i - 1), dx)
   OD;
   print (("   x              true y         calc y       relative error", newline));
   FOR i FROM 0 BY 10 TO  num points
   DO
      REAL x = x0 + dx * i;
      REAL true y = (x * x + 4.0) ^ 2 / 16.0;
      printf (($3(-zzd.7dxxx), -d.4de-ddl$, x, true y, y[i], y[i] / true y - 1.0))
   OD
END


procedure main()  # rsa demonstration

    n := 9516311845790656153499716760847001433441357
    e := 65537
    d := 5617843187844953170308463622230283376298685
    b := 2^integer(log(n,2))   # for blocking
    write("RSA Demo using\n   n = ",n,"\n   e = ",e,"\n   d = ",d,"\n   b = ",b)

    every m := !["Rosetta Code", "Hello Word!",
                 "This message is too long.", repl("x",*decode(n+1))] do {
       write("\nMessage = ",image(m))
       write(  "Encoded = ",m := encode(m))
       if m := rsa(m,e,n) then {               # unblocked
          write(  "Encrypt = ",m)
          write(  "Decrypt = ",m := rsa(m,d,n))
          }
       else {                                  # blocked
          every put(C := [], rsa(!block(m,b),e,n))
          writes("Encrypt = ") ; every writes(!C," ") ; write()
          every put(P := [], rsa(!C,d,n))
          writes("Decrypt = ") ; every writes(!P," ") ; write()
          write("Unblocked = ",m := unblock(P,b))
          }
       write(  "Decoded = ",image(decode(m)))
       }
end

procedure mod_power(base, exponent, modulus)   # fast modular exponentation
   result := 1
   while exponent > 0 do {
      if exponent % 2 = 1 then
         result := (result * base) % modulus
      exponent /:= 2
      base := base ^ 2 % modulus
      }
   return result
end

procedure rsa(text,e,n)  # return rsa encryption of numerically encoded message; fail if text < n
return mod_power(text,e,text < n)
end

procedure encode(text)  # numerically encode ascii text as int
   every (message := 0) := ord(!text) + 256 * message
   return message
end

procedure decode(message)  # numerically decode int to ascii text
   text := ""
   while text ||:= char((0 < message) % 256) do
      message /:= 256
   return reverse(text)
end

procedure block(m,b)   # break lg int into blocks of size b
   M := []
   while push(M, x := (0 < m) % b) do
      m /:= b
   return M
end

procedure unblock(M,b)  # reassemble blocks of size b into lg int
   every (m := 0) := !M + b * m
   return m
end


begin
    real procedure rk4 ( real procedure f ; real value y, x, dx ) ;
    begin  % Fourth-order Runge-Kutta method %
       real dy1, dy2, dy3, dy4;
       dy1 := dx * f(x, y);
       dy2 := dx * f(x + dx / 2.0, y + dy1 / 2.0);
       dy3 := dx * f(x + dx / 2.0, y + dy2 / 2.0);
       dy4 := dx * f(x + dx, y + dy3);
       y + (dy1 + 2.0 * dy2 + 2.0 * dy3 + dy4) / 6.0
    end rk4;
    real x0, x1, y0, dx;
    integer numPoints;
    x0 := 0; x1 := 10; y0 := 1.0;                                % Boundary conditions. %
    dx := 0.1;                                                   % Step size. %
    numPoints := entier ((x1 - x0) / dx + 0.5);                  % Add 0.5 for rounding errors. %
    begin
        real procedure dyByDx ( real value x, y ) ; x * sqrt(y); % Differential equation. %
        real array y ( 0 :: numPoints); y(0) := y0;              % Grid and starting point. %
        for i := 1 until numPoints do y(i) := rk4 (dyByDx, y(i-1), x0 + dx * (i - 1), dx);
        write( "   x              true y         calc y       relative error" );
        for i := 0 step 10 until numPoints do begin
            real x, trueY;
            x     := x0 + dx * i;
            trueY := (x * x + 4.0) ** 2 / 16.0;
            write( r_format := "A", r_w := 12, r_d := 7, s_w := 3, x, trueY, y( i )
                 , r_format := "S", r_w := 12, y( i ) / trueY - 1
                 )
        end for_i
    end
end.


      ∇RK4[⎕]∇
    ∇
[0]   Z←R(Y¯ RK4)Y;T;YN;TN;∆T;∆Y1;∆Y2;∆Y3;∆Y4
[1]   (T R ∆T)←R
[2]  LOOP:→(R≤TN←¯1↑T)/EXIT
[3]   ∆Y1←∆T×TN Y¯ YN←¯1↑Y
[4]   ∆Y2←∆T×(TN+∆T÷2)Y¯ YN+∆Y1÷2
[5]   ∆Y3←∆T×(TN+∆T÷2)Y¯ YN+∆Y2÷2
[6]   ∆Y4←∆T×(TN+∆T)Y¯ YN+∆Y3
[7]   Y←Y,YN+(∆Y1+(2×∆Y2)+(2×∆Y3)+∆Y4)÷6
[8]   T←T,TN+∆T
[9]   →LOOP
[10] EXIT:Z←T,[⎕IO+.5]Y
    ∇

      ∇PRINT[⎕]∇
    ∇
[0]   PRINT;TABLE
[1]   TABLE←0 10 .1({⍺×⍵*.5}RK4)1
[2]   ⎕←'T' 'RK4 Y' 'ERROR'⍪TABLE,TABLE[;2]-{((4+⍵*2)*2)÷16}TABLE[;1]
    ∇


public static void main(String[] args) {
    /*
    This is probably not the best method...or even the most optimized way...however it works since n and d are too big to be ints or longs
    This was also only tested with 'Rosetta Code' and 'Hello World'
    It's also pretty limited on plainText size (anything bigger than the above will fail)
    */
    BigInteger n = new BigInteger("9516311845790656153499716760847001433441357");
    BigInteger e = new BigInteger("65537");
    BigInteger d = new BigInteger("5617843187844953170308463622230283376298685");
    Charset c = Charsets.UTF_8;
    String plainText = "Rosetta Code";
    System.out.println("PlainText : " + plainText);
    byte[] bytes = plainText.getBytes();
    BigInteger plainNum = new BigInteger(bytes);
    System.out.println("As number : " + plainNum);
    BigInteger Bytes = new BigInteger(bytes);
    if (Bytes.compareTo(n) == 1) {
        System.out.println("Plaintext is too long");
        return;
    }
    BigInteger enc = plainNum.modPow(e, n);
    System.out.println("Encoded: " + enc);
    BigInteger dec = enc.modPow(d, n);
    System.out.println("Decoded: " + dec);
    String decText = new String(dec.toByteArray(), c);
    System.out.println("As text: " + decText);
}


function rsaencode(clearmsg::AbstractString, nmod::Integer, expub::Integer)
    bytes = parse(BigInt, "0x" * bytes2hex(collect(UInt8, clearmsg)))
    return powermod(bytes, expub, nmod)
end

function rsadecode(cryptmsg::Integer, nmod::Integer, dsecr::Integer)
    decoded = powermod(encoded, dsecr, nmod)
    return join(Char.(hex2bytes(hex(decoded))))
end

msg = "Rosetta Code."
nmod = big"9516311845790656153499716760847001433441357"
expub = 65537
dsecr = big"5617843187844953170308463622230283376298685"

encoded = rsaencode(msg, nmod, expub)
decoded = rsadecode(encoded, nmod, dsecr)
println("\n# $msg\n -> ENCODED: $encoded\n -> DECODED: $decoded")


#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double rk4(double(*f)(double, double), double dx, double x, double y)
{
	double	k1 = dx * f(x, y),
		k2 = dx * f(x + dx / 2, y + k1 / 2),
		k3 = dx * f(x + dx / 2, y + k2 / 2),
		k4 = dx * f(x + dx, y + k3);
	return y + (k1 + 2 * k2 + 2 * k3 + k4) / 6;
}

double rate(double x, double y)
{
	return x * sqrt(y);
}

int main(void)
{
	double *y, x, y2;
	double x0 = 0, x1 = 10, dx = .1;
	int i, n = 1 + (x1 - x0)/dx;
	y = (double *)malloc(sizeof(double) * n);

	for (y[0] = 1, i = 1; i < n; i++)
		y[i] = rk4(rate, dx, x0 + dx * (i - 1), y[i-1]);

	printf("x\ty\trel. err.\n------------\n");
	for (i = 0; i < n; i += 10) {
		x = x0 + dx * i;
		y2 = pow(x * x / 4 + 1, 2);
		printf("%g\t%g\t%g\n", x, y[i], y[i]/y2 - 1);
	}

	return 0;
}


// version 1.1.4-3

import java.math.BigInteger

fun main(args: Array<String>) {
    val n = BigInteger("9516311845790656153499716760847001433441357")
    val e = BigInteger("65537")
    val d = BigInteger("5617843187844953170308463622230283376298685")
    val c = Charsets.UTF_8
    val plainText = "Rosetta Code"
    println("PlainText : $plainText")
    val bytes = plainText.toByteArray(c)
    val plainNum = BigInteger(bytes)
    println("As number : $plainNum")
    if (plainNum > n) {
        println("Plaintext is too long")
        return
    }

    val enc = plainNum.modPow(e, n)
    println("Encoded   : $enc")

    val dec = enc.modPow(d, n)
    println("Decoded   : $dec")

    val decText = dec.toByteArray().toString(c)
    println("As text   : $decText")
}


toNumPlTxt[s_] := FromDigits[ToCharacterCode[s], 256];
fromNumPlTxt[plTxt_] := FromCharacterCode[IntegerDigits[plTxt, 256]];
enc::longmess = "Message '``' is too long for n = ``.";
enc[n_, _, mess_] /;
   toNumPlTxt[mess] >= n := (Message[enc::longmess, mess, n]; $Failed);
enc[n_, e_, mess_] := PowerMod[toNumPlTxt[mess], e, n];
dec[n_, d_, en_] := fromNumPlTxt[PowerMod[en, d, n]];
text = "The cake is a lie!";
n = 9516311845790656153499716760847001433441357;
e = 65537;
d = 5617843187844953170308463622230283376298685;
en = enc[n, e, text];
de = dec[n, d, en];
Print["Text: '" <> text <> "'"];
Print["n = " <> IntegerString[n]];
Print["e = " <> IntegerString[e]];
Print["d = " <> IntegerString[d]];
Print["Numeric plaintext: " <> IntegerString[toNumPlTxt[text]]];
Print["Encoded: " <> IntegerString[en]];
Print["Decoded: '" <> de <> "'"];


import strutils, streams, strformat
# nimble install stint
import stint

const messages = ["PPAP", "I have a pen, I have a apple\nUh! Apple-pen!",
    "I have a pen, I have pineapple\nUh! Pineapple-pen!",
    "Apple-pen, pineapple-pen\nUh! Pen-pineapple-apple-pen\nPen-pineapple-apple-pen\nDance time!", "\a\0"]
const
  n = u256("9516311845790656153499716760847001433441357")
  e = u256("65537")
  d = u256("5617843187844953170308463622230283376298685")
proc pcount(s: string, c: char): int{.inline.} =
  for ch in s:
    if ch != c:
      break
    result+=1
func powmodHexStr(s: string, key, divisor: UInt256): string{.inline.} =
  toHex(powmod(UInt256.fromHex(s), key, divisor))
proc translate(hexString: string, key, divisor: UInt256,
    encrypt = true): string =
  var
    strm = newStringStream(hexString)
    chunk, residue, tempChunk: string
  let chunkSize = len(toHex(divisor))
  while true:
    tempChunk = strm.peekStr(chunkSize-int(encrypt)*3)
    if len(chunk) > 0:
      if len(tempChunk) == 0:
        if encrypt:
          result&=powmodHexStr(pcount(chunk, '0').toHex(2)&align(chunk,
              chunkSize-3, '0'), key, divisor)
        else:
          tempChunk = align(powmodHexStr(chunk, key, divisor), chunkSize-1, '0')
          residue = tempChunk[2..^1].strip(trailing = false, chars = {'0'})
          result&=align(residue, fromHex[int](tempChunk[0..1])+len(residue), '0')
        break
      result&=align(powmodHexStr(chunk, key, divisor), chunkSize-3+int(
          encrypt)*3, '0')
    discard strm.readStr(chunkSize-int(encrypt)*3)
    chunk = tempChunk
  strm.close()
for message in messages:
  echo(&"plaintext:\n{message}")
  var numPlaintext = message.toHex()
  echo(&"numerical plaintext in hex:\n{numPlaintext}")
  var ciphertext = translate(numPlaintext, e, n)
  echo(&"ciphertext is: \n{ciphertext}")
  var deciphertext = translate(ciphertext, d, n, false)
  echo(&"deciphered numerical plaintext in hex is:\n{deciphertext}")
  echo(&"deciphered plaintext is:\n{parseHexStr(deciphertext)}\n\n")


stigid(V,b)=subst(Pol(V),'x,b);		\\ inverse function digits(...)

n = 9516311845790656153499716760847001433441357;
e = 65537;
d = 5617843187844953170308463622230283376298685;

text = "Rosetta Code"

inttext = stigid(Vecsmall(text),256)	\\ message as an integer
encoded = lift(Mod(inttext, n) ^ e)	\\ encrypted message
decoded = lift(Mod(encoded, n) ^ d)	\\ decrypted message
message = Strchr(digits(decoded, 256))	\\ readable message


using System;

namespace RungeKutta
{
    class Program
    {
        static void Main(string[] args)
        {
            //Incrementers to pass into the known solution
            double t = 0.0;
            double T = 10.0;
            double dt = 0.1;

            // Assign the number of elements needed for the arrays
            int n = (int)(((T - t) / dt)) + 1;

            // Initialize the arrays for the time index 's' and estimates 'y' at each index 'i'
            double[] y = new double[n];
            double[] s = new double[n];

            // RK4 Variables
            double dy1;
            double dy2;
            double dy3;
            double dy4;

            // RK4 Initializations
            int i = 0;
            s[i] = 0.0;
            y[i] = 1.0;

            Console.WriteLine(" ===================================== ");
            Console.WriteLine(" Beging 4th Order Runge Kutta Method ");
            Console.WriteLine(" ===================================== ");

            Console.WriteLine();
            Console.WriteLine(" Given the example Differential equation: \n");
            Console.WriteLine("     y' = t*sqrt(y) \n");
            Console.WriteLine(" With the initial conditions: \n");
            Console.WriteLine("     t0 = 0" + ", y(0) = 1.0 \n");
            Console.WriteLine(" Whose exact solution is known to be: \n");
            Console.WriteLine("     y(t) = 1/16*(t^2 + 4)^2 \n");
            Console.WriteLine(" Solve the given equations over the range t = 0...10 with a step value dt = 0.1 \n");
            Console.WriteLine(" Print the calculated values of y at whole numbered t's (0.0,1.0,...10.0) along with the error \n");
            Console.WriteLine();

            Console.WriteLine(" y(t) " +"RK4" + " ".PadRight(18) + "Absolute Error");
            Console.WriteLine(" -------------------------------------------------");
            Console.WriteLine(" y(0) " + y[i] + " ".PadRight(20) + (y[i] - solution(s[i])));

            // Iterate and implement the Rk4 Algorithm
            while (i < y.Length - 1)
            {

                dy1 = dt * equation(s[i], y[i]);
                dy2 = dt * equation(s[i] + dt / 2, y[i] + dy1 / 2);
                dy3 = dt * equation(s[i] + dt / 2, y[i] + dy2 / 2);
                dy4 = dt * equation(s[i] + dt, y[i] + dy3);

                s[i + 1] = s[i] + dt;
                y[i + 1] = y[i] + (dy1 + 2 * dy2 + 2 * dy3 + dy4) / 6;

                double error = Math.Abs(y[i + 1] - solution(s[i + 1]));
                double t_rounded = Math.Round(t + dt, 2);

                if (t_rounded % 1 == 0)
                {
                    Console.WriteLine(" y(" + t_rounded + ")" + " " + y[i + 1] + " ".PadRight(5) + (error));
                }

                i++;
                t += dt;

            };//End Rk4

            Console.ReadLine();
        }

        // Differential Equation
        public static double equation(double t, double y)
        {
            double y_prime;
            return y_prime = t*Math.Sqrt(y);
        }

        // Exact Solution
        public static double solution(double t)
        {
            double actual;
            actual = Math.Pow((Math.Pow(t, 2) + 4), 2)/16;
            return actual;
        }
    }
}


use bigint;

$n = 9516311845790656153499716760847001433441357;
$e = 65537;
$d = 5617843187844953170308463622230283376298685;

package Message {
    my @alphabet;
    push @alphabet, $_ for 'A' .. 'Z', ' ';
    my $rad = +@alphabet;
    $code{$alphabet[$_]} = $_ for 0..$rad-1;

    sub encode {
        my($t) = @_;
        my $cnt = my $sum = 0;
        for (split '', reverse $t) {
            $sum += $code{$_} * $rad**$cnt;
            $cnt++;
        }
        $sum;
    }

    sub decode {
        my($n) = @_;
        my(@i);
        while () {
            push @i, $n % $rad;
            last if  $n < $rad;
            $n = int $n / $rad;
        }
        reverse join '', @alphabet[@i];
    }

    sub expmod {
    my($a, $b, $n) = @_;
    my $c = 1;
    do {
        ($c *= $a) %= $n if $b % 2;
        ($a *= $a) %= $n;
    } while ($b = int $b/2);
    $c;
}

}

my $secret_message = "ROSETTA CODE";

$numeric_message  = Message::encode $secret_message;
$numeric_cipher   = Message::expmod $numeric_message, $e, $n;
$text_cipher      = Message::decode $numeric_cipher;
$numeric_cipher2  = Message::encode $text_cipher;
$numeric_message2 = Message::expmod $numeric_cipher2, $d, $n;
$secret_message2  = Message::decode $numeric_message2;

print <<"EOT";
Secret message is $secret_message
Secret message in integer form is $numeric_message
After exponentiation with public exponent we get: $numeric_cipher
This turns into the string $text_cipher
If we re-encode it in integer form we get $numeric_cipher2
After exponentiation with SECRET exponent we get: $numeric_message2
This turns into the string $secret_message2
EOT


/*
 * compiled with:
 * g++ (Debian 8.3.0-6) 8.3.0
 *
 * g++ -std=c++14 -o rk4 %
 *
 */
# include <iostream>
# include <math.h>

auto rk4(double f(double, double))
{
  return [f](double t, double y, double dt) -> double {
    double dy1 { dt * f( t     , y       ) },
           dy2 { dt * f( t+dt/2, y+dy1/2 ) },
           dy3 { dt * f( t+dt/2, y+dy2/2 ) },
           dy4 { dt * f( t+dt  , y+dy3   ) };
    return ( dy1 + 2*dy2 + 2*dy3 + dy4 ) / 6;
  };
}

int main(void)
{
  constexpr
    double TIME_MAXIMUM    {  10.0 },
           T_START         {   0.0 },
           Y_START         {   1.0 },
           DT              {   0.1 },
           WHOLE_TOLERANCE { 1e-12 };

  auto dy = rk4( [](double t, double y) -> double { return t*sqrt(y); } ) ;

  for (
      auto y { Y_START }, t { T_START };
      t <= TIME_MAXIMUM;
      y += dy(t,y,DT), t += DT
      )
    if (ceilf(t)-t < WHOLE_TOLERANCE)
      printf("y(%4.1f)\t=%12.6f \t error: %12.6e\n", t, y, std::fabs(y - pow(t*t+4,2)/16));

  return 0;
}


without javascript_semantics
include builtins/mpfr.e

mpz n = mpz_init("9516311845790656153499716760847001433441357"),
    e = mpz_init("65537"),
    d = mpz_init("5617843187844953170308463622230283376298685"),
    pt = mpz_init(),
    ct = mpz_init()

string plaintext = "Rossetta Code" -- matches C/zkl
--                 "Rosetta Code" -- matches D/FreeBasic/Go/Icon/J/Kotlin/Seed7.

mpz_import(pt, length(plaintext), 1, 1, 0, 0, plaintext)

if mpz_cmp(pt, n)>0 then ?9/0 end if

mpz_powm(ct, pt, e, n);
printf(1,"Encoded:   %s\n", {mpz_get_str(ct)})

mpz_powm(pt, ct, d, n);
printf(1,"Decoded:   %s\n", {mpz_get_str(pt)})

integer size =floor((mpz_sizeinbase(pt,2)+7)/8)
atom pMem = allocate(size,true)
integer count = mpz_export(pMem, 1, 1, 0, 0, pt)
if count>size then ?9/0 end if

printf(1,"As String: %s\n", {peek({pMem,count})})

{pt, ct, n, e, d} = mpz_free({pt, ct, n, e, d})


### This is a copy of "lib/rsa.l" ###

# Generate long random number
(de longRand (N)
   (use (R D)
      (while (=0 (setq R (abs (rand)))))
      (until (> R N)
         (unless (=0 (setq D (abs (rand))))
            (setq R (* R D)) ) )
      (% R N) ) )

# X power Y modulus N
(de **Mod (X Y N)
   (let M 1
      (loop
         (when (bit? 1 Y)
            (setq M (% (* M X) N)) )
         (T (=0 (setq Y (>> 1 Y)))
            M )
         (setq X (% (* X X) N)) ) ) )

# Probabilistic prime check
(de prime? (N)
   (and
      (> N 1)
      (bit? 1 N)
      (let (Q (dec N)  K 0)
         (until (bit? 1 Q)
            (setq
               Q  (>> 1 Q)
               K  (inc K) ) )
         (do 50
            (NIL (_prim? N Q K))
            T ) ) ) )

# (Knuth Vol.2, p.379)
(de _prim? (N Q K)
   (use (X J Y)
      (while (> 2 (setq X (longRand N))))
      (setq
         J 0
         Y (**Mod X Q N) )
      (loop
         (T
            (or
               (and (=0 J) (= 1 Y))
               (= Y (dec N)) )
            T )
         (T
            (or
               (and (> J 0) (= 1 Y))
               (<= K (inc 'J)) )
            NIL )
         (setq Y (% (* Y Y) N)) ) ) )

# Find a prime number with `Len' digits
(de prime (Len)
   (let P (longRand (** 10 (*/ Len 2 3)))
      (unless (bit? 1 P)
         (inc 'P) )
      (until (prime? P)  # P: Prime number of size 2/3 Len
         (inc 'P 2) )
      # R: Random number of size 1/3 Len
      (let (R (longRand (** 10 (/ Len 3)))  K (+ R (% (- P R) 3)))
         (when (bit? 1 K)
            (inc 'K 3) )
         (until (prime? (setq R (inc (* K P))))
            (inc 'K 6) )
         R ) ) )

# Generate RSA key
(de rsaKey (N)  #> (Encrypt . Decrypt)
   (let (P (prime (*/ N 5 10))  Q (prime (*/ N 6 10)))
      (cons
         (* P Q)
         (/
            (inc (* 2 (dec P) (dec Q)))
            3 ) ) ) )

# Encrypt a list of characters
(de encrypt (Key Lst)
   (let Siz (>> 1 (size Key))
      (make
         (while Lst
            (let N (char (pop 'Lst))
               (while (> Siz (size N))
                  (setq N (>> -16 N))
                  (inc 'N (char (pop 'Lst))) )
               (link (**Mod N 3 Key)) ) ) ) ) )

# Decrypt a list of numbers
(de decrypt (Keys Lst)
   (mapcan
      '((N)
         (let Res NIL
            (setq N (**Mod N (cdr Keys) (car Keys)))
            (until (=0 N)
               (push 'Res (char (& `(dec (** 2 16)) N)))
               (setq N (>> 16 N)) )
            Res ) )
      Lst ) )
### End of "lib/rsa.l" ###

# Generate 100-digit keys (private . public)
: (setq Keys (rsaKey 100))
-> (14394597526321726957429995133376978449624406217727317004742182671030....

# Encrypt
: (setq CryptText
   (encrypt (car Keys)
      (chop "The quick brown fox jumped over the lazy dog's back") ) )
-> (72521958974980041245760752728037044798830723189142175108602418861716...

# Decrypt
: (pack (decrypt Keys CryptText))
-> "The quick brown fox jumped over the lazy dog's back"


$n = [BigInt]::Parse("9516311845790656153499716760847001433441357")
$e = [BigInt]::new(65537)
$d = [BigInt]::Parse("5617843187844953170308463622230283376298685")
$plaintextstring = "Hello, Rosetta!"
$plaintext = [Text.ASCIIEncoding]::ASCII.GetBytes($plaintextstring)
[BigInt]$pt = [BigInt]::new($plaintext)
if ($n -lt $pt) {throw "`$n = $n < $pt = `$pt"}
$ct = [BigInt]::ModPow($pt, $e, $n)
"Encoded:  $ct"
$dc = [BigInt]::ModPow($ct, $d, $n)
"Decoded:  $dc"
$decoded = [Text.ASCIIEncoding]::ASCII.GetString($dc.ToByteArray())
"As ASCII: $decoded"


import binascii

n = 9516311845790656153499716760847001433441357    # p*q = modulus
e = 65537
d = 5617843187844953170308463622230283376298685

message='Rosetta Code!'
print('message                 ', message)

hex_data   = binascii.hexlify(message.encode())
print('hex data                ', hex_data)

plain_text = int(hex_data, 16)
print('plain text integer      ', plain_text)

if plain_text > n:
  raise Exception('plain text too large for key')

encrypted_text = pow(plain_text,     e, n)
print('encrypted text integer  ', encrypted_text)

decrypted_text = pow(encrypted_text, d, n)
print('decrypted text integer  ', decrypted_text)

print('message                 ', binascii.unhexlify(hex(decrypted_text)[2:]).decode())     # [2:] slicing, to strip the 0x part


#lang racket
(require math/number-theory)
(define-logger rsa)
(current-logger rsa-logger)

;; -| STRING TO NUMBER MAPPING |----------------------------------------------------------------------
(define (bytes->number B) ; We'll need our data in numerical form ..
  (for/fold ((rv 0)) ((b B)) (+ b (* rv 256))))

(define (number->bytes N) ; .. and back again
  (define (inr n b) (if (zero? n) b (inr (quotient n 256) (bytes-append (bytes (modulo n 256)) b))))
  (inr N (bytes)))

;; -| RSA PUBLIC / PRIVATE FUNCTIONS |----------------------------------------------------------------
;; The basic definitions... pretty well lifted from the text book!
(define ((C e n) p)
  ;; Just do the arithmetic to demonstrate RSA...
  ;; breaking large messages into blocks is something for another day.
  (unless (< p n) (raise-argument-error 'C (format "(and/c integer? (</c ~a))" n) p))
  (modular-expt p e n))

(define ((P d n) c)
  (modular-expt c d n))

;; -| RSA KEY GENERATION |----------------------------------------------------------------------------
;; Key generation
;; Full description of the steps can be found on Wikipedia
(define (RSA-keyset function-base-name)
  (log-info "RSA-keyset: ~s" function-base-name)
  (define max-k 4294967087)
  ;; I'm guessing this RNG is about as cryptographically strong as replacing spaces with tabs.
  (define (big-random n-rolls)
    (for/fold ((rv 1)) ((roll (in-range n-rolls 0 -1))) (+ (* rv (add1 max-k)) 1 (random max-k))))
  (define (big-random-prime)
    (define start-number (big-random (/ 1024 32)))
    (log-debug "got large (possibly non-prime) number, finding next prime")
    (next-prime (match start-number ((? odd? o) o) ((app add1 e) e))))

  ;; [1] Choose two distinct prime numbers p and q.
  (log-debug "generating p")
  (define p (big-random-prime))
  (log-debug "p generated")
  (log-debug "generating q")
  (define q (big-random-prime))
  (log-debug "q generated")
  (log-info "primes generated")

  ;; [2] Compute n = pq.
  (define n (* p q))

  ;; [3] Compute φ(n) = φ(p)φ(q) = (p − 1)(q − 1) = n - (p + q -1),
  ;;                    where φ is Euler's totient function.
  (define φ (- n (+ p q -1)))

  ;; [4] Choose an integer e such that 1 < e < φ(n) and gcd(e, φ(n)) = 1; i.e., e and φ(n) are
  ;;     coprime. ... most commonly 2^16 + 1 = 65,537 ...
  (define e (+ (expt 2 16) 1))

  ;; [5] Determine d as d ≡ e−1 (mod φ(n)); i.e., d is the multiplicative inverse of e (modulo φ(n)).
  (log-debug "generating d")
  (define d (modular-inverse e φ))
  (log-info "d generated")
  (values n e d))

;; -| GIVE A USABLE SET OF PRIVATE STUFF TO A USER |--------------------------------------------------
;; six values: the public (encrypt) function (numeric)
;;             the private (decrypt) function (numeric)
;;             the public (encrypt) function (bytes)
;;             the private (decrypt) function (bytes)
;;             private (list n e d)
;;             public (list n e)
(define (RSA-key-pack #:function-base-name function-base-name)
  (define (rnm-fn f s) (procedure-rename f (string->symbol (format "~a-~a" function-base-name s))))
  (define-values (n e d) (RSA-keyset function-base-name))
  (define my-C (rnm-fn (C e n) "C"))
  (define my-P (rnm-fn (P d n) "P"))
  (define my-encrypt (rnm-fn (compose number->bytes my-C bytes->number) "encrypt"))
  (define my-decrypt (rnm-fn (compose number->bytes my-P bytes->number) "decrypt"))
  (values my-C my-P my-encrypt my-decrypt (list n e d) (list n e)))

;; -| HEREON IS JUST A LOAD OF CHATTY DEMOS |---------------------------------------------------------
(define (narrated-encrypt-bytes C who plain-text)
  (define plain-n (bytes->number plain-text))
  (define cypher-n (C plain-n))
  (define cypher-text (number->bytes cypher-n))
  (printf #<<EOS
~a wants to send plain text: ~s
  as number: ~s
  cyphered number: ~s
sent by ~a over the public interwebs:
~s
...

EOS
          who plain-text plain-n cypher-n who cypher-text)
  cypher-text)

(define (narrated-decrypt-bytes P who cypher-text)
  (define cypher-n (bytes->number cypher-text))
  (define plain-n (P cypher-n))
  (define plain-text (number->bytes plain-n))
  (printf #<<EOS
...
~s
  received by ~a
  as number: ~s
  decyphered (with P) number: ~s
decyphered text:
~s

EOS
          cypher-text who cypher-n plain-n plain-text)
  plain-text)

;; ENCRYPT AND DECRYPT A MESSAGE WITH THE e.g. KEYS
(define-values (given-n given-e given-d)
  (values 9516311845790656153499716760847001433441357
          65537
          5617843187844953170308463622230283376298685))

;; Get the keys specific RSA functions
(for ((message-text (list #"hello world" #"TOP SECRET!")))
  (define Bobs-public-function (C given-e given-n))
  (define Bobs-private-function (P given-d given-n))
  (define cypher-text (narrated-encrypt-bytes Bobs-public-function "Alice" message-text))
  (define plain-text (narrated-decrypt-bytes Bobs-private-function "Bob" cypher-text))
  plain-text)

;; Demonstrate with larger keys.
;; (And include a free recap on digital signatures, too)
(define-values (A-pub-C A-pvt-P A-pub-encrypt A-pvt-decrypt A-pvt-keys A-pub-keys)
  (RSA-key-pack #:function-base-name 'Alice))
(define-values (B-pub-C B-pvt-P B-pub-encrypt B-pvt-decrypt B-pvt-keys B-pub-keys)
  (RSA-key-pack #:function-base-name 'Bob))

;; Since p and q are random, it is possible that message' = "message modulo {A,B}-key-n" will be too
;; big for "message' modulo {B,A}-key-n", if that happens then I run the program again until it
;; works. Strictly, we need blocking of the signed message -- which is not yet implemented.
(let* ((plain-A-to-B #"Dear Bob, meet you in Lymm at 1200, Alice")
       (signed-A-to-B         (A-pvt-decrypt plain-A-to-B))
       (unsigned-A-to-B       (A-pub-encrypt signed-A-to-B))
       (crypt-signed-A-to-B   (B-pub-encrypt signed-A-to-B))
       (decrypt-signed-A-to-B (B-pvt-decrypt crypt-signed-A-to-B))
       (decrypt-verified-B    (A-pub-encrypt decrypt-signed-A-to-B)))
  (printf
   #<<EOS
Alice wants to send ~s to Bob.
She "encrypts" with her private "decryption" key.
(A-prv msg) -> ~s
Only she could have done this (only she has the her private key data) -- so this is a signature on the
message. Anyone can verify the signature by "decrypting" the message with the public "encryption" key.
(A-pub (A-prv msg)) -> ~s
But anyone is able to do this, so there is no privacy here.
Everyone knows that it can only be Alice at Lymm at noon, but this message is for Bob's eyes only.
We need to encrypt this with his public key:
(B-pub (A-prv msg)) -> ~s
Which is what gets posted to alt.chat.secret-rendezvous
Bob decrypts this to get the signed message from Alice:
(B-prv (B-pub (A-prv msg))) -> ~s
And verifies Alice's signature:
(A-pub (B-prv (B-pub (A-prv msg)))) -> ~s
Alice genuinely sent the message.
And nobody else (on a.c.s-r, at least) has read it.

KEYS:
 Alice's full set: ~s
 Bob's full set: ~s
EOS
   plain-A-to-B signed-A-to-B unsigned-A-to-B crypt-signed-A-to-B decrypt-signed-A-to-B
   decrypt-verified-B A-pvt-keys B-pvt-keys))


import std.stdio, std.math, std.typecons;

alias FP = real;
alias FPs = Typedef!(FP[101]);

void runge(in FP function(in FP, in FP)
           pure nothrow @safe @nogc yp_func,
           ref FPs t, ref FPs y, in FP dt) pure nothrow @safe @nogc {
    foreach (immutable n; 0 .. t.length - 1) {
        immutable FP
            dy1 = dt * yp_func(t[n], y[n]),
            dy2 = dt * yp_func(t[n] + dt / 2.0, y[n] + dy1 / 2.0),
            dy3 = dt * yp_func(t[n] + dt / 2.0, y[n] + dy2 / 2.0),
            dy4 = dt * yp_func(t[n] + dt, y[n] + dy3);
        t[n + 1] = t[n] + dt;
        y[n + 1] = y[n] + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0;
    }
}

FP calc_err(in FP t, in FP calc) pure nothrow @safe @nogc {
    immutable FP actual = (t ^^ 2 + 4.0) ^^ 2 / 16.0;
    return abs(actual - calc);
}

void main() {
    enum FP dt = 0.10;
    FPs t_arr, y_arr;

    t_arr[0] = 0.0;
    y_arr[0] = 1.0;
    runge((t, y) => t * y.sqrt, t_arr, y_arr, dt);

    foreach (immutable i; 0 .. t_arr.length)
        if (i % 10 == 0)
            writefln("y(%.1f) = %.8f Error: %.6g",
                     t_arr[i], y_arr[i],
                     calc_err(t_arr[i], y_arr[i]));
}


constant $n = 9516311845790656153499716760847001433441357;
constant $e = 65537;
constant $d = 5617843187844953170308463622230283376298685;

my $secret-message = "ROSETTA CODE";

package Message {
    my @alphabet = slip('A' .. 'Z'), ' ';
    my $rad = +@alphabet;
    my %code = @alphabet Z=> 0 .. *;
    subset Text of Str where /^^ @alphabet+ $$/;
    our sub encode(Text $t) {
	[+] %code{$t.flip.comb} Z* (1, $rad, $rad*$rad ... *);
    }
    our sub decode(Int $n is copy) {
	@alphabet[
	    gather loop {
		take $n % $rad;
		last if $n < $rad;
		$n div= $rad;
	    }
	].join.flip;
    }
}

use Test;
plan 1;

say "Secret message is $secret-message";
say "Secret message in integer form is $_" given
    my $numeric-message = Message::encode $secret-message;
say "After exponentiation with public exponent we get: $_" given
    my $numeric-cipher = expmod $numeric-message, $e, $n;
say "This turns into the string $_" given
    my $text-cipher = Message::decode $numeric-cipher;

say "If we re-encode it in integer form we get $_" given
    my $numeric-cipher2 = Message::encode $text-cipher;
say "After exponentiation with SECRET exponent we get: $_" given
    my $numeric-message2 = expmod $numeric-cipher2, $d, $n;
say "This turns into the string $_" given
    my $secret-message2 = Message::decode $numeric-message2;

is $secret-message, $secret-message2, "the message has been correctly decrypted";


import 'dart:math' as Math;

num RungeKutta4(Function f, num t, num y, num dt){
  num k1 = dt * f(t,y);
  num k2 = dt * f(t+0.5*dt, y + 0.5*k1);
  num k3 = dt * f(t+0.5*dt, y + 0.5*k2);
  num k4 = dt * f(t + dt, y + k3);
  return y + (1/6) * (k1 + 2*k2 + 2*k3 + k4);
}

void main(){
  num t  = 0;
  num dt = 0.1;
  num tf = 10;
  num totalPoints = ((tf-t)/dt).floor()+1;
  num y  = 1;
  Function f  = (num t, num y) => t * Math.sqrt(y);
  Function actual = (num t) => (1/16) * (t*t+4)*(t*t+4);
  for (num i = 0; i <= totalPoints; i++){
    num relativeError = (actual(t) - y)/actual(t);
    if (i%10 == 0){
      print('y(${t.round().toStringAsPrecision(3)}) = ${y.toStringAsPrecision(11)}  Error = ${relativeError.toStringAsPrecision(11)}');
    }
    y  = RungeKutta4(f, t, y, dt);
    t += dt;
  }
}