package main

import "fmt"

func feigenbaum() {
    maxIt, maxItJ := 13, 10
    a1, a2, d1 := 1.0, 0.0, 3.2
    fmt.Println(" i       d")
    for i := 2; i <= maxIt; i++ {
        a := a1 + (a1-a2)/d1
        for j := 1; j <= maxItJ; j++ {
            x, y := 0.0, 0.0
            for k := 1; k <= 1<<uint(i); k++ {
                y = 1.0 - 2.0*y*x
                x = a - x*x
            }
            a -= x / y
        }
        d := (a1 - a2) / (a - a1)
        fmt.Printf("%2d    %.8f\n", i, d)
        d1, a2, a1 = d, a1, a
    }
}

func main() {
    feigenbaum()
}


V file_contents = File(‘input.txt’).read()
File(‘output.txt’, ‘w’).write(file_contents)


class Feigenbaum {
    static void main(String[] args) {
        int max_it = 13
        int max_it_j = 10
        double a1 = 1.0
        double a2 = 0.0
        double d1 = 3.2
        double a

        println(" i       d")
        for (int i = 2; i <= max_it; i++) {
            a = a1 + (a1 - a2) / d1
            for (int j = 0; j < max_it_j; j++) {
                double x = 0.0
                double y = 0.0
                for (int k = 0; k < 1 << i; k++) {
                    y = 1.0 - 2.0 * y * x
                    x = a - x * x
                }
                a -= x / y
            }
            double d = (a1 - a2) / (a - a1)
            printf("%2d    %.8f\n", i, d)
            d1 = d
            a2 = a1
            a1 = a
        }
    }
}


import Data.List (mapAccumL)

feigenbaumApprox :: Int -> [Double]
feigenbaumApprox mx = snd $ mitch mx 10
  where
    mitch :: Int -> Int -> ((Double, Double, Double), [Double])
    mitch mx mxj =
      mapAccumL
        (\(a1, a2, d1) i ->
            let a =
                  iterate
                    (\a ->
                        let (x, y) =
                              iterate
                                (\(x, y) -> (a - (x * x), 1.0 - ((2.0 * x) * y)))
                                (0.0, 0.0) !!
                              (2 ^ i)
                        in a - (x / y))
                    (a1 + (a1 - a2) / d1) !!
                  mxj
                d = (a1 - a2) / (a - a1)
            in ((a, a1, d), d))
        (1.0, 0.0, 3.2)
        [2 .. (1 + mx)]

-- TEST ------------------------------------------------------------------
main :: IO ()
main =
  (putStrLn . unlines) $
  zipWith
    (\i s -> justifyRight 2 ' ' (show i) ++ '\t' : s)
    [1 ..]
    (show <$> feigenbaumApprox 13)
  where
    justifyRight n c s = drop (length s) (replicate n c ++ s)


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program readwrtFile64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

.equ TAILLEBUF,  1000
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessErreur:  .asciz "Error open input file.\n"
szMessErreur4: .asciz "Error open output file.\n"
szMessErreur1: .asciz "Error close file.\n"
szMessErreur2: .asciz "Error read file.\n"
szMessErreur3: .asciz "Error write output file.\n"

/*************************************************/
szMessCodeErr: .asciz "Error code décimal :  @ \n"

szNameFileInput:     .asciz "input.txt"
szNameFileOutput:    .asciz "output.txt"

/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sBuffer:        .skip TAILLEBUF
sZoneConv:      .skip 24
/**********************************************/
/* -- Code section                            */
/**********************************************/
.text
.global main
main:                            // entry of program
    mov x0,AT_FDCWD
    ldr x1,qAdrszNameFileInput   // file name
    mov x2,#O_RDWR               //  flags
    mov x3,#0                    // mode
    mov x8,#OPEN                 // call system OPEN
    svc #0
    cmp x0,0                     // open error ?
    ble erreur
    mov x19,x0                   // save File Descriptor
    ldr x1,qAdrsBuffer           // buffer address
    mov x2,TAILLEBUF             // buffer size
    mov x8,READ                  // call system  READ
    svc 0
    cmp x0,0                     // read error ?
    ble erreur2
    mov x20,x0                    // length read characters
                                 // close imput file
    mov x0,x19                   // Fd
    mov x8,CLOSE                 // call system CLOSE
    svc 0
    cmp x0,0                     // close error ?
    blt erreur1

                                 // create output file
    mov x0,AT_FDCWD
    ldr x1,qAdrszNameFileOutput  // file name
    mov x2,O_CREAT|O_RDWR        //  flags
    ldr x3,qFicMask1             // Mode
    mov x8,OPEN                  // call system open file
    svc 0
    cmp x0,#0                    // create error ?
    ble erreur4
    mov x19,x0                   // file descriptor
    ldr x1,qAdrsBuffer
    mov x2,x20                   // length to write
    mov x8, #WRITE               // select system call 'write'
    svc #0                       // perform the system call
    cmp x0,#0                    // error write ?
    blt erreur3

                                 // close output file
    mov x0,x19                   // Fd  fichier
    mov x8, #CLOSE               //  call system CLOSE
    svc #0
    cmp x0,#0                    // error close ?
    blt erreur1
    mov x0,#0                    // return code OK
    b 100f
erreur:
    ldr x1,qAdrszMessErreur
    bl  displayError
    mov x0,#1                   // error return code
    b 100f
erreur1:
    ldr x1,qAdrszMessErreur1
    bl  displayError
    mov x0,#1                   // error return code
    b 100f
erreur2:
    ldr x1,qAdrszMessErreur2
    bl  displayError
    mov x0,#1                  // error return code
    b 100f
erreur3:
    ldr x1,qAdrszMessErreur3
    bl  displayError
    mov x0,#1                 // error return code
    b 100f
erreur4:
    ldr x1,qAdrszMessErreur4
    bl  displayError
    mov x0,#1                 // error return code
    b 100f

100:                          // end program
    mov x8,EXIT
    svc 0
qAdrszNameFileInput:    .quad szNameFileInput
qAdrszNameFileOutput:   .quad szNameFileOutput
qAdrszMessErreur:       .quad szMessErreur
qAdrszMessErreur1:      .quad szMessErreur1
qAdrszMessErreur2:      .quad szMessErreur2
qAdrszMessErreur3:      .quad szMessErreur3
qAdrszMessErreur4:      .quad szMessErreur4
qAdrsBuffer:            .quad sBuffer
qFicMask1:              .quad 0644
/******************************************************************/
/*     display error message                                      */
/******************************************************************/
/* x0 contains error code */
/* x1 contains address error message    */
displayError:
    stp x2,lr,[sp,-16]!            // save  registers
    mov x2,x0                      // save error code
    mov x0,x1                      // display message error
    bl affichageMess
    mov x0,x2
    ldr x1,qAdrsZoneConv           // conversion error code
    bl conversion10S               // decimal conversion
    ldr x0,qAdrszMessCodeErr
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc          // insert result at @ character
    bl affichageMess               // display message final
    ldp x2,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrsZoneConv:        .quad sZoneConv
qAdrszMessCodeErr:    .quad szMessCodeErr
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


:set-state-ok t

(defun read-channel (channel limit state)
   (mv-let (ch state)
           (read-char$ channel state)
      (if (or (null ch)
              (zp limit))
          (let ((state (close-input-channel channel state)))
             (mv nil state))
          (mv-let (so-far state)
                  (read-channel channel (1- limit) state)
             (mv (cons ch so-far) state)))))

(defun read-from-file (filename limit state)
   (mv-let (channel state)
           (open-input-channel filename :character state)
      (mv-let (contents state)
              (read-channel channel limit state)
         (mv (coerce contents 'string) state))))

(defun write-channel (channel cs state)
   (if (endp cs)
       (close-output-channel channel state)
       (let ((state (write-byte$ (char-code (first cs))
                                 channel state)))
          (let ((state (write-channel channel
                                      (rest cs)
                                      state)))
              state))))

(defun write-to-file (filename str state)
   (mv-let (channel state)
           (open-output-channel filename :byte state)
      (write-channel channel (coerce str 'list) state)))

(defun copy-file (in out state)
   (mv-let (contents state)
           (read-from-file in (expt 2 40) state)
      (write-to-file out contents state)))


public class Feigenbaum {
    public static void main(String[] args) {
        int max_it = 13;
        int max_it_j = 10;
        double a1 = 1.0;
        double a2 = 0.0;
        double d1 = 3.2;
        double a;

        System.out.println(" i       d");
        for (int i = 2; i <= max_it; i++) {
            a = a1 + (a1 - a2) / d1;
            for (int j = 0; j < max_it_j; j++) {
                double x = 0.0;
                double y = 0.0;
                for (int k = 0; k < 1 << i; k++) {
                    y = 1.0 - 2.0 * y * x;
                    x = a - x * x;
                }
                a -= x / y;
            }
            double d = (a1 - a2) / (a - a1);
            System.out.printf("%2d    %.8f\n", i, d);
            d1 = d;
            a2 = a1;
            a1 = a;
        }
    }
}


def feigenbaum_delta(imax; jmax):
  def lpad: tostring | (" " *  (4 - length)) + .;
  def pp(i;x): "\(i|lpad)   \(x)";

  "Feigenbaum's delta constant incremental calculation:",
     pp("i"; "δ"),
     pp(1; "3.20"),
     ( foreach range(2; 1+imax) as $i (
         {a1: 1.0, a2: 0.0, d1: 3.2};

         .a = .a1 + (.a1 - .a2) / .d1
         | reduce range(1; 1+jmax) as $j (.;
             .x = 0 | .y = 0
             | reduce range(1; 1+pow(2;$i)) as $k (.;
                 .y = (1 - 2 * .x * .y)
                 | .x = .a - (.x * .x) )
             | .a -= (.x / .y) )
         | .d = (.a1 - .a2) / (.a - .a1)
	 | .emit = pp($i; .d)
         | .d1 = .d | .a2 = .a1 | .a1 = .a;

	 .emit ) ) ;

feigenbaum_delta(13; 10)


INCLUDE "D2:IO.ACT" ;from the Action! Tool Kit

PROC Dir(CHAR ARRAY filter)
  BYTE dev=[1]
  CHAR ARRAY line(255)

  Close(dev)
  Open(dev,filter,6)
  DO
    InputSD(dev,line)
    PrintE(line)
    IF line(0)=0 THEN
      EXIT
    FI
  OD
  Close(dev)
RETURN

PROC CopyFile(CHAR ARRAY src,dst)
  DEFINE BUF_LEN="1000"
  BYTE in=[1], out=[2]
  BYTE ARRAY buff(BUF_LEN)
  CARD len

  Close(in)
  Close(out)
  Open(in,src,4)
  Open(out,dst,8)

  DO
    len=Bget(in,buff,BUF_LEN)
    IF len>0 THEN
      Bput(out,buff,len)
    FI
  UNTIL len#BUF_LEN
  OD

  Close(in)
  Close(out)
RETURN

PROC Main()
  CHAR ARRAY filter="D:*.*",
    src="D:INPUT.TXT", dst="D:OUTPUT.TXT"

  Put(125) PutE() ;clear screen

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)

  PrintF("Copy ""%S"" to ""%S""%E%E",src,dst)
  CopyFile(src,dst)

  PrintF("Dir ""%S""%E",filter)
  Dir(filter)
RETURN


with Ada.Text_IO; use Ada.Text_IO;

procedure Read_And_Write_File_Line_By_Line is
   Input, Output : File_Type;
begin
   Open (File => Input,
         Mode => In_File,
         Name => "input.txt");
   Create (File => Output,
           Mode => Out_File,
           Name => "output.txt");
   loop
      declare
         Line : String := Get_Line (Input);
      begin
         -- You can process the contents of Line here.
         Put_Line (Output, Line);
      end;
   end loop;
   Close (Input);
   Close (Output);
exception
   when End_Error =>
      if Is_Open(Input) then
         Close (Input);
      end if;
      if Is_Open(Output) then
         Close (Output);
      end if;
end Read_And_Write_File_Line_By_Line;


file i, o;
text s;

i.open("input.txt", OPEN_READONLY, 0);
o.open("output.txt", OPEN_CREATE | OPEN_TRUNCATE | OPEN_WRITEONLY,
       0644);

while (i.line(s) ^ -1) {
    o.text(s);
    o.byte('\n');
}


# http://en.wikipedia.org/wiki/Feigenbaum_constant

function feigenbaum_delta(imax=23, jmax=20)
    a1, a2, d1 = BigFloat(1.0), BigFloat(0.0), BigFloat(3.2)
    println("Feigenbaum's delta constant incremental calculation:\ni   δ\n1   3.20")
    for i in 2:imax
        a = a1 + (a1 - a2) / d1
        for j in 1:jmax
            x, y = 0, 0
            for k in 1:2^i
                y = 1 - 2 * x * y
                x = a - x * x
            end
            a -= x / y
        end
        d = (a1 - a2) / (a - a1)
        println(rpad(i, 4), lpad(d, 4))
        d1, a2 = d, a1
        a1 = a
    end
end

feigenbaum_delta()


// Version 1.2.40

fun feigenbaum() {
    val maxIt = 13
    val maxItJ = 10
    var a1 = 1.0
    var a2 = 0.0
    var d1 = 3.2
    println(" i       d")
    for (i in 2..maxIt) {
        var a = a1 + (a1 - a2) / d1
        for (j in 1..maxItJ) {
            var x = 0.0
            var y = 0.0
            for (k in 1..(1 shl i)) {
                 y = 1.0 - 2.0 * y * x
                 x = a - x * x
            }
            a -= x / y
        }
        val d = (a1 - a2) / (a - a1)
        println("%2d    %.8f".format(i,d))
        d1 = d
        a2 = a1
        a1 = a
    }
}

fun main(args: Array<String>) {
    feigenbaum()
}


PROC copy file v1 = (STRING in name, out name)VOID: (
  # note: algol68toc-1.18 - can compile, but not run v1 #
  INT errno;
  FILE in file, out file;
  errno := open(in  file, in  name, stand in  channel);
  errno := open(out file, out name, stand out channel);

  BOOL in ended := FALSE;
  PROC call back ended = (REF FILE f) BOOL: in ended := TRUE;
  on logical file end(in file, call back ended);

  STRING line;
  WHILE
    get(in  file, (line, new line));
# WHILE # NOT in ended DO # break to avoid excess new line #
    put(out file, (line, new line))
  OD;
ended:
  close(in  file);
  close(out file)
);

PROC copy file v2 = (STRING in name, out name)VOID: (
  INT errno;
  FILE in file, out file;
  errno := open(in file, in name, stand in channel);
  errno := open(out file, out name, stand out channel);

  PROC call back ended = (REF FILE f) BOOL: GO TO done;
  on logical file end(in file, call back ended);

  STRING line;
  DO
    get(in  file, line);
    put(out file, line);
    get(in  file, new line);
    put(out file, new line)
  OD;
done:
  close(in file);
  close(out file)
);

test:(
  copy file v2("input.txt","output.txt")
)


on copyFile from src into dst
       set filedata to read file src
       set outfile to open for access dst with write permission
       write filedata to outfile
       close access outfile
end copyFile

copyFile from ":input.txt" into ":output.txt"


function leftShift(n,p)
    local r = n
    while p>0 do
        r = r * 2
        p = p - 1
    end
    return r
end

-- main

local MAX_IT = 13
local MAX_IT_J = 10
local a1 = 1.0
local a2 = 0.0
local d1 = 3.2

print(" i       d")
for i=2,MAX_IT do
    local a = a1 + (a1 - a2) / d1
    for j=1,MAX_IT_J do
        local x = 0.0
        local y = 0.0
        for k=1,leftShift(1,i) do
            y = 1.0 - 2.0 * y * x
            x = a - x * x
        end
        a = a - x / y
    end
    d = (a1 - a2) / (a - a1)
    print(string.format("%2d    %.8f", i, d))
    d1 = d
    a2 = a1
    a1 = a
end


MODULE Feigenbaum;
FROM FormatString IMPORT FormatString;
FROM LongStr IMPORT RealToStr;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;

VAR
    buf : ARRAY[0..63] OF CHAR;
    i,j,k,max_it,max_it_j : INTEGER;
    a,x,y,d,a1,a2,d1 : LONGREAL;
BEGIN
    max_it := 13;
    max_it_j := 10;

    a1 := 1.0;
    a2 := 0.0;
    d1 := 3.2;

    WriteString(" i       d");
    WriteLn;
    FOR i:=2 TO max_it DO
        a := a1 + (a1 - a2) / d1;
        FOR j:=1 TO max_it_j DO
            x := 0.0;
            y := 0.0;
            FOR k:=1 TO INT(1 SHL i) DO
                y := 1.0 - 2.0 * y * x;
                x := a - x * x
            END;
            a := a - x / y
        END;
        d := (a1 - a2) / (a - a1);
        FormatString("%2i    ", buf, i);
        WriteString(buf);
        RealToStr(d, buf);
        WriteString(buf);
        WriteLn;
        d1 := d;
        a2 := a1;
        a1 := a
    END;

    ReadChar
END Feigenbaum.


/* ARM assembly Raspberry PI  */
/*  program readwrtfile.s   */

/*********************************************/
/*constantes                                */
/********************************************/
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ READ,   3
.equ WRITE,  4
.equ OPEN,   5
.equ CLOSE,  6
.equ CREATE,  8
/*  file */
.equ O_RDWR,	0x0002		@ open for reading and writing

.equ TAILLEBUF,  1000
/*********************************/
/* Initialized data              */
/*********************************/
.data
szMessErreur: .asciz "Erreur ouverture fichier input.\n"
szMessErreur4: .asciz "Erreur création fichier output.\n"
szMessErreur1: .asciz "Erreur fermeture fichier.\n"
szMessErreur2: .asciz "Erreur lecture fichier.\n"
szMessErreur3: .asciz "Erreur d'écriture dans fichier de sortie.\n"
szRetourligne: .asciz  "\n"
szMessErr: .ascii	"Error code : "
sDeci: .space 15,' '
         .asciz "\n"

szNameFileInput:	.asciz "input.txt"
szNameFileOutput:	.asciz "output.txt"

/*******************************************/
/* DONNEES NON INITIALISEES                */
/*******************************************/
.bss
sBuffer:  .skip TAILLEBUF

/**********************************************/
/* -- Code section                            */
/**********************************************/
.text
.global main
main:
    push {fp,lr}    /* save registers */

    ldr r0,iAdrszNameFileInput   @ file name
    mov r1,#O_RDWR                   @  flags
    mov r2,#0                         @ mode
    mov r7,#OPEN                     @ call system OPEN
    swi #0
    cmp r0,#0        @ open error ?
    ble erreur
    mov r8,r0               @ save File Descriptor
    ldr r1,iAdrsBuffer   @ buffer address
    mov r2,#TAILLEBUF     @ buffer size
    mov r7, #READ          @ call system  READ
    swi 0
    cmp r0,#0            @ read error ?
    ble erreur2
    mov r2,r0            @ length read characters

    /* close imput file */
    mov r0,r8     @ Fd
    mov r7, #CLOSE      @ call system CLOSE
    swi 0
    cmp r0,#0            @ close error ?
    blt erreur1

    @ create output file
    ldr r0,iAdrszNameFileOutput   @ file name
    ldr r1,iFicMask1                 @ flags
    mov r7, #CREATE                  @ call system create file
    swi 0
    cmp r0,#0                         @ create error ?
    ble erreur4
    mov r0,r8                       @ file descriptor
    ldr r1,iAdrsBuffer
    @ et r2 contains the length to write
    mov r7, #WRITE                 @ select system call 'write'
    swi #0                        @ perform the system call
    cmp r0,#0                      @ error write ?
    blt erreur3

    @ close output file
    mov r0,r8    @ Fd  fichier
    mov r7, #CLOSE    @  call system CLOSE
    swi #0
    cmp r0,#0      @ error close ?
    blt erreur1
    mov r0,#0     @ return code OK
    b 100f
erreur:
    ldr r1,iAdrszMessErreur
    bl   afficheerreur
    mov r0,#1       @ error return code
    b 100f
erreur1:
    ldr r1,iAdrszMessErreur1
    bl   afficheerreur
    mov r0,#1       @ error return code
    b 100f
erreur2:
    ldr r1,iAdrszMessErreur2
    bl   afficheerreur
    mov r0,#1       @ error return code
    b 100f
erreur3:
    ldr r1,iAdrszMessErreur3
    bl   afficheerreur
    mov r0,#1       @ error return code
    b 100f
erreur4:
    ldr r1,iAdrszMessErreur4
    bl   afficheerreur
    mov r0,#1       @ error return code
    b 100f

100:		@ end program
    pop {fp,lr}   /* restaur des  2 registres */
    mov r7, #EXIT /* appel fonction systeme pour terminer */
    swi 0
iAdrszNameFileInput:	.int szNameFileInput
iAdrszNameFileOutput:	.int szNameFileOutput
iAdrszMessErreur:		.int szMessErreur
iAdrszMessErreur1:		.int szMessErreur1
iAdrszMessErreur2:		.int szMessErreur2
iAdrszMessErreur3:		.int szMessErreur3
iAdrszMessErreur4:		.int szMessErreur4
iAdrsBuffer:				.int sBuffer
iFicMask1: 				.octa 0644
/******************************************************************/
/*     display text with size calculation                         */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
    push {r0,r1,r2,r7,lr}    			/* save  registres */
    mov r2,#0   				/* counter length */
1:      /* loop length calculation */
    ldrb r1,[r0,r2]  			/* read octet start position + index */
    cmp r1,#0       			/* if 0 its over */
    addne r2,r2,#1   			/* else add 1 in the length */
    bne 1b          			/* and loop */
                                /* so here r2 contains the length of the message */
    mov r1,r0        			/* address message in r1 */
    mov r0,#STDOUT      		/* code to write to the standard output Linux */
    mov r7, #WRITE             /* code call system "write" */
    swi #0                      /* call systeme */
    pop {r0,r1,r2,r7,lr}    	/* restaur des  2 registres */
    bx lr	        			/* return  */
/***************************************************/
/*   display error message                         */
/***************************************************/
/* r0 contains error code  r1  address error message */
afficheerreur:
   push {r1-r2,lr}    @ save registers
    mov r2,r0         @ save error code
    mov r0,r1         @ address error message
    bl affichageMess   @ display error message
    mov r0,r2         @ error code
    ldr r1,iAdrsDeci    @ result address
    bl conversion10S
    ldr r0,iAdrszMessErr @ display error code
    bl affichageMess
    pop {r1-r2,lr}    @ restaur registers
    bx lr              @ return function
iAdrszMessErr:   .int szMessErr
iAdrsDeci:		.int sDeci

/***************************************************/
/*  Converting a register to a signed decimal      */
/***************************************************/
/* r0 contains value and r1 area address    */
conversion10S:
    push {r0-r4,lr}    @ save registers
    mov r2,r1       /* debut zone stockage */
    mov r3,#'+'     /* par defaut le signe est + */
    cmp r0,#0       @ negative number ?
    movlt r3,#'-'   @ yes
    mvnlt r0,r0     @ number inversion
    addlt r0,#1
    mov r4,#10       @ length area
1:  @ start loop
    bl divisionPar10R
    add r1,#48   @ digit
    strb r1,[r2,r4]  @ store digit on area
    sub r4,r4,#1      @ previous position
    cmp r0,#0          @ stop if quotient = 0
    bne 1b

    strb r3,[r2,r4]  @ store signe
    subs r4,r4,#1    @ previous position
    blt  100f        @ if r4 < 0 -> end

    mov r1,#' '   @ space
2:
    strb r1,[r2,r4]  @store byte space
    subs r4,r4,#1    @ previous position
    bge 2b           @ loop if r4 > 0
100:
    pop {r0-r4,lr}   @ restaur registers
    bx lr

/***************************************************/
/*   division for 10 fast unsigned                 */
/***************************************************/
@ r0 contient le dividende
@ r0 retourne le quotient
@ r1 retourne le reste
divisionPar10R:
    push {r2,lr}         @ save  registers
    sub r1, r0, #10        @ calcul de r0 - 10
    sub r0, r0, r0, lsr #2  @ calcul de r0 - (r0 /4)
    add r0, r0, r0, lsr #4  @ calcul de (r0-(r0/4))+ ((r0-(r0/4))/16
    add r0, r0, r0, lsr #8  @ etc ...
    add r0, r0, r0, lsr #16
    mov r0, r0, lsr #3
    add r2, r0, r0, asl #2
    subs r1, r1, r2, asl #1    @ calcul (N-10) - (N/10)*10
    addpl r0, r0, #1          @ regul quotient
    addmi r1, r1, #10         @ regul reste
    pop {r2,lr}
    bx lr


import strformat

iterator feigenbaum(): tuple[n: int; δ: float] =
  ## Yield successive approximations of Feigenbaum constant.

  const
    MaxI = 13
    MaxJ = 10
  var
    a1 = 1.0
    a2 = 0.0
    δ = 3.2

  for i in 2..MaxI:
    var a = a1 + (a1 - a2) / δ
    for j in 1..MaxJ:
      var x, y = 0.0
      for _ in 1..(1 shl i):
        y = 1 - 2 * y * x
        x = a - x * x
      a -= x / y

    δ = (a1 - a2) / (a - a1)
    a2 = a1
    a1 = a
    yield (i, δ)

echo " i         δ"
for n, δ in feigenbaum():
  echo fmt"{n:2d}    {δ:.8f}"


constant maxIt = 13,
        maxItJ = 10
atom a1 = 1.0,
     a2 = 0.0,
     d1 = 3.2
puts(1," i d\n")
for i=2 to maxIt do
     atom a = a1 + (a1 - a2) / d1
     for j=1 to maxItJ do
          atom x = 0, y = 0
          for k=1 to power(2,i) do
               y = 1 - 2*y*x
               x = a - x*x
          end for
          a = a - x/y
     end for
     atom d = (a1-a2)/(a-a1)
     printf(1,"%2d %.8f\n",{i,d})
     d1 = d
     a2 = a1
     a1 = a
end for


source: read "input.txt"
write "output.txt" source

print source


Loop, Read, input.txt, output.txt
 FileAppend, %A_LoopReadLine%`n


BEGIN {
  while ( (getline <"input.txt") > 0 ) {
    print >"output.txt"
  }
}


#lang racket
(define (feigenbaum #:max-it (max-it 13) #:max-it-j (max-it-j 10))
  (displayln " i       d" (current-error-port))
  (define-values (_a _a1 d)
    (for/fold ((a 1) (a1 0) (d 3.2))
              ((i (in-range 2 (add1 max-it))))
      (let* ((a′ (for/fold ((a (+ a (/ (- a a1) d))))
                           ((j (in-range max-it-j)))
                   (let-values (([x y] (for/fold ((x 0) (y 0))
                                                 ((k (expt 2 i)))
                                         (values (- a (* x x))
                                                 (- 1 (* 2 y x))))))
                     (- a (/ x y)))))
             (d′ (/ (- a a1) (- a′ a))))
        (eprintf "~a   ~a\n" (~a i #:width 2) (real->decimal-string d′ 8))
        (values a′ a d′))))
  d)

(module+ main
  (feigenbaum))


(main
    { "input.txt" >>>   -- File is now on stack
    foo set             -- File is now in 'foo'
    foo "output.txt" <<< })


 OPEN "INPUT.TXT" FOR INPUT AS #1
 OPEN "OUTPUT.TXT" FOR OUTPUT AS #2
 DO UNTIL EOF(1)
   LINE INPUT #1, DATA$
   PRINT #2, DATA$
 LOOP
 CLOSE #1
 CLOSE #2
 SYSTEM


/*REXX pgm calculates the (Mitchell) Feigenbaum bifurcation velocity, #digs can be given*/
parse arg digs maxi maxj .                       /*obtain optional argument from the CL.*/
if digs=='' | digs==","  then digs= 30           /*Not specified?  Then use the default.*/
if maxi=='' | maxi==","  then maxi= 20           /* "      "         "   "   "     "    */
if maxJ=='' | maxJ==","  then maxJ= 10           /* "      "         "   "   "     "    */
#= 4.669201609102990671853203820466201617258185577475768632745651343004134330211314737138,
                      || 68974402394801381716    /*◄──Feigenbaum's constant, true value.*/
numeric digits digs                              /*use the specified # of decimal digits*/
    a1=  1
    a2=  0
    d1=  3.2
say 'Using '    maxJ      " iterations for  maxJ,  with "      digs     ' decimal digits:'
say
say copies(' ', 9)             center("correct", 11)              copies(' ', digs+1)
say center('i', 9, "─")        center('digits' , 11, "─")         center('d', digs+1, "─")

    do i=2  for maxi-1
    a= a1  +  (a1 - a2) / d1
                               do maxJ
                               x= 0;   y= 0
                                                   do 2**i;       y= 1  -  2 * x * y
                                                                  x= a  -  x*x
                                                   end   /*2**i*/
                               a= a  -  x / y
                               end   /*maxj*/
    d= (a1 - a2)  /  (a - a1)                    /*compute the delta (D) of the function*/
    t= max(0, compare(d, #)  - 2)                /*# true digs so far, ignore dec. point*/
    say center(i, 9)     center(t, 11)     d     /*display values for  I & D ──►terminal*/
    parse value  d  a1  a    with    d1  a2  a1  /*assign 3 variables with 3 new values.*/
    end   /*i*/
                                                 /*stick a fork in it,  we're all done. */
say left('', 9 + 1 + 11 + 1 + t )"↑"             /*show position of greatest accuracy.  */
say '         true value= '    # / 1             /*true value of Feigenbaum's constant. */


# Project : Feigenbaum constant calculation

decimals(8)
see "Feigenbaum constant calculation:" + nl
maxIt = 13
maxItJ = 10
a1 = 1.0
a2 = 0.0
d1 = 3.2
see "i     " + "d" + nl
for i = 2 to maxIt
     a = a1 + (a1 - a2) / d1
     for j = 1 to maxItJ
          x = 0
          y = 0
          for k = 1 to pow(2,i)
               y = 1 - 2 * y * x
               x = a - x * x
          next
          a = a - x / y
     next
     d = (a1 - a2) / (a - a1)
     if i < 10
        see "" + i + "    " + d + nl
     else
        see "" + i + "  " + d + nl
     ok
     d1 = d
     a2 = a1
     a1 = a
next


def main
    maxIt = 13
    maxItJ = 10
    a1 = 1.0
    a2 = 0.0
    d1 = 3.2
    puts " i       d"
    for i in 2 .. maxIt
        a = a1 + (a1 - a2) / d1
        for j in 1 .. maxItJ
            x = 0.0
            y = 0.0
            for k in 1 .. 1 << i
                y = 1.0 - 2.0 * y * x
                x = a - x * x
            end
            a = a - x / y
        end
        d = (a1 - a2) / (a - a1)
        print "%2d    %.8f\n" % [i, d]
        d1 = d
        a2 = a1
        a1 = a
    end
end

main()


GET "libhdr"

LET start() BE $(

    // Attempt to open the named files.
    LET source = findinput("input.txt")
    LET destination = findoutput("output.txt")

    TEST source = 0 THEN
        writes("Unable to open input.txt*N")
    ELSE TEST destination = 0 THEN
        writes("Unable to open output.txt*N")
    ELSE $(

        // The current character, initially unknown.
        LET ch = ?

        // Make the open files the current input and output streams.
        selectinput(source)
        selectoutput(destination)

        // Copy the input to the output character by character until
        // endstreamch is returned to indicate input is exhausted.
        ch := rdch()
        UNTIL ch = endstreamch DO $(
            wrch(ch)
            ch := rdch()
        $)

        // Close the currently selected streams.
        endread()
        endwrite()
    $)
$)


import Foundation

func feigenbaum(iterations: Int = 13) {
  var a = 0.0
  var a1 = 1.0
  var a2 = 0.0
  var d = 0.0
  var d1 = 3.2

  print(" i       d")

  for i in 2...iterations {
    a = a1 + (a1 - a2) / d1

    for _ in 1...10 {
      var x = 0.0
      var y = 0.0

      for _ in 1...1<<i {
        y = 1.0 - 2.0 * y * x
        x = a - x * x
      }

      a -= x / y
    }

    d = (a1 - a2) / (a - a1)
    d1 = d
    (a1, a2) = (a, a1)

    print(String(format: "%2d    %.8f", i, d))
  }
}

feigenbaum()


Module Module1

    Sub Main()
        Dim maxIt = 13
        Dim maxItJ = 10
        Dim a1 = 1.0
        Dim a2 = 0.0
        Dim d1 = 3.2
        Console.WriteLine(" i       d")
        For i = 2 To maxIt
            Dim a = a1 + (a1 - a2) / d1
            For j = 1 To maxItJ
                Dim x = 0.0
                Dim y = 0.0
                For k = 1 To 1 << i
                    y = 1.0 - 2.0 * y * x
                    x = a - x * x
                Next
                a -= x / y
            Next
            Dim d = (a1 - a2) / (a - a1)
            Console.WriteLine("{0,2:d}    {1:f8}", i, d)
            d1 = d
            a2 = a1
            a1 = a
        Next
    End Sub

End Module


#include <stdio.h>

int main(int argc, char **argv) {
  FILE *in, *out;
  int c;

  in = fopen("input.txt", "r");
  if (!in) {
    fprintf(stderr, "Error opening input.txt for reading.\n");
    return 1;
  }

  out = fopen("output.txt", "w");
  if (!out) {
    fprintf(stderr, "Error opening output.txt for writing.\n");
    fclose(in);
    return 1;
  }

  while ((c = fgetc(in)) != EOF) {
    fputc(c, out);
  }

  fclose(out);
  fclose(in);
  return 0;
}


import "/fmt" for Fmt

var feigenbaum = Fn.new {
    var maxIt = 13
    var maxItJ = 10
    var a1 = 1
    var a2 = 0
    var d1 = 3.2
    System.print(" i       d")
    for (i in 2..maxIt) {
        var a = a1 + (a1 - a2)/d1
        for (j in 1..maxItJ) {
            var x = 0
            var y = 0
            for (k in 1..(1<<i)) {
                y = 1 - 2*y*x
                x = a - x*x
            }
            a = a - x/y
        }
        var d = (a1 - a2)/(a - a1)
        System.print("%(Fmt.d(2, i))    %(Fmt.f(0, d, 8))")
        d1 = d
        a2 = a1
        a1 = a
    }
}

feigenbaum.call()


using System.IO;

using (var reader = new StreamReader("input.txt"))
using (var writer = new StreamWriter("output.txt"))
{
    var text = reader.ReadToEnd();
    writer.Write(text);
}


#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    string line;
    ifstream input ( "input.txt" );
    ofstream output ("output.txt");

    if (output.is_open()) {
        if (input.is_open()){
            while (getline (input,line)) {
                output << line << endl;
            }
            input.close(); // Not necessary - will be closed when variable goes out of scope.
        }
        else {
            cout << "input.txt cannot be opened!\n";
        }
        output.close(); // Not necessary - will be closed when variable goes out of scope.
    }
    else {
        cout << "output.txt cannot be written to!\n";
    }
    return 0;
}


import StdEnv

copyFile fromPath toPath world
    # (ok, fromFile, world) = fopen fromPath FReadData world
    | not ok = abort ("Cannot open " +++ fromPath +++ " for reading")
    # (ok, toFile, world) = fopen toPath FWriteData world
    | not ok = abort ("Cannot open " +++ toPath +++ " for writing")
    # (fromFile, toFile) = copyData 1024 fromFile toFile
    # (ok, world) = fclose fromFile world
    | not ok = abort ("Cannot close " +++ fromPath +++ " after reading")
    # (ok, world) = fclose toFile world
    | not ok = abort ("Cannot close " +++ toPath +++ " after writing")
    = world
where
    copyData bufferSize fromFile toFile
        # (buffer, fromFile) = freads fromFile bufferSize
        # toFile = fwrites buffer toFile
        | size buffer < bufferSize = (fromFile, toFile) // we're done
        = copyData bufferSize fromFile toFile // continue recursively


(use 'clojure.java.io)

(copy (file "input.txt") (file "output.txt"))


$set ans85 flag"ans85" flagas"s" sequential"line"


<cfif fileExists(expandPath("input.txt"))>
  <cffile action="read" file="#expandPath('input.txt')#" variable="inputContents">
  <cffile action="write" file="#expandPath('output.txt')#" output="#inputContents#">
</cfif>


(with-open-file (in #p"input.txt" :direction :input)
  (with-open-file (out #p"output.txt" :direction :output)
    (loop for line = (read-line in nil 'foo)
          until (eq line 'foo)
          do (write-line line out))))


import std.file: copy;

void main() {
    copy("input.txt", "output.txt");
}


;
; File Input and output examples for DBL version 4 by Dario B.
;

RECORD CUSTOM

CUCOD,  D5      ;customer code
CUNAM,  A20     ;name
CUCIT,  A20     ;city
,       A55
;------- 100 bytes -------------

A80,    A80

                       PROC
;--------------------------------------------------------------

        XCALL FLAGS (0007000000,1)      ;suppress STOP message

        CLOSE 1
        OPEN (1,O,'TT:')                ;open video

        CLOSE 2
        OPEN (2,O,"CUSTOM.DDF")         ;create file in output

        ;Add new record
        CLEAR CUSTOM
        CUCOD=1
        CUNAM="Alan Turing"
        CUCIT="London"
        WRITES (2,CUSTOM)

        ;Add new record
        CLEAR CUSTOM
        CUCOD=2
        CUNAM="Galileo Galilei"
        CUCIT="Pisa"
        WRITES (2,CUSTOM)

        ;Modify a record
        CLOSE 2
        OPEN (2,U,"CUSTOM.DDF") [ERR=NOCUS]     ;open in update
        READ (2,CUSTOM,2)       [ERR=NOREC]
        CUCIT="Pisa - Italy"
        WRITE (2,CUSTOM,2)      [ERR=NOWRI]

        ;Add new record
        CLOSE 2
        OPEN (2,A,"CUSTOM.DDF") [ERR=NOCUS]     ;open in append

        CLEAR CUSTOM
        CUCOD=3
        CUNAM="Kenneth Lane Thompson"
        CUCIT="New Orleans"
        WRITES (2,CUSTOM)
        CLOSE 2

        ;Read file and display a video
        CLOSE 2
        OPEN (2,I,"CUSTOM.DDF")         [ERR=NOCUS]
        DO FOREVER
           BEGIN
                READS (2,CUSTOM,EOF)    [ERR=NOREC]
                DISPLAY (1,13,CUSTOM)
           END
EOF,    DISPLAY (1,10)
        CLOSE 2

        ;Write/read a text file
        CLOSE 3
        OPEN (3,O,"FILE.TXT")
        DISPLAY (3,"An Occurrence at Owl Creek Bridge",13,10)
        DISPLAY (3,"A man stood upon a railroad bridge in northern Alabama,",13,10)
        DISPLAY (3,"looking down into the swift water twenty feet below.",13,10)
        DISPLAY (3,"The man's hands were behind his back, the wrists bound ")
        DISPLAY (3,"with a cord.",13,10)
        CLOSE 3

        OPEN (3,I,"FILE.TXT")
        DO FOREVER
           BEGIN
                READS (3,A80,EOFF)
                DISPLAY (1,A80(1:%TRIM(A80)),10)
           END
EOFF,   CLOSE 3
        DISPLAY (1,10)

        GOTO QUIT

;---------------------------------------------------------------
NOCUS,  DISPLAY (1,10,"File CUSTUM.DDF Not found!",10)
        GOTO QUIT
NOREC,  DISPLAY (1,10,"Read error!",10)
        GOTO QUIT
NOWRI,  DISPLAY (1,10,"Write error!",10)
        GOTO QUIT

QUIT,   CLOSE 1
        STOP


$ open input input.txt
$ open /write output output.txt
$ loop:
$  read /end_of_file = done input line
$  write output line
$  goto loop
$ done:
$ close input
$ close output


- Read(F,V1..Vn)
- ReadLn(F,V1..Vn)
- Write(F,V1[,V2..Vn])
- WriteLn(f,V1[,V2..Vn])
- BlockRead(F,Buff,BytesToRead[,BytesRead])
- BlockWrite(F,Buff,BytesToRead[,BytesWritten])


       START   ;Simple File Input and Output

RECORD TEMP
       INLINE, A72

PROC
      OPEN (8,I,"input.txt")
      OPEN (9,O,"output.txt")

LOOP,
      READS(8,TEMP,END)
      WRITES(9,TEMP)
      GOTO LOOP

END,
     CLOSE 8
     CLOSE 9

     END


class
    APPLICATION

create
    make

feature {NONE} -- Initialization

    make
            -- Run application.
        do
            create input_file.make_open_read ("input.txt")
            create output_file.make_open_write ("output.txt")

            from
                input_file.read_character
            until
                input_file.exhausted
            loop
                output_file.put (input_file.last_character)
                input_file.read_character
            end

            input_file.close
            output_file.close
        end

feature -- Access

    input_file: PLAIN_TEXT_FILE
    output_file: PLAIN_TEXT_FILE

end


import system'io;

public program()
{
    var text := File.assign("input.txt").readContent();

    File.assign("output.txt").saveContent(text);
}


defmodule FileReadWrite do
  def copy(path,new_path) do
    case File.read(path) do
      # In case of success, write to the new file
      {:ok, body} ->
        # Can replace with :write! to generate an error upon failure
        File.write(new_path,body)
      # If not successful, raise an error
      {:error,reason} ->
        # Using Erlang's format_error to generate error string
        :file.format_error(reason)
    end
  end
end

FileReadWrite.copy("input.txt","output.txt")


(defvar input (with-temp-buffer
                (insert-file-contents "input.txt")
                (buffer-string)))

(with-temp-file "output.txt"
  (insert input))


-module( file_io ).

-export( [task/0] ).

task() ->
       {ok, Contents} = file:read_file( "input.txt" ),
       ok = file:write_file( "output.txt", Contents ).


include std/io.e
write_lines("output.txt", read_lines("input.txt"))


open System.IO

let copyFile fromTextFileName toTextFileName =
    let inputContent = File.ReadAllText fromTextFileName
    inputContent |> fun text -> File.WriteAllText(toTextFileName, text)

[<EntryPoint>]
let main argv =
    copyFile "input.txt" "output.txt"
    0


"input.txt" binary file-contents
"output.txt" binary set-file-contents


\ <to> <from> copy-file
: copy-file ( a1 n1 a2 n2 -- )
    r/o open-file throw >r
    w/o create-file throw r>
    begin
        pad maxstring  2 pick  read-file throw
    ?dup while
        pad swap  3 pick  write-file throw
    repeat
    close-file throw
    close-file throw ;

\ Invoke it like this:
s" output.txt" s" input.txt" copy-file


program FileIO

  integer, parameter :: out = 123, in = 124
  integer :: err
  character :: c

  open(out, file="output.txt", status="new", action="write", access="stream", iostat=err)
  if (err == 0) then
     open(in, file="input.txt", status="old", action="read", access="stream", iostat=err)
     if (err == 0) then
        err = 0
        do while (err == 0)
           read(unit=in, iostat=err) c
           if (err == 0) write(out) c
        end do
        close(in)
     end if
     close(out)
  end if

end program FileIO


' FB 1.05.0 Win64

/'
input.txt contains:

The quick brown fox jumps over the lazy dog.
Empty vessels make most noise.
Too many chefs spoil the broth.
A rolling stone gathers no moss.
'/

Open "output.txt" For Output As #1
Open "input.txt" For Input As #2
Dim line_ As String ' note that line is a keyword

While Not Eof(2)
  Line Input #2, line_
  Print #1, line_
Wend

Close #2
Close #1


contents = read["file:input.txt"]
w = new Writer["output.txt"]
w.print[contents]
w.close[]


Public Sub Main()
Dim sOutput As String = "Hello "
Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored

File.Save(User.Home &/ "output.txt", sOutput)
File.Save(User.Home &/ "input.txt", sOutput & sInput)

Print "'input.txt' contains - " & sOutput & sInput
Print "'output.txt' contains - " & sOutput

End


CopyFile := function(src, dst)
  local f, g, line;
  f := InputTextFile(src);
  g := OutputTextFile(dst, false);
  while true do
    line := ReadLine(f);
    if line = fail then
      break
    else
      WriteLine(g, Chomp(line));
    fi;
  od;
  CloseStream(f);
  CloseStream(g);
end;


var file, str;
file = file_text_open_read("input.txt");
str = "";
while (!file_text_eof(file))
    {
    str += file_text_read_string(file);
    if (!file_text_eof(file))
        {
        str += "
"; //It is important to note that a linebreak is actually inserted here rather than a character code of some kind
        file_text_readln(file);
        }
    }
file_text_close(file);

file = file_text_open_write("output.txt");
file_text_write_string(file,str);
file_text_close(file);


package main

import (
    "fmt"
    "io/ioutil"
)

func main() {
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        fmt.Println(err)
        return
    }
    if err = ioutil.WriteFile("output.txt", b, 0666); err != nil {
        fmt.Println(err)
    }
}


content = new File('input.txt').text
new File('output.txt').write(content)


Start,My Documents,Rightclick:input.txt,Copy,Menu,Edit,Paste,
Rightclick:Copy of input.txt,Rename,Type:output.txt[enter]


main = readFile "input.txt" >>= writeFile "output.txt"


let in  openin "input.txt"
let out openout "output.txt"
while !(catch (let c read char in))
  write c out
endwhile
close in; close out


CHARACTER input='input.txt ', output='output.txt ', c, buffer*4096
SYSTEM(COPY=input//output, ERror=11) ! on error branch to label 11 (not shown)


software {
	file = load("input.txt")
	open("output.txt").write(file)
}


procedure main()
in  := open(f := "input.txt","r") | stop("Unable to open ",f)
out := open(f := "output.txt","w") | stop("Unable to open ",f)
while write(out,read(in))
end


; open two LUNs
openw,unit1,'output.txt,/get
openr,unit2,'input.txt',/get
; how many bytes to read
fs = fstat(unit2)
; make buffer
buff = bytarr(fs.size)
; transfer content
readu,unit2,buff
writeu,unit1,buff
; that's all
close,/all


inf := File with("input.txt") openForReading
outf := File with("output.txt") openForUpdating

while(l := inf readLine,
  outf write(l, "\n")
)

inf close
outf close


import java.io.*;

public class FileIODemo {
  public static void main(String[] args) {
    try {
      FileInputStream in = new FileInputStream("input.txt");
      FileOutputStream out = new FileOutputStream("ouput.txt");
      int c;
      while ((c = in.read()) != -1) {
        out.write(c);
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e){
      e.printStackTrace();
    }
  }
}


var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2;
var f_in = fso.OpenTextFile('input.txt', ForReading);
var f_out = fso.OpenTextFile('output.txt', ForWriting, true);

// for small files:
// f_out.Write( f_in.ReadAll() );

while ( ! f_in.AtEndOfStream) {
    // ReadLine() does not include the newline char
    f_out.WriteLine( f_in.ReadLine() );
}

f_in.Close();
f_out.Close();


jq -M --raw-input --raw-output '. as $line | $line' input.txt > output.txt


mystring = read("file1", String)
open(io->write(io, mystring), "file2", "w")


// version 1.1.2

import java.io.File

fun main(args: Array<String>) {
    val text = File("input.txt").readText()
    File("output.txt").writeText(text)
}


: puts(*)  . "\n" . ;
: set-file  '> swap open ;
: >>contents  slurp puts ;
: copy-file
    swap set-file 'fdst set fdst fout >>contents fdst close ;

'output.txt 'input.txt copy-file


nomainwin

    open "input.txt" for input as #f1
        qtyBytes = lof( #f1)
        source$  = input$( #f1, qtyBytes)
    close #f1

    open "output.txt" for output as #f2
        #f2 source$;
    close #f2

    end


----------------------------------------
-- Returns file as ByteArray
-- @param {string} tFile
-- @return {byteArray|false}
----------------------------------------
on getBytes (tFile)
  fp = xtra("fileIO").new()
  fp.openFile(tFile, 1)
  if fp.status() then return false
  data = fp.readByteArray(fp.getLength())
  fp.closeFile()
  return data
end

----------------------------------------
-- Saves ByteArray to file
-- @param {string} tFile
-- @param {byteArray} tString
-- @return {bool} success
----------------------------------------
on putBytes (tFile, tByteArray)
  fp = xtra("fileIO").new()
  fp.openFile(tFile, 2)
  err = fp.status()
  if not (err) then fp.delete()
  else if (err and not (err = -37)) then return false
  fp.createFile(tFile)
  if fp.status() then return false
  fp.openFile(tFile, 2)
  if fp.status() then return false
  fp.writeByteArray(tByteArray)
  fp.closeFile()
  return true
end


Section Header

+ name := FILE_IO;

Section Public

- main <- (
  + e : ENTRY;
  + f : STD_FILE;
  + s : STRING;

  e := FILE_SYSTEM.get "input.txt";
  (e != NULL).if {
    f ?= e.open_read_only;
    (f != NULL).if {
      s := STRING.create(f.size);
      f.read s size (f.size);
      f.close;
    };
  };

  (s != NULL).if {
    e := FILE_SYSTEM.make_file "output.txt";
    (e != NULL).if {
      f ?= e.open;
      (f != NULL).if {
        f.write s from (s.lower) size (s.count);
        f.close;
      };
    };
  };
);


to copy :from :to
  openread :from
  openwrite :to
  setread :from
  setwrite :to
  until [eof?] [print readrawline]
  closeall
end

copy "input.txt "output.txt


inFile  = io.open("input.txt", "r")
data = inFile:read("*all") -- may be abbreviated to "*a";
                           -- other options are "*line",
                           -- or the number of characters to read.
inFile:close()

outFile = io.open("output.txt", "w")
outfile:write(data)
outfile:close()

-- Oneliner version:
io.open("output.txt", "w"):write(io.open("input.txt", "r"):read("*a"))


Module FileInputOutput {
      Edit "Input.txt"
      Document Doc$
      Load.Doc Doc$, "Input.txt"
      Report Doc$
      Print "Press a key:";Key$
      Save.Doc Doc$, "Output.txt"
      Edit "Output.txt"
}
FileInputOutput


inout:=proc(filename)
local f;
f:=FileTools[Text][ReadFile](filename);
FileTools[Text][WriteFile]("output.txt",f);
end proc;


[email protected][];
If[FileExistsQ["output.txt"], DeleteFile["output.txt"], Print["No output yet"] ];
CopyFile["input.txt", "output.txt"]


inFile = openFile "input.txt"
outFile = createFile "output.txt"
while not EOF inFile do
(
    format "%" (readLine inFile) to:outFile
)
close inFile
close outFile


:- module file_io.
:- interface.

:- import_module io.
:- pred main(io::di, io::uo) is det.

:- implementation.

main(!IO) :-
   io.open_input("input.txt", InputRes, !IO),
   (
       InputRes = ok(Input),
       io.read_file_as_string(Input, ReadRes, !IO),
       (
           ReadRes = ok(Contents),
           io.close_input(Input, !IO),
           io.open_output("output.txt", OutputRes, !IO),
           (
                OutputRes = ok(Output),
                io.write_string(Output, Contents, !IO),
                io.close_output(Output, !IO)
           ;
                OutputRes = error(OutputError),
                print_io_error(OutputError, !IO)
           )
       ;
           ReadRes = error(_, ReadError),
           print_io_error(ReadError, !IO)
       )
    ;
       InputRes = error(InputError),
       print_io_error(InputError, !IO)
    ).

:- pred print_io_error(io.error::in, io::di, io::uo) is det.

print_io_error(Error, !IO) :-
   io.stderr_stream(Stderr, !IO),
   io.write_string(Stderr, io.error_message(Error), !IO),
   io.set_exit_status(1, !IO).


alias Write2FileAndReadIt {
.write myfilename.txt Goodbye Mike!
.echo -a Myfilename.txt contains: $read(myfilename.txt,1)
}


MODULE FileIO EXPORTS Main;

IMPORT IO, Rd, Wr;

<*FATAL ANY*>

VAR
  infile: Rd.T;
  outfile: Wr.T;
  txt: TEXT;

BEGIN
  infile := IO.OpenRead("input.txt");
  outfile := IO.OpenWrite("output.txt");
  txt := Rd.GetText(infile, LAST(CARDINAL));
  Wr.PutText(outfile, txt);
  Rd.Close(infile);
  Wr.Close(outfile);
END FileIO.


import Nanoquery.IO

input = new(File, "input.txt")
output = new(File)

output.create("output.txt")
output.open("output.txt")

contents = input.readAll()
output.write(contents)


/* NetRexx */
options replace format comments java crossref symbols nobinary

import java.nio.

parse arg infileName outfileName .

if infileName  = '' | infileName.length  = 0 then infileName  = 'data/input.txt'
if outfileName = '' | outfileName.length = 0 then outfileName = 'data/output.txt'

binaryCopy(infileName, outfileName)

return

method binaryCopy(infileName, outfileName) public static

  do
    infile  = Paths.get('.', [String infileName])
    outfile = Paths.get('.', [String outfileName])
    fileOctets = Files.readAllBytes(infile)
    Files.write(outfile, fileOctets, [StandardOpenOption.WRITE, StandardOpenOption.CREATE])

  catch ioex = IOException
    ioex.printStackTrace()
  end

  return


import os
copyfile("input.txt", "output.txt")


use IO;

bundle Default {
  class Test {
    function : Main(args : String[]) ~ Nil {
      len := File->Size("input.txt");
      buffer := Byte->New[len];
      in := FileReader->New("input.txt");
      if(in->IsOpen() <> Nil) {
        in->ReadBuffer(0, len, buffer);
        out := FileWriter->New("output.txt");
        if(out->IsOpen() <> Nil) {
          out->WriteBuffer(0, len, buffer);
          out->Close();
        };
        in->Close();
      };
    }
  }
}


uses
  classes;
begin
  with TFileStream.Create('input.txt', fmOpenRead) do
  try
    SaveToFile('output.txt');
  finally
    Free;
  end;
end;


[[NSFileManager defaultManager] copyItemAtPath:@"input.txt" toPath:@"output.txt" error:NULL];


let () =
  let ic = open_in "input.txt" in
  let oc = open_out "output.txt" in
  try
    while true do
      let s = input_line ic in
      output_string oc s;
      output_char oc '\n';
    done
  with End_of_file ->
    close_in ic;
    close_out oc;
;;


in = fopen("input.txt", "r", "native");
out = fopen("output.txt", "w","native");
if (in == -1)
  disp("Error opening input.txt for reading.");
else
if (out == -1)
  disp("Error opening output.txt for writing.");
else
while (1)
  [val,count]=fread(in,1,"uchar",0,"native");
  if (count > 0)
    count=fwrite(out,val,"uchar",0,"native");
    if (count == 0)
      disp("Error writing to output.txt.");
    end
  else
    break;
  end
endwhile
end
end
if (in != -1)
  fclose(in);
end
if (out != -1)
  fclose(out);
end


: fcopy(in, out)
| f g |
   File newMode(in,  File.BINARY) dup open(File.READ) ->f
   File newMode(out, File.BINARY) dup open(File.WRITE) ->g

   while(f >> dup notNull) [ g addChar ] drop
   f close g close ;


COPY-LOB FROM FILE "input.txt" TO FILE "output.txt".


declare
  class TextFile from Open.file Open.text end

  In = {New TextFile init(name:"input.txt")}
  Out = {New TextFile init(name:"output.txt" flags:[write text create truncate])}

  proc {CopyAll In Out}
     case {In getS($)} of false then skip
     [] Line then
        {Out putS(Line)}
        {CopyAll In Out}
     end
  end
in
  {CopyAll In Out}
  {Out close}
  {In close}


nPowers: [1 2 4 8 16 32 64 128 256 512]
fermatSet: map 0..9 'x -> 1 + 2 ^ nPowers\[x]

loop 0..9 'i ->
    print ["F(" i ") =" fermatSet\[i]]

print ""

loop 0..9 'i ->
    print ["Prime factors of F(" i ") =" factors.prime fermatSet\[i]]


#!/usr/bin/perl

open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
open my $fh_out, '>', 'output.txt' or die "could not open <output.txt> for writing: $!";
# '>' overwrites file, '>>' appends to file, just like in the shell

binmode $fh_out; # marks filehandle for binary content on systems where that matters

print $fh_out $_ while <$fh_in>;
# prints current line to file associated with $fh_out filehandle

# the same, less concise
#while (<$fh_in>) {
#  print $fh_out $_;
#};

close $fh_in;
close $fh_out;


#include <iostream>
#include <vector>
#include <boost/integer/common_factor.hpp>
#include <boost/multiprecision/cpp_int.hpp>
#include <boost/multiprecision/miller_rabin.hpp>

typedef boost::multiprecision::cpp_int integer;

integer fermat(unsigned int n) {
    unsigned int p = 1;
    for (unsigned int i = 0; i < n; ++i)
        p *= 2;
    return 1 + pow(integer(2), p);
}

inline void g(integer& x, const integer& n) {
    x *= x;
    x += 1;
    x %= n;
}

integer pollard_rho(const integer& n) {
    integer x = 2, y = 2, d = 1, z = 1;
    int count = 0;
    for (;;) {
        g(x, n);
        g(y, n);
        g(y, n);
        d = abs(x - y);
        z = (z * d) % n;
        ++count;
        if (count == 100) {
            d = gcd(z, n);
            if (d != 1)
                break;
            z = 1;
            count = 0;
        }
    }
    if (d == n)
        return 0;
    return d;
}

std::vector<integer> get_prime_factors(integer n) {
    std::vector<integer> factors;
    for (;;) {
        if (miller_rabin_test(n, 25)) {
            factors.push_back(n);
            break;
        }
        integer f = pollard_rho(n);
        if (f == 0) {
            factors.push_back(n);
            break;
        }
        factors.push_back(f);
        n /= f;
    }
    return factors;
}

void print_vector(const std::vector<integer>& factors) {
    if (factors.empty())
        return;
    auto i = factors.begin();
    std::cout << *i++;
    for (; i != factors.end(); ++i)
        std::cout << ", " << *i;
    std::cout << '\n';
}

int main() {
    std::cout << "First 10 Fermat numbers:\n";
    for (unsigned int i = 0; i < 10; ++i)
        std::cout << "F(" << i << ") = " << fermat(i) << '\n';
    std::cout << "\nPrime factors:\n";
    for (unsigned int i = 0; i < 9; ++i) {
        std::cout << "F(" << i << "): ";
        print_vector(get_prime_factors(fermat(i)));
    }
    return 0;
}


integer fn = open("input.txt","rb")
string txt = get_text(fn)
    close(fn)
    fn = open("output.txt","wb")
    puts(fn,txt)
    close(fn)


<?php

if (!$in = fopen('input.txt', 'r')) {
    die('Could not open input file.');
}

if (!$out = fopen('output.txt', 'w')) {
    die('Could not open output file.');
}

while (!feof($in)) {
    $data = fread($in, 512);
    fwrite($out, $data);
}

fclose($out);
fclose($in);
?>


This uses the 'factor' function defined in the page Prime Decomposition
http://rosettacode.org/wiki/Prime_decomposition#Common_Lisp


This uses the `factor` function from the `coreutils` library
that comes standard with most GNU/Linux, BSD, and Unix systems.
https://www.gnu.org/software/coreutils/
https://en.wikipedia.org/wiki/GNU_Core_Utilities


USING: formatting io kernel lists lists.lazy math math.functions
math.primes.factors sequences ;

: lfermats ( -- list )
    0 lfrom [ [ 1 2 2 ] dip ^ ^ + ] lmap-lazy ;

CHAR: ₀ 10 lfermats ltake list>array [
    "First 10 Fermat numbers:" print
    [ dupd "F%c = %d\n" printf 1 + ] each drop nl
] [
    "Factors of first few Fermat numbers:" print [
        dupd factors dup length 1 = " (prime)" "" ?
        "Factors of F%c: %[%d, %]%s\n" printf 1 +
    ] each drop
] 2bi


package main

import (
    "fmt"
    "github.com/jbarham/primegen"
    "math"
    "math/big"
    "math/rand"
    "sort"
    "time"
)

const (
    maxCurves = 10000
    maxRnd    = 1 << 31
    maxB1     = uint64(43 * 1e7)
    maxB2     = uint64(2 * 1e10)
)

var (
    zero  = big.NewInt(0)
    one   = big.NewInt(1)
    two   = big.NewInt(2)
    three = big.NewInt(3)
    four  = big.NewInt(4)
    five  = big.NewInt(5)
)

// Uses algorithm in Wikipedia article, including speed-up.
func pollardRho(n *big.Int) (*big.Int, error) {
    // g(x) = (x^2 + 1) mod n
    g := func(x, n *big.Int) *big.Int {
        x2 := new(big.Int)
        x2.Mul(x, x)
        x2.Add(x2, one)
        return x2.Mod(x2, n)
    }
    x, y, d := new(big.Int).Set(two), new(big.Int).Set(two), new(big.Int).Set(one)
    t, z := new(big.Int), new(big.Int).Set(one)
    count := 0
    for {
        x = g(x, n)
        y = g(g(y, n), n)
        t.Sub(x, y)
        t.Abs(t)
        t.Mod(t, n)
        z.Mul(z, t)
        count++
        if count == 100 {
            d.GCD(nil, nil, z, n)
            if d.Cmp(one) != 0 {
                break
            }
            z.Set(one)
            count = 0
        }
    }
    if d.Cmp(n) == 0 {
        return nil, fmt.Errorf("Pollard's rho failure")
    }
    return d, nil
}

// Gets all primes under 'n' - uses a Sieve of Atkin under the hood.
func getPrimes(n uint64) []uint64 {
    pg := primegen.New()
    var primes []uint64
    for {
        prime := pg.Next()
        if prime < n {
            primes = append(primes, prime)
        } else {
            break
        }
    }
    return primes
}

// Computes Stage 1 and Stage 2 bounds.
func computeBounds(n *big.Int) (uint64, uint64) {
    le := len(n.String())
    var b1, b2 uint64
    switch {
    case le <= 30:
        b1, b2 = 2000, 147396
    case le <= 40:
        b1, b2 = 11000, 1873422
    case le <= 50:
        b1, b2 = 50000, 12746592
    case le <= 60:
        b1, b2 = 250000, 128992510
    case le <= 70:
        b1, b2 = 1000000, 1045563762
    case le <= 80:
        b1, b2 = 3000000, 5706890290
    default:
        b1, b2 = maxB1, maxB2
    }
    return b1, b2
}

// Adds two specified P and Q points (in Montgomery form). Assumes R = P - Q.
func pointAdd(px, pz, qx, qz, rx, rz, n *big.Int) (*big.Int, *big.Int) {
    t := new(big.Int).Sub(px, pz)
    u := new(big.Int).Add(qx, qz)
    u.Mul(t, u)
    t.Add(px, pz)
    v := new(big.Int).Sub(qx, qz)
    v.Mul(t, v)
    upv := new(big.Int).Add(u, v)
    umv := new(big.Int).Sub(u, v)
    x := new(big.Int).Mul(upv, upv)
    x.Mul(x, rz)
    if x.Cmp(n) >= 0 {
        x.Mod(x, n)
    }
    z := new(big.Int).Mul(umv, umv)
    z.Mul(z, rx)
    if z.Cmp(n) >= 0 {
        z.Mod(z, n)
    }
    return x, z
}

// Doubles a point P (in Montgomery form).
func pointDouble(px, pz, n, a24 *big.Int) (*big.Int, *big.Int) {
    u2 := new(big.Int).Add(px, pz)
    u2.Mul(u2, u2)
    v2 := new(big.Int).Sub(px, pz)
    v2.Mul(v2, v2)
    t := new(big.Int).Sub(u2, v2)
    x := new(big.Int).Mul(u2, v2)
    if x.Cmp(n) >= 0 {
        x.Mod(x, n)
    }
    z := new(big.Int).Mul(a24, t)
    z.Add(v2, z)
    z.Mul(t, z)
    if z.Cmp(n) >= 0 {
        z.Mod(z, n)
    }
    return x, z
}

// Multiplies a specified point P (in Montgomery form) by a specified scalar.
func scalarMultiply(k, px, pz, n, a24 *big.Int) (*big.Int, *big.Int) {
    sk := fmt.Sprintf("%b", k)
    lk := len(sk)
    qx := new(big.Int).Set(px)
    qz := new(big.Int).Set(pz)
    rx, rz := pointDouble(px, pz, n, a24)
    for i := 1; i < lk; i++ {
        if sk[i] == '1' {
            qx, qz = pointAdd(rx, rz, qx, qz, px, pz, n)
            rx, rz = pointDouble(rx, rz, n, a24)

        } else {
            rx, rz = pointAdd(qx, qz, rx, rz, px, pz, n)
            qx, qz = pointDouble(qx, qz, n, a24)
        }
    }
    return qx, qz
}

// Lenstra's two-stage ECM algorithm.
func ecm(n *big.Int) (*big.Int, error) {
    if n.Cmp(one) == 0 || n.ProbablyPrime(10) {
        return n, nil
    }
    b1, b2 := computeBounds(n)
    dd := uint64(math.Sqrt(float64(b2)))
    beta := make([]*big.Int, dd+1)
    for i := 0; i < len(beta); i++ {
        beta[i] = new(big.Int)
    }
    s := make([]*big.Int, 2*dd+2)
    for i := 0; i < len(s); i++ {
        s[i] = new(big.Int)
    }

    // stage 1 and stage 2 precomputations
    curves := 0
    logB1 := math.Log(float64(b1))
    primes := getPrimes(b2)
    numPrimes := len(primes)
    idxB1 := sort.Search(len(primes), func(i int) bool { return primes[i] >= b1 })

    // compute a B1-powersmooth integer 'k'
    k := big.NewInt(1)
    for i := 0; i < idxB1; i++ {
        p := primes[i]
        bp := new(big.Int).SetUint64(p)
        t := uint64(logB1 / math.Log(float64(p)))
        bt := new(big.Int).SetUint64(t)
        bt.Exp(bp, bt, nil)
        k.Mul(k, bt)
    }
    g := big.NewInt(1)
    for (g.Cmp(one) == 0 || g.Cmp(n) == 0) && curves <= maxCurves {
        curves++
        st := int64(6 + rand.Intn(maxRnd-5))
        sigma := big.NewInt(st)

        // generate a new random curve in Montgomery form with Suyama's parameterization
        u := new(big.Int).Mul(sigma, sigma)
        u.Sub(u, five)
        u.Mod(u, n)
        v := new(big.Int).Mul(four, sigma)
        v.Mod(v, n)
        vmu := new(big.Int).Sub(v, u)
        a := new(big.Int).Mul(vmu, vmu)
        a.Mul(a, vmu)
        t := new(big.Int).Mul(three, u)
        t.Add(t, v)
        a.Mul(a, t)
        t.Mul(four, u)
        t.Mul(t, u)
        t.Mul(t, u)
        t.Mul(t, v)
        a.Quo(a, t)
        a.Sub(a, two)
        a.Mod(a, n)
        a24 := new(big.Int).Add(a, two)
        a24.Quo(a24, four)

        // stage 1
        px := new(big.Int).Mul(u, u)
        px.Mul(px, u)
        t.Mul(v, v)
        t.Mul(t, v)
        px.Quo(px, t)
        px.Mod(px, n)
        pz := big.NewInt(1)
        qx, qz := scalarMultiply(k, px, pz, n, a24)
        g.GCD(nil, nil, n, qz)

        // if stage 1 is successful, return a non-trivial factor else
        // move on to stage 2
        if g.Cmp(one) != 0 && g.Cmp(n) != 0 {
            return g, nil
        }

        // stage 2
        s[1], s[2] = pointDouble(qx, qz, n, a24)
        s[3], s[4] = pointDouble(s[1], s[2], n, a24)
        beta[1].Mul(s[1], s[2])
        beta[1].Mod(beta[1], n)
        beta[2].Mul(s[3], s[4])
        beta[2].Mod(beta[2], n)
        for d := uint64(3); d <= dd; d++ {
            d2 := 2 * d
            s[d2-1], s[d2] = pointAdd(s[d2-3], s[d2-2], s[1], s[2], s[d2-5], s[d2-4], n)
            beta[d].Mul(s[d2-1], s[d2])
            beta[d].Mod(beta[d], n)
        }
        g.SetUint64(1)
        b := new(big.Int).SetUint64(b1 - 1)
        rx, rz := scalarMultiply(b, qx, qz, n, a24)
        t.Mul(two, new(big.Int).SetUint64(dd))
        t.Sub(b, t)
        tx, tz := scalarMultiply(t, qx, qz, n, a24)
        q, step := idxB1, 2*dd
        for r := b1 - 1; r < b2; r += step {
            alpha := new(big.Int).Mul(rx, rz)
            alpha.Mod(alpha, n)
            limit := r + step
            for q < numPrimes && primes[q] <= limit {
                d := (primes[q] - r) / 2
                t := new(big.Int).Sub(rx, s[2*d-1])
                f := new(big.Int).Add(rz, s[2*d])
                f.Mul(t, f)
                f.Sub(f, alpha)
                f.Add(f, beta[d])
                g.Mul(g, f)
                g.Mod(g, n)
                q++
            }
            trx := new(big.Int).Set(rx)
            trz := new(big.Int).Set(rz)
            rx, rz = pointAdd(rx, rz, s[2*dd-1], s[2*dd], tx, tz, n)
            tx.Set(trx)
            tz.Set(trz)
        }
        g.GCD(nil, nil, n, g)
    }

    // no non-trivial factor found, return an error
    if curves > maxCurves {
        return zero, fmt.Errorf("maximum curves exceeded before a factor was found")
    }
    return g, nil
}

// find prime factors of 'n' using an appropriate method.
func primeFactors(n *big.Int) ([]*big.Int, error) {
    var res []*big.Int
    if n.ProbablyPrime(10) {
        return append(res, n), nil
    }
    le := len(n.String())
    var factor1 *big.Int
    var err error
    if le > 20 && le <= 60 {
        factor1, err = ecm(n)
    } else {
        factor1, err = pollardRho(n)
    }
    if err != nil {
        return nil, err
    }
    if !factor1.ProbablyPrime(10) {
        return nil, fmt.Errorf("first factor is not prime")
    }
    factor2 := new(big.Int)
    factor2.Quo(n, factor1)
    if !factor2.ProbablyPrime(10) {
        return nil, fmt.Errorf("%d (second factor is not prime)", factor1)
    }
    return append(res, factor1, factor2), nil
}

func fermatNumbers(n int) (res []*big.Int) {
    f := new(big.Int).SetUint64(3) // 2^1 + 1
    for i := 0; i < n; i++ {
        t := new(big.Int).Set(f)
        res = append(res, t)
        f.Sub(f, one)
        f.Mul(f, f)
        f.Add(f, one)
    }
    return res
}

func main() {
    start := time.Now()
    rand.Seed(time.Now().UnixNano())
    fns := fermatNumbers(10)
    fmt.Println("First 10 Fermat numbers:")
    for i, f := range fns {
        fmt.Printf("F%c = %d\n", 0x2080+i, f)
    }

    fmt.Println("\nFactors of first 10 Fermat numbers:")
    for i, f := range fns {
        fmt.Printf("F%c = ", 0x2080+i)
        factors, err := primeFactors(f)
        if err != nil {
            fmt.Println(err)
            continue
        }
        for _, factor := range factors {
            fmt.Printf("%d ", factor)
        }
        if len(factors) == 1 {
            fmt.Println("- prime")
        } else {
            fmt.Println()
        }
    }
    fmt.Printf("\nTook %s\n", time.Since(start))
}


(let V (in "input.txt" (till))
   (out "output.txt" (prin V)) )


object lines = Stdio.File("input.txt")->line_iterator();
object out = Stdio.File("output.txt", "cw");
foreach(lines; int line_number; string line)
    out->write(line + "\n");


declare in file, out file;

open file (in) title ('/INPUT.TXT,type(text),recsize(100)') input;
open file (out) title ('/OUTPUT.TXT,type(text),recsize(100') output;
do forever;
   get file (in)  edit (line) (L);
   put file (out) edit (line) (A);
end;


import Data.Numbers.Primes (primeFactors)
import Data.Bool (bool)

fermat :: Integer -> Integer
fermat = succ . (2 ^) . (2 ^)

fermats :: [Integer]
fermats = fermat <$> [0 ..]

--------------------------- TEST ---------------------------
main :: IO ()
main =
  mapM_
    putStrLn
    [ fTable "First 10 Fermats:" show show fermat [0 .. 9]
    , fTable
        "Factors of first 7:"
        show
        showFactors
        primeFactors
        (take 7 fermats)
    ]

------------------------- DISPLAY --------------------------
fTable :: String -> (a -> String) -> (b -> String) -> (a -> b) -> [a] -> String
fTable s xShow fxShow f xs =
  unlines $
  s : fmap (((++) . rjust w ' ' . xShow) <*> ((" -> " ++) . fxShow . f)) xs
  where
    rjust n c = drop . length <*> (replicate n c ++)
    w = maximum (length . xShow <$> xs)

showFactors :: [Integer] -> String
showFactors x
  | 1 < length x = show x
  | otherwise = "(prime)"


lvars i_stream = discin('input.txt');
lvars o_stream = discout('output.txt');
lvars c;
while (i_stream() ->> c) /= termin do
    o_stream(c);
endwhile;


Get-Content $PWD\input.txt | Out-File $PWD\output.txt


import shutil
shutil.copyfile('input.txt', 'output.txt')


import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class FermatNumbers {

    public static void main(String[] args) {
        System.out.println("First 10 Fermat numbers:");
        for ( int i = 0 ; i < 10 ; i++ ) {
            System.out.printf("F[%d] = %s\n", i, fermat(i));
        }
        System.out.printf("%nFirst 12 Fermat numbers factored:%n");
        for ( int i = 0 ; i < 13 ; i++ ) {
            System.out.printf("F[%d] = %s\n", i, getString(getFactors(i, fermat(i))));
        }
    }

    private static String getString(List<BigInteger> factors) {
        if ( factors.size() == 1 ) {
            return factors.get(0) + " (PRIME)";
        }
        return factors.stream().map(v -> v.toString()).map(v -> v.startsWith("-") ? "(C" + v.replace("-", "") + ")" : v).collect(Collectors.joining(" * "));
    }

    private static Map<Integer, String> COMPOSITE = new HashMap<>();
    static {
        COMPOSITE.put(9, "5529");
        COMPOSITE.put(10, "6078");
        COMPOSITE.put(11, "1037");
        COMPOSITE.put(12, "5488");
        COMPOSITE.put(13, "2884");
    }

    private static List<BigInteger> getFactors(int fermatIndex, BigInteger n) {
        List<BigInteger> factors = new ArrayList<>();
        BigInteger factor = BigInteger.ONE;
        while ( true ) {
            if ( n.isProbablePrime(100) ) {
                factors.add(n);
                break;
            }
            else {
                if ( COMPOSITE.containsKey(fermatIndex) ) {
                    String stop = COMPOSITE.get(fermatIndex);
                    if ( n.toString().startsWith(stop) ) {
                        factors.add(new BigInteger("-" + n.toString().length()));
                        break;
                    }
                }
                factor = pollardRhoFast(n);
                if ( factor.compareTo(BigInteger.ZERO) == 0 ) {
                    factors.add(n);
                    break;
                }
                else {
                    factors.add(factor);
                    n = n.divide(factor);
                }
            }
        }
        return factors;
    }

    private static final BigInteger TWO = BigInteger.valueOf(2);

    private static BigInteger fermat(int n) {
        return TWO.pow((int)Math.pow(2, n)).add(BigInteger.ONE);
    }

    //  See:  https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
    @SuppressWarnings("unused")
    private static BigInteger pollardRho(BigInteger n) {
        BigInteger x = BigInteger.valueOf(2);
        BigInteger y = BigInteger.valueOf(2);
        BigInteger d = BigInteger.ONE;
        while ( d.compareTo(BigInteger.ONE) == 0 ) {
            x = pollardRhoG(x, n);
            y = pollardRhoG(pollardRhoG(y, n), n);
            d = x.subtract(y).abs().gcd(n);
        }
        if ( d.compareTo(n) == 0 ) {
            return BigInteger.ZERO;
        }
        return d;
    }

    //  Includes Speed Up of 100 multiples and 1 GCD, instead of 100 multiples and 100 GCDs.
    //  See Variants section of Wikipedia article.
    //  Testing F[8] = 1238926361552897 * Prime
    //    This variant = 32 sec.
    //    Standard algorithm = 107 sec.
    private static BigInteger pollardRhoFast(BigInteger n) {
        long start = System.currentTimeMillis();
        BigInteger x = BigInteger.valueOf(2);
        BigInteger y = BigInteger.valueOf(2);
        BigInteger d = BigInteger.ONE;
        int count = 0;
        BigInteger z = BigInteger.ONE;
        while ( true ) {
            x = pollardRhoG(x, n);
            y = pollardRhoG(pollardRhoG(y, n), n);
            d = x.subtract(y).abs();
            z = z.multiply(d).mod(n);
            count++;
            if ( count == 100 ) {
                d = z.gcd(n);
                if ( d.compareTo(BigInteger.ONE) != 0 ) {
                    break;
                }
                z = BigInteger.ONE;
                count = 0;
            }
        }
        long end = System.currentTimeMillis();
        System.out.printf("    Pollard rho try factor %s elapsed time = %d ms (factor = %s).%n", n, (end-start), d);
        if ( d.compareTo(n) == 0 ) {
            return BigInteger.ZERO;
        }
        return d;
    }

    private static BigInteger pollardRhoG(BigInteger x, BigInteger n) {
        return x.multiply(x).add(BigInteger.ONE).mod(n);
    }

}


  $ "input.txt" sharefile drop
  temp put
  temp share
  $ "output.txt" putfile drop


src <- file("input.txt", "r")
dest <- file("output.txt", "w")

fc <- readLines(src, -1)
writeLines(fc, dest)
close(src); close(dest)


#lang racket
(define file-content
  (with-input-from-file "input.txt"
    (lambda ()
      (let loop ((lst null))
        (define new (read-char))
        (if (eof-object? new)
            (apply string lst)
            (loop (append lst (list new))))))))

(with-output-to-file "output.txt"
  (lambda ()
    (write file-content)))


# To take advantage of gojq's arbitrary-precision integer arithmetic:
def power($b): . as $in | reduce range(0;$b) as $i (1; . * $in);

def gcd(a; b):
  # subfunction expects [a,b] as input
  # i.e. a ~ .[0] and b ~ .[1]
  def rgcd: if .[1] == 0 then .[0]
         else [.[1], .[0] % .[1]] | rgcd
         end;
  [a,b] | rgcd;

# This is fast because the state of `until` is just a number
def is_prime:
  . as $n
  | if ($n < 2)         then false
    elif ($n % 2 == 0)  then $n == 2
    elif ($n % 3 == 0)  then $n == 3
    elif ($n % 5 == 0)  then $n == 5
    elif ($n % 7 == 0)  then $n == 7
    elif ($n % 11 == 0) then $n == 11
    elif ($n % 13 == 0) then $n == 13
    elif ($n % 17 == 0) then $n == 17
    elif ($n % 19 == 0) then $n == 19
    elif ($n % 23 == 0) then $n == 23
    elif ($n % 29 == 0) then $n == 29
    elif ($n % 31 == 0) then $n == 31
    elif ($n % 37 == 0) then $n == 37
    elif ($n % 41 == 0) then $n == 41
    else 43
    | until( (. * .) > $n or ($n % . == 0); . + 2)
    | . * . > $n
    end;


using Primes

fermat(n) = BigInt(2)^(BigInt(2)^n) + 1
prettyprint(fdict) = replace(replace(string(fdict), r".+\(([^)]+)\)" => s"\1"), r"\=\>" => "^")

function factorfermats(max, nofactor=false)
    for n in 0:max
        fm = fermat(n)
        if nofactor
            println("Fermat number F($n) is $fm.")
            continue
        end
        factors = factor(fm)
        println("Fermat number F($n), $fm, ",
            length(factors) < 2 ? "is prime." : "factors to $(prettyprint(factors)).")
    end
end

factorfermats(9, true)
factorfermats(10)


import java.math.BigInteger
import kotlin.math.pow

fun main() {
    println("First 10 Fermat numbers:")
    for (i in 0..9) {
        println("F[$i] = ${fermat(i)}")
    }
    println()
    println("First 12 Fermat numbers factored:")
    for (i in 0..12) {
        println("F[$i] = ${getString(getFactors(i, fermat(i)))}")
    }
}

private fun getString(factors: List<BigInteger>): String {
    return if (factors.size == 1) {
        "${factors[0]} (PRIME)"
    } else factors.map { it.toString() }
        .joinToString(" * ") {
            if (it.startsWith("-"))
                "(C" + it.replace("-", "") + ")"
            else it
        }
}

private val COMPOSITE = mutableMapOf(
    9 to "5529",
    10 to "6078",
    11 to "1037",
    12 to "5488",
    13 to "2884"
)

private fun getFactors(fermatIndex: Int, n: BigInteger): List<BigInteger> {
    var n2 = n
    val factors: MutableList<BigInteger> = ArrayList()
    var factor: BigInteger
    while (true) {
        if (n2.isProbablePrime(100)) {
            factors.add(n2)
            break
        } else {
            if (COMPOSITE.containsKey(fermatIndex)) {
                val stop = COMPOSITE[fermatIndex]
                if (n2.toString().startsWith(stop!!)) {
                    factors.add(BigInteger("-" + n2.toString().length))
                    break
                }
            }
            //factor = pollardRho(n)
            factor = pollardRhoFast(n)
            n2 = if (factor.compareTo(BigInteger.ZERO) == 0) {
                factors.add(n2)
                break
            } else {
                factors.add(factor)
                n2.divide(factor)
            }
        }
    }
    return factors
}

private val TWO = BigInteger.valueOf(2)
private fun fermat(n: Int): BigInteger {
    return TWO.pow(2.0.pow(n.toDouble()).toInt()).add(BigInteger.ONE)
}

//  See:  https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm
@Suppress("unused")
private fun pollardRho(n: BigInteger): BigInteger {
    var x = BigInteger.valueOf(2)
    var y = BigInteger.valueOf(2)
    var d = BigInteger.ONE
    while (d.compareTo(BigInteger.ONE) == 0) {
        x = pollardRhoG(x, n)
        y = pollardRhoG(pollardRhoG(y, n), n)
        d = (x - y).abs().gcd(n)
    }
    return if (d.compareTo(n) == 0) {
        BigInteger.ZERO
    } else d
}

//  Includes Speed Up of 100 multiples and 1 GCD, instead of 100 multiples and 100 GCDs.
//  See Variants section of Wikipedia article.
//  Testing F[8] = 1238926361552897 * Prime
//    This variant = 32 sec.
//    Standard algorithm = 107 sec.
private fun pollardRhoFast(n: BigInteger): BigInteger {
    val start = System.currentTimeMillis()
    var x = BigInteger.valueOf(2)
    var y = BigInteger.valueOf(2)
    var d: BigInteger
    var count = 0
    var z = BigInteger.ONE
    while (true) {
        x = pollardRhoG(x, n)
        y = pollardRhoG(pollardRhoG(y, n), n)
        d = (x - y).abs()
        z = (z * d).mod(n)
        count++
        if (count == 100) {
            d = z.gcd(n)
            if (d.compareTo(BigInteger.ONE) != 0) {
                break
            }
            z = BigInteger.ONE
            count = 0
        }
    }
    val end = System.currentTimeMillis()
    println("    Pollard rho try factor $n elapsed time = ${end - start} ms (factor = $d).")
    return if (d.compareTo(n) == 0) {
        BigInteger.ZERO
    } else d
}

private fun pollardRhoG(x: BigInteger, n: BigInteger): BigInteger {
    return (x * x + BigInteger.ONE).mod(n)
}


$INCLUDE "rapidq.inc"

DIM File1 AS QFileStream
DIM File2 AS QFileStream

File1.Open("input.txt", fmOpenRead)
File2.Open("output.txt", fmCreate)

WHILE NOT File1.EOF
    data$ = File1.ReadLine
    File2.WriteLine(data$)
WEND

File1.Close
File2.Close


Sub WriteToFile(input As FolderItem, output As FolderItem)
  Dim tis As TextInputStream
  Dim tos As TextOutputStream
  tis = tis.Open(input)
  tos = tos.Create(output)
  While Not tis.EOF
    tos.WriteLine(tis.ReadLine)
  Wend
  tis.Close
  tos.Close
End Sub


val .fermat = f 2 ^ 2 ^ .n + 1

val .factors = f(var .x) {
    for[.f=[]] .i, .s = 2, truncate .x ^/ 2; .i < .s; .i += 1 {
        if .x div .i {
            .f ~= [.i]
            .x \= .i
            .s = truncate .x ^/ 2
        }
    } ~ [.x]
}

writeln "first 10 Fermat numbers"
for .i in 0..9 {
    writeln $"F\(.i + 16x2080:cp) = \(.fermat(.i))"
}
writeln()

writeln "factors of first few Fermat numbers"
for .i in 0..9 {
    val .ferm = .fermat(.i)
    val .fac = .factors(.ferm)
    if len(.fac) == 1 {
        writeln $"F\(.i + 16x2080:cp) is prime"
    } else {
        writeln $"F\(.i + 16x2080:cp) factors: ", .fac
    }
}


ClearAll[Fermat]
Fermat[n_] := 2^(2^n) + 1
Fermat /@ Range[0, 9]
Scan[FactorInteger /* Print, %]


import math
import bignum
import strformat
import strutils
import tables
import times

const Composite = {9: "5529", 10: "6078", 11: "1037", 12: "5488", 13: "2884"}.toTable

const Subscripts = ["₀", "₁", "₂", "₃", "₄", "₅", "₆", "₇", "₈", "₉"]

let One = newInt(1)

#---------------------------------------------------------------------------------------------------

func fermat(n: int): Int {.inline.} = 2^(culong(2^n)) + 1

#---------------------------------------------------------------------------------------------------

template isProbablyPrime(n: Int): bool = n.probablyPrime(25) != 0

#---------------------------------------------------------------------------------------------------

func pollardRhoG(x, n: Int): Int {.inline.} = (x * x + 1) mod n

#---------------------------------------------------------------------------------------------------

proc pollardRhoFast(n: Int): Int =

  let start = getTime()
  var
    x = newInt(2)
    y = newInt(2)
    count = 0
    z = One

  while true:
    x = pollardRhoG(x, n)
    y = pollardRhoG(pollardRhoG(y, n), n)
    result = abs(x - y)
    z = z * result mod n
    inc count
    if count == 100:
      result = gcd(z, n)
      if result != One: break
      z = One
      count = 0

  let duration = (getTime() - start).inMilliseconds
  echo fmt"    Pollard rho try factor {n} elapsed time = {duration} ms (factor = {result})."
  if result == n:
    result = newInt(0)

#---------------------------------------------------------------------------------------------------

proc factors(fermatIndex: int; n: Int): seq[Int] =

  var n = n
  var factor: Int
  while true:

    if n.isProbablyPrime():
      result.add(n)
      break

    if fermatIndex in Composite:
      let stop = Composite[fermatIndex]
      let s = $n
      if s.startsWith(stop):
        result.add(newInt(-s.len))
        break

    factor = pollardRhoFast(n)
    if factor.isZero():
      result.add(n)
      break
    result.add(factor)
    n = n div factor

#---------------------------------------------------------------------------------------------------

func `$`(factors: seq[Int]): string =

  if factors.len == 1:
    result = fmt"{factors[0]} (PRIME)"

  else:
    result = $factors[0]
    let start = result.high
    for factor in factors[1..^1]:
      result.addSep(" * ", start)
      result.add(if factor < 0: fmt"(C{-factor})" else: $factor)

#---------------------------------------------------------------------------------------------------

func subscript(n: Natural): string =
  var n = n
  while true:
    result.insert(Subscripts[n mod 10], 0)
    n = n div 10
    if n == 0: break

#———————————————————————————————————————————————————————————————————————————————————————————————————

echo "First 10 Fermat numbers:"
for i in 0..9:
  echo fmt"F{subscript(i)} = {fermat(i)}"

echo ""
echo "First 12 Fermat numbers factored:"
for i in 0..12:
  echo fmt"F{subscript(i)} = {factors(i, fermat(i))}"


use strict;
use warnings;
use feature 'say';
use bigint try=>"GMP";
use ntheory qw<factor>;

my @Fermats = map { 2**(2**$_) + 1 } 0..9;

my $sub = 0;
say 'First 10 Fermat numbers:';
printf "F%s = %s\n", $sub++, $_ for @Fermats;

$sub = 0;
say "\nFactors of first few Fermat numbers:";
for my $f (map { [factor($_)] } @Fermats[0..8]) {
   printf "Factors of F%s: %s\n", $sub++, @$f == 1 ? 'prime' : join ' ', @$f
}


write %output.txt read %input.txt

; No line translations:
write/binary %output.txt read/binary %input.txt

; Save a web page:
write/binary %output.html read http://rosettacode.org


file: read %input.txt
write %output.txt file


with files'
here dup "input.txt" slurp "output.txt" spew


/*REXX program reads a file and copies the contents into an output file  (on a line by line basis).*/
iFID =  'input.txt'                              /*the name of the   input  file.       */
oFID = 'output.txt'                              /* "    "   "  "   output    "         */
call lineout iFID,,1                             /*insure the  input starts at line one.*/      /* ◄■■■■■■ optional.*/
call lineout oFID,,1                             /*   "    "  output    "    "   "   "  */      /* ◄■■■■■■ optional.*/

  do  while lines(iFID)\==0;    $=linein(iFID)   /*read records from input 'til finished*/
             call lineout oFID, $                /*write the record just read ──► output*/
  end   /*while*/                                /*stick a fork in it,  we're all done. */

call lineout iFID                                /*close   input  file, just to be safe.*/      /* ◄■■■■■■ best programming practice.*/
call lineout oFID                                /*  "    output    "     "   "  "   "  */      /* ◄■■■■■■ best programming practice.*/


with javascript_semantics
-- demo\rosetta\Fermat.exw
include mpfr.e

procedure fermat(mpz res, integer n)
    integer pn = power(2,n)
    mpz_ui_pow_ui(res,2,pn)
    mpz_add_si(res,res,1)
end procedure

mpz fn = mpz_init()
constant lim = iff(platform()=JS?18:29), -- (see note)
         print_lim = iff(platform()=JS?16:20)
for i=0 to lim do
    fermat(fn,i)
    if i<=print_lim then
        printf(1,"F%d = %s\n",{i,shorten(mpz_get_str(fn))})
    else -- (since printing it takes too long...)
        printf(1,"F%d has %,d digits\n",{i,mpz_sizeinbase(fn,10)})
    end if
end for

printf(1,"\n")
constant flimit = iff(platform()=JS?11:13)
for i=0 to flimit do
    atom t = time()
    fermat(fn,i)
    sequence f = mpz_prime_factors(fn, 200000)
    t = time()-t
    string fs = "",
           ts = elapsed(t)
    if length(f[$])=1 then -- (as per docs)
        mpz_set_str(fn,f[$][1])
        if not mpz_prime(fn) then
            if length(f)=1 then
                fs = " (not prime)"
            else
                fs = " (last factor is not prime)"
            end if
        end if
        f = deep_copy(f)
        f[$][1] = shorten(f[$][1])
    elsif length(f)=1
      and mpz_prime(fn) then
        fs = " (prime)"
    end if
    fs = mpz_factorstring(f)&fs
    printf(1,"Factors of F%d: %s [%s]\n",{i,fs,ts})
end for


fn1 = "ReadMe.txt"
fn2 = "ReadMe2.txt"

fp = fopen(fn1,"r")
str = fread(fp, getFileSize(fp))
fclose(fp)

fp = fopen(fn2,"w")
fwrite(fp, str)
fclose(fp)
see "OK" + nl

func getFileSize fp
     c_filestart = 0
     c_fileend = 2
     fseek(fp,0,c_fileend)
     nfilesize = ftell(fp)
     fseek(fp,0,c_filestart)
     return nfilesize


str = File.open('input.txt', 'rb') {|f| f.read}
File.open('output.txt', 'wb') {|f| f.write str}


open "input.txt" for input as #in
fileLen   = LOF(#in)		    'Length Of File
fileData$ = input$(#in, fileLen)    'read entire file
close #in

open "output.txt" for output as #out
print #out, fileData$               'write entire fie
close #out
end

' or directly with no intermediate fileData$

open "input.txt"  for input  as #in
open "output.txt" for output as #out
fileLen   = LOF(#in)		    'Length Of File
print #out, input$(#in, fileLen)    'entire file
close #in
close #out


use std::fs::File;
use std::io::{Read, Write};

fn main() {
    let mut file = File::open("input.txt").unwrap();
    let mut data = Vec::new();
    file.read_to_end(&mut data).unwrap();
    let mut file = File::create("output.txt").unwrap();
    file.write_all(&data).unwrap();
}


(seed (in "/dev/urandom" (rd 8)))
(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)) ) ) )
(de isprime (N)
   (cache '(NIL) N
      (if (== N 2)
         T
         (and
            (> N 1)
            (bit? 1 N)
            (let (Q (dec N)  N1 (dec N)  K 0  X)
               (until (bit? 1 Q)
                  (setq
                     Q (>> 1 Q)
                     K (inc K) ) )
               (catch 'composite
                  (do 16
                     (loop
                        (setq X
                           (**Mod
                              (rand 2 (min (dec N) 1000000000000))
                              Q
                              N ) )
                        (T (or (=1 X) (= X N1)))
                        (T
                           (do K
                              (setq X (**Mod X 2 N))
                              (when (=1 X) (throw 'composite))
                              (T (= X N1) T) ) )
                        (throw 'composite) ) )
                  (throw 'composite T) ) ) ) ) ) )
(de gcd (A B)
   (until (=0 B)
      (let M (% A B)
         (setq A B B M) ) )
   (abs A) )
(de g (A)
   (% (+ (% (* A A) N) C) N) )
(de pollard-brent (N)
   (let
      (A (dec N)
         Y (rand 1 (min A 1000000000000000000))
         C (rand 1 (min A 1000000000000000000))
         M (rand 1 (min A 1000000000000000000))
         G 1
         R 1
         Q 1 )
      (ifn (bit? 1 N)
         2
         (loop
            (NIL (=1 G))
            (setq X Y)
            (do R
               (setq Y (g Y)) )
            (zero K)
            (loop
               (NIL (and (> R K) (=1 G)))
               (setq YS Y)
               (do (min M (- R K))
                  (setq
                     Y (g Y)
                     Q (% (* Q (abs (- X Y))) N) ) )
               (setq
                  G (gcd Q N)
                  K (+ K M) )
            )
            (setq R (* R 2)) )
         (when (== G N)
            (loop
               (NIL (> G 1))
               (setq
                  YS (g YS)
                  G (gcd (abs (- X YS)) N) ) ) )
         (if (== G N)
            NIL
            G ) ) ) )
(de factors (N)
   (sort
      (make
         (loop
            (setq N (/ N (link (pollard-brent N))))
            (T (isprime N)) )
         (link N) ) ) )
(de fermat (N)
   (inc (** 2 (** 2 N))) )
(for (N 0 (>= 8 N) (inc N))
   (println N ': (fermat N)) )
(prinl)
(for (N 0 (>= 8 N) (inc N))
   (let N (fermat N)
      (println
         N
         ':
         (if (isprime N) 'PRIME (factors N)) ) ) )


def factors(x):
    factors = []
    i = 2
    s = int(x ** 0.5)
    while i < s:
        if x % i == 0:
            factors.append(i)
            x = int(x / i)
            s = int(x ** 0.5)
        i += 1
    factors.append(x)
    return factors

print("First 10 Fermat numbers:")
for i in range(10):
    fermat = 2 ** 2 ** i + 1
    print("F{} = {}".format(chr(i + 0x2080) , fermat))

print("\nFactors of first few Fermat numbers:")
for i in range(10):
    fermat = 2 ** 2 ** i + 1
    fac = factors(fermat)
    if len(fac) == 1:
        print("F{} -> IS PRIME".format(chr(i + 0x2080)))
    else:
        print("F{} -> FACTORS: {}".format(chr(i + 0x2080), fac))


use ntheory:from<Perl5> <factor>;

my @Fermats = (^Inf).map: 2 ** 2 ** * + 1;

my $sub = '₀';
say "First 10 Fermat numbers:";
printf "F%s = %s\n", $sub++, $_ for @Fermats[^10];

$sub = '₀';
say "\nFactors of first few Fermat numbers:";
for @Fermats[^9].map( {"$_".&factor} ) -> $f {
    printf "Factors of F%s: %s %s\n", $sub++, $f.join(' '), $f.elems == 1 ?? '- prime' !! ''
}


import java.io.{ FileNotFoundException, PrintWriter }

object FileIO extends App {
  try {
    val MyFileTxtTarget = new PrintWriter("output.txt")

    scala.io.Source.fromFile("input.txt").getLines().foreach(MyFileTxtTarget.println)
    MyFileTxtTarget.close()
  } catch {
    case e: FileNotFoundException => println(e.getLocalizedMessage())
    case e: Throwable => {
      println("Some other exception type:")
      e.printStackTrace()
    }
  }
}


; Open ports for the input and output files
(define in-file (open-input-file "input.txt"))
(define out-file (open-output-file "output.txt"))

; Read and write characters from the input file
; to the output file one by one until end of file
(do ((c (read-char in-file) (read-char in-file)))
        ((eof-object? c))
        (write-char c out-file))

; Close the ports
(close-input-port in-file)
(close-output-port out-file)


$ include "seed7_05.s7i";
  include "osfiles.s7i";

const proc: main is func
  begin
    copyFile("input.txt", "output.txt");
  end func;


/*REXX program to find and display  Fermat  numbers, and show factors of Fermat numbers.*/
parse arg n .                                    /*obtain optional argument from the CL.*/
if n=='' | n==","  then n= 9                     /*Not specified?  Then use the default.*/
numeric digits 20                                /*ensure enough decimal digits, for n=9*/

       do j=0  to n;   f= 2** (2**j)   +  1      /*calculate a series of Fermat numbers.*/
       say right('F'j, length(n) + 1)': '     f  /*display a particular     "      "    */
       end   /*j*/
say
       do k=0  to n;   f= 2** (2**k)   +  1; say /*calculate a series of Fermat numbers.*/
       say center(' F'k": " f' ', 79, "═")       /*display a particular     "      "    */
       p= factr(f)                               /*factor a Fermat number,  given time. */
       if words(p)==1  then say f ' is prime.'
                       else say 'factors: '   p
       end   /*k*/
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
factr:  procedure; parse arg x 1 z,,?
             do k=1  to 11  by 2;  j= k;  if j==1  then j= 2;  if j==9  then iterate
             call build                          /*add  J  to the factors list.         */
             end   /*k*/                         /* [↑]  factor  X  with some low primes*/

             do y=0  by 2;         j= j + 2 +   y // 4      /*ensure not  ÷  by three.  */
             parse var j '' -1 _;  if _==5  then iterate    /*last digit a "5"? Skip it.*/
             if j*j>x | j>z  then leave
             call build                          /*add  Y  to the factors list.         */
             end   /*y*/                         /* [↑]  factor  X  with other higher #s*/
        j= z
        if z\==1  then ?= build()
        if ?=''   then do;  @.1= x;  ?= x;  #= 1;  end
        return ?
/*──────────────────────────────────────────────────────────────────────────────────────*/
build:     do  while z//j==0;    z= z % j;    ?= ? j;    end;              return strip(?)


decimals(0)
load "stdlib.ring"

see "working..." + nl
see "The first 10 Fermat numbers are:" + nl

num = 0
limit = 9

for n = 0 to limit
    fermat = pow(2,pow(2,n)) + 1
    mod = fermat%2
    if n > 5
       ferm = string(fermat)
       tmp = number(right(ferm,1))+1
       fermat = left(ferm,len(ferm)-1) + string(tmp)
    ok
    see "F(" + n + ") = " + fermat + nl
next

see "done..." + nl


This uses the `factor` function from the `coreutils` library
that comes standard with most GNU/Linux, BSD, and Unix systems.
https://www.gnu.org/software/coreutils/
https://en.wikipedia.org/wiki/GNU_Core_Utilities


put file "input.txt" into fileContents
put fileContents into file "output.txt"


var in = %f'input.txt'.open_r;
var out = %f'output.txt'.open_w;

in.each { |line|
    out.print(line);
};


(File newNamed: 'input.txt' &mode: File Read) sessionDo: [| :in |
  (File newNamed: 'output.txt' &mode: File CreateWrite) sessionDo: [| :out |
    in >> out]]


 struct DivisorGen {
    curr: u64,
    last: u64,
}

impl Iterator for DivisorGen {
    type Item = u64;

    fn next(&mut self) -> Option<u64> {
        self.curr += 2u64;

        if self.curr < self.last{
            None
        } else {
            Some(self.curr)
        }
    }
}

fn divisor_gen(num : u64) -> DivisorGen {
    DivisorGen { curr: 0u64, last: (num / 2u64) + 1u64 }
}

fn is_prime(num : u64) -> bool{
    if num == 2 || num == 3 {
        return true;
    } else if num % 2 == 0 || num % 3 == 0 || num <= 1{
        return false;
    }else{
        for i in divisor_gen(num){
            if num % i == 0{
                return false;
            }
        }
    }
    return true;
}

fn main() {
    let fermat_closure = |i : u32| -> u64 {2u64.pow(2u32.pow(i + 1u32))};
    let mut f_numbers : Vec<u64> = Vec::new();

    println!("First 4 Fermat numbers:");
    for i in 0..4 {
        let f = fermat_closure(i) + 1u64;
        f_numbers.push(f);
        println!("F{}: {}", i, f);
    }

    println!("Factor of the first four numbers:");
    for f in f_numbers.iter(){
        let is_prime : bool = f % 4 == 1 && is_prime(*f);
        let not_or_not = if is_prime {" "} else {" not "};
        println!("{} is{}prime", f, not_or_not);
    }
}


import scala.collection.mutable
import scala.collection.mutable.ListBuffer

object FermatNumbers {
  def main(args: Array[String]): Unit = {
    println("First 10 Fermat numbers:")
    for (i <- 0 to 9) {
      println(f"F[$i] = ${fermat(i)}")
    }
    println()
    println("First 12 Fermat numbers factored:")
    for (i <- 0 to 12) {
      println(f"F[$i] = ${getString(getFactors(i, fermat(i)))}")
    }
  }

  private val TWO = BigInt(2)

  def fermat(n: Int): BigInt = {
    TWO.pow(math.pow(2.0, n).intValue()) + 1
  }

  def getString(factors: List[BigInt]): String = {
    if (factors.size == 1) {
      return s"${factors.head} (PRIME)"
    }

    factors.map(a => a.toString)
      .map(a => if (a.startsWith("-")) "(C" + a.replace("-", "") + ")" else a)
      .reduce((a, b) => a + " * " + b)
  }

  val COMPOSITE: mutable.Map[Int, String] = scala.collection.mutable.Map(
    9 -> "5529",
    10 -> "6078",
    11 -> "1037",
    12 -> "5488",
    13 -> "2884"
  )

  def getFactors(fermatIndex: Int, n: BigInt): List[BigInt] = {
    var n2 = n
    var factors = new ListBuffer[BigInt]
    var loop = true
    while (loop) {
      if (n2.isProbablePrime(100)) {
        factors += n2
        loop = false
      } else {
        if (COMPOSITE.contains(fermatIndex)) {
          val stop = COMPOSITE(fermatIndex)
          if (n2.toString.startsWith(stop)) {
            factors += -n2.toString().length
            loop = false
          }
        }
        if (loop) {
          val factor = pollardRhoFast(n2)
          if (factor == 0) {
            factors += n2
            loop = false
          } else {
            factors += factor
            n2 = n2 / factor
          }
        }
      }
    }

    factors.toList
  }

  def pollardRhoFast(n: BigInt): BigInt = {
    var x = BigInt(2)
    var y = BigInt(2)
    var z = BigInt(1)
    var d = BigInt(1)
    var count = 0

    var loop = true
    while (loop) {
      x = pollardRhoG(x, n)
      y = pollardRhoG(pollardRhoG(y, n), n)
      d = (x - y).abs
      z = (z * d) % n
      count += 1
      if (count == 100) {
        d = z.gcd(n)
        if (d != 1) {
          loop = false
        } else {
          z = BigInt(1)
          count = 0
        }
      }
    }

    println(s"    Pollard rho try factor $n")
    if (d == n) {
      return 0
    }
    d
  }

  def pollardRhoG(x: BigInt, n: BigInt): BigInt = ((x * x) + 1) % n
}


| in out |
in := FileStream open: 'input.txt' mode: FileStream read.
out := FileStream open: 'output.txt' mode: FileStream write.
[ in atEnd ]
  whileFalse: [
     out nextPut: (in next)
  ]


let: q Bin list;
'input.txt' rfile read {{@q $1 push} when} for
@q 'output.txt' rwfile write
0 $1 &+ for


        input(.input,5,,'input.txt')
        output(.output,6,,'output.txt')
while   output = input                   :s(while)
end


fun copyFile (from, to) =
let
  val instream = TextIO.openIn from
  val outstream = TextIO.openOut to
  val () = TextIO.output (outstream, TextIO.inputAll instream)
  val () = TextIO.closeIn instream
  val () = TextIO.closeOut outstream
in
  true
end handle _ => false;