I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

# Loops/Increment loop index within loop body

Loops/Increment loop index within loop body
You are encouraged to solve this task according to the task description, using any language you may know.

Sometimes, one may need   (or want)   a loop which its   iterator   (the index variable)   is modified within the
loop body   in addition to the normal incrementation by the   (do)   loop structure index.

Goal

Demonstrate the best way to accomplish this.

Write a loop which:

•   starts the index (variable) at   42
•   (at iteration time)   increments the index by unity
•   if the index is prime:
•   displays the count of primes found (so far) and the prime   (to the terminal)
•   increments the index such that the new index is now the (old) index plus that prime
•   terminates the loop when   42   primes are shown

Extra credit:   because of the primes get rather large, use commas within the displayed primes to ease comprehension.

Show all output here.

Note

Not all programming languages allow the modification of a loop's index.   If that is the case, then use whatever method that is appropriate or idiomatic for that language.   Please add a note if the loop's index isn't modifiable.

## 11l

Translation of: Python
`F is_prime(n)   L(x) (2, 3)      I n % x == 0         R n == x   Int64 d = 5   L d * d <= n      L(x) (2, 4)         I n % d == 0            R 0B         d += x   R 1B Int64 i = 42V n = 0L n < 42   I is_prime(i)      n++      print(‘n = #2 #16’.format(n, i))      i += i - 1   i++`
Output:
```n =  1               43
n =  2               89
n =  3              179
n =  4              359
n =  5              719
n =  6             1439
n =  7             2879
n =  8             5779
n =  9            11579
n = 10            23159
...
n = 40   24876007075181
n = 41   49752014150467
n = 42   99504028301131
```

## 360 Assembly

Assembler 360 provides 3 instructions to create loops: BCT, BXH and BXLE, the register which contains the loop index can be modified at any time. Nothing exceptional for an assembly, banning to modify the loop index begins with high level languages.
This task is a good example of the use of ED instruction to format a number. For macro use (IF,DO,...), see Structured Macros.

`*        Loops/Increment loop index within loop body - 16/07/2018LOOPILWB PROLOG         SR     R6,R6              i=0         ZAP    N,=P'42'           n=42       DO WHILE=(C,R6,LT,IMAX)     do while(i<imax)         BAL    R14,ISPRIME          call isprime(n)       IF C,R0,EQ,=F'1' THEN         if n is prime then         LA     R6,1(R6)               i=i+1         XDECO  R6,XDEC                edit i         MVC    PG+2(2),XDEC+10        output i         MVC    ZN,EM                  load edit mask         ED     ZN,N                   edit n         MVC    PG+7(L'ZN),ZN          output n         XPRNT  PG,L'PG                print buffer         ZAP    WP,N                   n         AP     WP,N                   +n         SP     WP,=P'1'               +1         ZAP    N,WP                   n=n+n-1       ENDIF    ,                    endif                           ZAP    WP,N                 n         AP     WP,=P'1'             +1         ZAP    N,WP                 n=n+1       ENDDO    ,                  enddo         EPILOGISPRIME  EQU    *                  isprime(n) -----------------------         CP     N,=P'2'            if n=2         BE     RETURN1            then return(1)         CP     N,=P'3'            if n=3         BE     RETURN1            then return(1)         ZAP    WDP,N              n         DP     WDP,=PL8'2'        /2         CP     WDP+8(8),=P'0'     if mod(n,2)=0         BE     RETURN0            then return(0)         ZAP    WDP,N              n         DP     WDP,=PL8'3'        /3         CP     WDP+8(8),=P'0'     if mod(n,3)=0         BE     RETURN0            then return(0)         ZAP    J,=P'5'            j=5LWHILE   ZAP    WP,J               j         MP     WP,J               *j         CP     WP,N               while(j*j<=n)         BH     EWHILE             ~         ZAP    WDP,N                n         DP     WDP,J                /j         CP     WDP+8(8),=P'0'       if mod(n,j)=0         BE     RETURN0              then return(0)         ZAP    WP,J                 j         AP     WP,=P'2'             +2         ZAP    WDP,N                n         DP     WDP,WP               n/(j+2)         CP     WDP+8(8),=P'0'       if mod(n,j+2)=0         BE     RETURN0              then return(0)         ZAP    WP,J                 j         AP     WP,=P'6'             +6         ZAP    J,WP                 j=j+6         B      LWHILE             loopwhileEWHILE   B      RETURN1            return(1)RETURN0  LA     R0,0               rc=0         B      RETURNXRETURN1  LA     R0,1               rc=1RETURNX  BR     R14                return to caller -----------------IMAX     DC     F'42'              limitEM       DC     XL20'402020206B2020206B2020206B2020206B202120'  maskN        DS     PL8                nJ        DS     PL8                jPG       DC     CL80'i=00 :  000,000,000,000,000'   bufferXDEC     DS     CL12               temp for XDECOWP       DS     PL8                temp for AP,SP,MPWDP      DS     PL16               temp for DPCW       DS     CL16               temp for UNPKZN       DS     CL20         REGEQU         END    LOOPILWB`
Output:
```i= 1 :                   43
i= 2 :                   89
i= 3 :                  179
i= 4 :                  359
i= 5 :                  719
i= 6 :                1,439
i= 7 :                2,879
i= 8 :                5,779
i= 9 :               11,579
i=10 :               23,159
i=11 :               46,327
i=12 :               92,657
i=13 :              185,323
i=14 :              370,661
i=15 :              741,337
i=16 :            1,482,707
i=17 :            2,965,421
i=18 :            5,930,887
i=19 :           11,861,791
i=20 :           23,723,597
i=21 :           47,447,201
i=22 :           94,894,427
i=23 :          189,788,857
i=24 :          379,577,741
i=25 :          759,155,483
i=26 :        1,518,310,967
i=27 :        3,036,621,941
i=28 :        6,073,243,889
i=29 :       12,146,487,779
i=30 :       24,292,975,649
i=31 :       48,585,951,311
i=32 :       97,171,902,629
i=33 :      194,343,805,267
i=34 :      388,687,610,539
i=35 :      777,375,221,081
i=36 :    1,554,750,442,183
i=37 :    3,109,500,884,389
i=38 :    6,219,001,768,781
i=39 :   12,438,003,537,571
i=40 :   24,876,007,075,181
i=41 :   49,752,014,150,467
i=42 :   99,504,028,301,131
```

## AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
` /* ARM assembly AARCH64 Raspberry PI 3B *//*  program loopinc64.s   */ /*******************************************//* Constantes file                         *//*******************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc" /*********************************//* Initialized data              *//*********************************/.dataszMessOverflow:     .asciz "Error: overflow !!!!"sMessResult:        .asciz "Index  : @ Value  : @ \n"szCarriageReturn:   .asciz "\n" /*********************************//* UnInitialized data            *//*********************************/.bsssZoneConv:                .skip 24/*********************************//*  code section                 *//*********************************/.text.global main main:                             // entry of program     mov x20,0                     // counter    mov x21,42                    // start index1:                                // begin loop    mov x0,x21    bl isPrime                    // prime ?    bcs 100f                      // error overflow ?    cbnz x0,2f                    // is prime ?    add x21,x21,1                 // no -> increment index    b 1b                          // and loop2:                                // display index and prime    add x20,x20,1                 // increment counter    mov x0,x20    ldr x1,qAdrsZoneConv          // conversion index    bl conversion10    ldr x0,qAdrsMessResult    ldr x1,qAdrsZoneConv     bl strInsertAtCharInc         // insert result at first @ character    mov x10,x0    mov x0,x21                    // conversion value    ldr x1,qAdrsZoneConv     bl conversion10               // decimal conversion  ascii    mov x0,x10    ldr x1,qAdrsZoneConv    bl strInsertAtCharInc         // insert result at second @ character    bl affichageMess       add x21,x21,x21    cmp x20,42                    // end ?    blt 1b                        // no loop 100:                              // standard end of the program     mov x0,0                      // return code    mov x8,EXIT                   // request to exit program    svc 0                         // perform the system call qAdrsZoneConv:            .quad sZoneConvqAdrszCarriageReturn:     .quad szCarriageReturnqAdrsMessResult:          .quad sMessResult/***************************************************//*   Verification si un nombre est premier         *//***************************************************//* x0 contient le nombre à verifier *//* x0 retourne 1 si premier  0 sinon */isPrime:    stp x1,lr,[sp,-16]!        // save  registres    stp x2,x3,[sp,-16]!        // save  registres    mov x2,x0    sub x1,x0,#1    cmp x2,0    beq 99f                    // retourne zéro    cmp x2,2                   // pour 1 et 2 retourne 1    ble 2f    mov x0,#2    bl moduloPuR64    bcs 100f                   // erreur overflow    cmp x0,#1    bne 99f                    // Pas premier    cmp x2,3    beq 2f    mov x0,#3    bl moduloPuR64    blt 100f                   // erreur overflow    cmp x0,#1    bne 99f     cmp x2,5    beq 2f    mov x0,#5    bl moduloPuR64    bcs 100f                   // erreur overflow    cmp x0,#1    bne 99f                    // Pas premier     cmp x2,7    beq 2f    mov x0,#7    bl moduloPuR64    bcs 100f                   // erreur overflow    cmp x0,#1    bne 99f                    // Pas premier     cmp x2,11    beq 2f    mov x0,#11    bl moduloPuR64    bcs 100f                   // erreur overflow    cmp x0,#1    bne 99f                    // Pas premier     cmp x2,13    beq 2f    mov x0,#13    bl moduloPuR64    bcs 100f                   // erreur overflow    cmp x0,#1    bne 99f                    // Pas premier2:    cmn x0,0                   // carry à zero pas d'erreur    mov x0,1                   // premier    b 100f99:    cmn x0,0                   // carry à zero pas d'erreur    mov x0,#0                  // Pas premier100:    ldp x2,x3,[sp],16          // restaur des  2 registres    ldp x1,lr,[sp],16          // restaur des  2 registres    ret                        // retour adresse lr x30 /********************************************************//*   Calcul modulo de b puissance e modulo m  *//*    Exemple 4 puissance 13 modulo 497 = 445         *//********************************************************//* x0  nombre  *//* x1 exposant *//* x2 modulo   */moduloPuR64:    stp x1,lr,[sp,-16]!        // save  registres    stp x3,x4,[sp,-16]!        // save  registres    stp x5,x6,[sp,-16]!        // save  registres    stp x7,x8,[sp,-16]!        // save  registres    stp x9,x10,[sp,-16]!       // save  registres    cbz x0,100f    cbz x1,100f    mov x8,x0    mov x7,x1    mov x6,1                   // resultat    udiv x4,x8,x2    msub x9,x4,x2,x8           // contient le reste1:    tst x7,1    beq 2f    mul x4,x9,x6    umulh x5,x9,x6    mov x6,x4    mov x0,x6    mov x1,x5    bl divisionReg128U    cbnz x1,99f                 // overflow    mov x6,x32:    mul x8,x9,x9    umulh x5,x9,x9    //cbnz x5,99f    mov x0,x8    mov x1,x5    bl divisionReg128U    cbnz x1,99f                 // overflow    mov x9,x3    lsr x7,x7,1    cbnz x7,1b    mov x0,x6                  // result    cmn x0,0                   // carry à zero pas d'erreur    b 100f99:    ldr x0,qAdrszMessOverflow    bl   affichageMess    cmp x0,0                   // carry à un car erreur    mov x0,-1                  // code erreur 100:    ldp x9,x10,[sp],16         // restaur des  2 registres    ldp x7,x8,[sp],16          // restaur des  2 registres    ldp x5,x6,[sp],16          // restaur des  2 registres    ldp x3,x4,[sp],16          // restaur des  2 registres    ldp x1,lr,[sp],16          // restaur des  2 registres    ret                        // retour adresse lr x30qAdrszMessOverflow:         .quad  szMessOverflow/***************************************************//*   division d un nombre de 128 bits par un nombre de 64 bits *//***************************************************//* x0 contient partie basse dividende *//* x1 contient partie haute dividente *//* x2 contient le diviseur *//* x0 retourne partie basse quotient *//* x1 retourne partie haute quotient *//* x3 retourne le reste */divisionReg128U:    stp x6,lr,[sp,-16]!        // save  registres    stp x4,x5,[sp,-16]!        // save  registres    mov x5,#0                  // raz du reste R    mov x3,#128                // compteur de boucle    mov x4,#0                  // dernier bit1:        lsl x5,x5,#1               // on decale le reste de 1    tst x1,1<<63               // test du bit le plus à gauche    lsl x1,x1,#1               // on decale la partie haute du quotient de 1    beq 2f    orr  x5,x5,#1              // et on le pousse dans le reste R2:    tst x0,1<<63    lsl x0,x0,#1               // puis on decale la partie basse     beq 3f    orr x1,x1,#1               // et on pousse le bit de gauche dans la partie haute3:    orr x0,x0,x4               // position du dernier bit du quotient    mov x4,#0                  // raz du bit    cmp x5,x2    blt 4f    sub x5,x5,x2                // on enleve le diviseur du reste    mov x4,#1                   // dernier bit à 14:                               // et boucle    subs x3,x3,#1    bgt 1b        lsl x1,x1,#1               // on decale le quotient de 1    tst x0,1<<63    lsl x0,x0,#1               // puis on decale la partie basse     beq 5f    orr x1,x1,#15:    orr x0,x0,x4                  // position du dernier bit du quotient    mov x3,x5100:    ldp x4,x5,[sp],16          // restaur des  2 registres    ldp x6,lr,[sp],16          // restaur des  2 registres    ret                        // retour adresse lr x30/********************************************************//*        File Include fonctions                        *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc" `
Output:
```Index  : 1 Value  : 43
Index  : 2 Value  : 89
Index  : 3 Value  : 179
Index  : 4 Value  : 359
Index  : 5 Value  : 719
Index  : 6 Value  : 1439
Index  : 7 Value  : 2879
Index  : 8 Value  : 5779
Index  : 9 Value  : 11579
Index  : 10 Value  : 23159
Index  : 11 Value  : 46327
Index  : 12 Value  : 92657
Index  : 13 Value  : 185323
Index  : 14 Value  : 370661
Index  : 15 Value  : 741337
Index  : 16 Value  : 1482707
Index  : 17 Value  : 2965421
Index  : 18 Value  : 5930887
Index  : 19 Value  : 11861791
Index  : 20 Value  : 23723597
Index  : 21 Value  : 47447201
Index  : 22 Value  : 94894427
Index  : 23 Value  : 189788857
Index  : 24 Value  : 379577741
Index  : 25 Value  : 759155483
Index  : 26 Value  : 1518310967
Index  : 27 Value  : 3036621941
Index  : 28 Value  : 6073243889
Index  : 29 Value  : 12146487779
Index  : 30 Value  : 24292975649
Index  : 31 Value  : 48585951311
Index  : 32 Value  : 97171902629
Index  : 33 Value  : 194343805267
Index  : 34 Value  : 388687610539
Index  : 35 Value  : 777375221081
Index  : 36 Value  : 1554750442183
Index  : 37 Value  : 3109500884389
Index  : 38 Value  : 6219001768781
Index  : 39 Value  : 12438003537571
Index  : 40 Value  : 24876007075181
Index  : 41 Value  : 49752014150467
Index  : 42 Value  : 99504028301131
```

Ada does not allow the loop counter of a FOR loop to be modified in the loop. This example uses a simple Ada loop. The example also uses an Ada fixed decimal type to provide the comma insertion for the output.

`with Ada.Text_IO;         use Ada.Text_IO;with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;with Ada.Text_IO.Editing; use Ada.Text_IO.Editing;with Ada.Numerics.Generic_Elementary_Functions; procedure Main is   type nums is delta 0.1 digits 15;   format : String  := "zz_zzz_zzz_zzz_zzz_zz9.9";   pic    : picture := To_Picture (format);   package Nums_io is new Decimal_Output (Nums);   use Nums_IO;   type U_64 is mod 2**64;    package mod_io is new Modular_IO (U_64);   use mod_io;    function Is_Prime (Num : U_64) return boolean is      package Flt_Funcs is new Ada.Numerics.Generic_Elementary_Functions        (Float);      use Flt_Funcs;       T     : U_64          := 2;      Limit : constant U_64 := U_64 (Sqrt (Float (Num)));   begin      if Num = 2 then         return True;      end if;      while T <= Limit loop         if Num mod T = 0 then            return False;         end if;         T := T + (if T > 2 then 2 else 1);      end loop;      return True;   end Is_Prime;   Prime_Count : natural := 0;   Prime_Test  : U_64    := 42;begin   loop      if Is_Prime (Prime_Test) then         Prime_Count := Prime_Count + 1;         Put ("n =");         Put (Item => Prime_Count, Width => 3);         Put (Item => Nums (Prime_Test), Pic => pic);         New_Line;         Prime_Test := (Prime_Test * 2) - 1;      end if;      Prime_Test := Prime_Test + 1;      exit when Prime_Count = 42;   end loop;end Main; `
Output:
```n =  1                    43.0
n =  2                    89.0
n =  3                   179.0
n =  4                   359.0
n =  5                   719.0
n =  6                 1,439.0
n =  7                 2,879.0
n =  8                 5,779.0
n =  9                11,579.0
n = 10                23,159.0
n = 11                46,327.0
n = 12                92,657.0
n = 13               185,323.0
n = 14               370,661.0
n = 15               741,337.0
n = 16             1,482,707.0
n = 17             2,965,421.0
n = 18             5,930,887.0
n = 19            11,861,791.0
n = 20            23,723,597.0
n = 21            47,447,201.0
n = 22            94,894,427.0
n = 23           189,788,857.0
n = 24           379,577,741.0
n = 25           759,155,483.0
n = 26         1,518,310,967.0
n = 27         3,036,621,941.0
n = 28         6,073,243,889.0
n = 29        12,146,487,779.0
n = 30        24,292,975,649.0
n = 31        48,585,951,311.0
n = 32        97,171,902,629.0
n = 33       194,343,805,267.0
n = 34       388,687,610,539.0
n = 35       777,375,221,081.0
n = 36     1,554,750,442,183.0
n = 37     3,109,500,884,389.0
n = 38     6,219,001,768,781.0
n = 39    12,438,003,537,571.0
n = 40    24,876,007,075,181.0
n = 41    49,752,014,150,467.0
n = 42    99,504,028,301,131.0
```

## ALGOL 68

In Algol 68, the FOR loop counter cannot be modified in the loop. This uses a WHILE loop testing at the top but is otherwise largely a translation of the Kotlin entry.

`BEGIN    # returns TRUE if n is prime, FALSE otherwise #    PROC is prime = ( LONG INT n )BOOL:         IF   n MOD 2 = 0 THEN n = 2         ELIF n MOD 3 = 0 THEN n = 3         ELSE            LONG INT d := 5;            BOOL result := TRUE;            WHILE IF   d * d > n   THEN FALSE                  ELIF n MOD d = 0 THEN result := FALSE                  ELIF d +:= 2;                       n MOD d = 0 THEN result := FALSE                  ELSE d +:= 4; TRUE                  FI            DO SKIP OD;            result         FI # is prime # ;     LONG INT i := 42;    LONG INT n := 0;    WHILE n < 42 DO        IF is prime( i ) THEN            n +:= 1;            print( ( "n = "                   , whole( n,  -2 )                   , "  "                   , whole( i, -19 )                   , newline                   )                 );            i +:= i - 1        FI;        i +:= 1    ODEND`
Output:
```n =  1                   43
n =  2                   89
n =  3                  179
n =  4                  359
n =  5                  719
n =  6                 1439
n =  7                 2879
n =  8                 5779
n =  9                11579
n = 10                23159
n = 11                46327
n = 12                92657
n = 13               185323
n = 14               370661
n = 15               741337
n = 16              1482707
n = 17              2965421
n = 18              5930887
n = 19             11861791
n = 20             23723597
n = 21             47447201
n = 22             94894427
n = 23            189788857
n = 24            379577741
n = 25            759155483
n = 26           1518310967
n = 27           3036621941
n = 28           6073243889
n = 29          12146487779
n = 30          24292975649
n = 31          48585951311
n = 32          97171902629
n = 33         194343805267
n = 34         388687610539
n = 35         777375221081
n = 36        1554750442183
n = 37        3109500884389
n = 38        6219001768781
n = 39       12438003537571
n = 40       24876007075181
n = 41       49752014150467
n = 42       99504028301131
```

## ARM Assembly

Works with: as version Raspberry Pi
` /* ARM assembly Raspberry PI  *//*  program loopinc96.s   */ /************************************//* Constantes                       *//************************************/.equ STDOUT, 1     @ Linux output console.equ EXIT,   1     @ Linux syscall.equ WRITE,  4     @ Linux syscall /*********************************//* Initialized data              *//*********************************/.dataszMessMultOver:     .asciz "Multiplication 64 : Dépassement de capacité.\n"sMessResult:        .ascii "Index  : "sMessIndex:         .fill 11, 1, ' '            @ size => 11                    .ascii "Value  : "sMessValeur:        .fill 21, 1, ' '            @ size => 21szCarriageReturn:   .asciz "\n" /*********************************//* UnInitialized data            *//*********************************/.bss  /*********************************//*  code section                 *//*********************************/.text.global main main:                                              @ entry of program     mov r7,#0                                      @ counter    mov r5,#42                                     @ start index low bits    mov r6,#0                                      @ start index high bits1:                                                 @ begin loop    mov r0,r5    mov r1,r6    bl isPrime                                     @ prime ?    bcs 100f                                       @ error overflow ?    cmp r0,#1                                      @ is prime ?    beq 2f                                         @ yes    adds r5,#1                                     @ no -> increment index    addcs r6,#1    b 1b                                           @ and loop2:                                                 @ display index and prime    add r7,#1                                      @ increment counter    mov r0,r7    ldr r1,iAdrsMessIndex                          @ conversion index    bl conversion10    mov r0,r5    mov r1,r6                                      @ conversion value    ldr r2,iAdrsMessValeur    bl conversionRegDoubleU                        @ conversion double -> ascii    ldr r0,iAdrsMessResult    bl affichageMess       adds r5,r5    add r6,r6    addcs r6,#1    cmp r7,#42                                     @ end ?    blt 1b                                         @ no loop 100:                                               @ standard end of the program     mov r0, #0                                     @ return code    mov r7, #EXIT                                  @ request to exit program    svc #0                                         @ perform the system call iAdrsMessIndex:           .int sMessIndexiAdrsMessValeur:          .int sMessValeuriAdrszCarriageReturn:     .int szCarriageReturniAdrsMessResult:          .int sMessResult  /******************************************************************//*     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"     svc #0                                         @ call systeme     pop {r0,r1,r2,r7,lr}                           @ restaur des  2 registres */     bx lr                                          @ return  /******************************************************************//*     Converting a register to a decimal unsigned                */ /******************************************************************//* r0 contains value and r1 address area   *//* r0 return size of result (no zero final in area) *//* area size => 11 bytes          */.equ LGZONECAL,   10conversion10:    push {r1-r4,lr}                                   @ save registers     mov r3,r1    mov r2,#LGZONECAL1:                                                    @ start loop    bl divisionpar10U                                 @ unsigned  r0 <- dividende. quotient ->r0 reste -> r1    add r1,#48                                        @ digit    strb r1,[r3,r2]                                   @ store digit on area    cmp r0,#0                                         @ stop if quotient = 0     subne r2,#1                                       @ else previous position    bne 1b                                            @ and loop                                                      @ and move digit from left of area    mov r4,#02:    ldrb r1,[r3,r2]    strb r1,[r3,r4]    add r2,#1    add r4,#1    cmp r2,#LGZONECAL    ble 2b                                                      @ and move spaces in end on area    mov r0,r4                                         @ result length     mov r1,#' '                                       @ space3:    strb r1,[r3,r4]                                   @ store space in area    add r4,#1                                         @ next position    cmp r4,#LGZONECAL    ble 3b                                            @ loop if r4 <= area size 100:    pop {r1-r4,lr}                                    @ restaur registres     bx lr                                             @return /***************************************************//*   division par 10   unsigned                    *//***************************************************//* r0 dividende   *//* r0 quotient   */	/* r1 remainder  */divisionpar10U:    push {r2,r3,r4, lr}    mov r4,r0                                          @ save value    //mov r3,#0xCCCD                                   @ r3 <- magic_number lower  raspberry 3    //movt r3,#0xCCCC                                  @ r3 <- magic_number higter raspberry 3    ldr r3,iMagicNumber                                @ r3 <- magic_number    raspberry 1 2    umull r1, r2, r3, r0                               @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)     mov r0, r2, LSR #3                                 @ r2 <- r2 >> shift 3    add r2,r0,r0, lsl #2                               @ r2 <- r0 * 5     sub r1,r4,r2, lsl #1                               @ r1 <- r4 - (r2 * 2)  = r4 - (r0 * 10)    pop {r2,r3,r4,lr}    bx lr                                              @ leave function iMagicNumber:  	.int 0xCCCCCCCD/***************************************************//*   number is prime ?              *//***************************************************//* r0 contains low bytes of double *//* r1 contains high bytes of double *//* r0 returns 1 if prime else 0  */@2147483647@4294967297@131071isPrime:    push {r1-r5,lr}                      @ save registers    mov r4,r0                            @ save double    mov r5,r1      subs r2,r0,#1                        @ exposant n - 1    sbcs r3,r1,#0     mov r0,#2                            @ base  2    mov r1,#0    bl moduloPuR96                       @ compute modulo    bcs 100f                             @ overflow error    cmp r0,#1                            @ modulo <> 1 -> no prime    bne 90f      mov r0,#3                            @ base 3    mov r1,#0    bl moduloPuR96    bcs 100f                             @ overflow error    cmp r0,#1    bne 90f     mov r0,#5                            @ base 5    mov r1,#0    bl moduloPuR96    bcs 100f                             @ overflow error    cmp r0,#1    bne 90f     mov r0,#7                            @ base 7    mov r1,#0    bl moduloPuR96    bcs 100f                             @ overflow error    cmp r0,#1    bne 90f     mov r0,#11                           @ base 11    mov r1,#0    bl moduloPuR96    bcs 100f                             @ overflow error    cmp r0,#1    bne 90f     mov r0,#13                           @ base 13    mov r1,#0    bl moduloPuR96    bcs 100f                             @ overflow error    cmp r0,#1    bne 90f     mov r0,#17                           @ base 17    mov r1,#0    bl moduloPuR96    bcs 100f                             @ overflow error    cmp r0,#1    bne 90f    mov r0,#1                            @ is prime    msr     cpsr_f, #0                   @ no error overflow zero -> flags    b 100f90:    mov r0,#0                            @ no prime    msr     cpsr_f, #0                   @ no error overflow zero -> flags100:                                     @ fin standard de la fonction     pop {r1-r5,lr}                       @ restaur registers    bx lr                                @ return   /********************************************************//*   compute  b pow e modulo m  *//*                                             *//********************************************************//* r0 base double low bits *//* r1 base double high bits *//* r2 exposant low bitss  *//* r3 exposant high bits *//* r4 modulo low bits *//* r5 modulo high bits *//* r0 returns result low bits *//* r1 returns result high bits *//* if overflow , flag carry is set else is clear */moduloPuR96:    push {r2-r12,lr}                       @ save registers      cmp r0,#0                              @ control low byte <> zero     bne 1f    cmp r1,#0                              @ control high bytes <> zero    beq 100f1:    mov r9,r4                              @ modulo PB    mov r10,r5                             @ modulo PH    mov r5,r2                              @ exposant **    mov r6,r3                              @ exposant    mov r7,r0                              @ base PB    mov r8,r1                              @ base PH    mov r2,#0    mov r3,r9    mov r4,r10    mov r11,#1                             @ result PB    mov r12,#0                             @ result PH/* r0 contient partie basse dividende *//* r1 contient partie moyenne dividende *//* r2 contient partie haute du diviseur *//* r3 contient partie basse diviseur  *//* r4 contient partie haute diviseur  *//* r0 retourne partie basse du quotient *//* r1 retourne partie moyenne du quotient *//* r2 retourne partie haute du quotient *//* r3 retourne partie basse du reste *//* r4 retourne partie haute du reste */    bl divisionReg96DU    mov r7,r3                               @ base <- remainder    mov r8,r42:    tst r5,#1                               @ test du bit 0    beq 3f    mov r0,r7    mov r1,r8    mov r2,r11    mov r3,r12    bl multiplicationR96U    bcs 100f                                @ error overflow    mov r3,r9    mov r4,r10    bl divisionReg96DU    mov r11,r3                              @ result <- remainder    mov r12,r43:    mov r0,r7    mov r1,r8    mov r2,r7    mov r3,r8    bl multiplicationR96U    bcs 100f                                @ error overflow    mov r3,r9    mov r4,r10    bl divisionReg96DU    mov r7,r3                               @ base <- remainder    mov r8,r4     lsr r5,#1       lsrs r6,#1    orrcs r5,#0x80000000    cmp r5,#0    bne 2b    cmp r6,#0    bne 2b    mov r0,r11    mov r1,r12    msr     cpsr_f, #0                       @ no error overflow zero -> flags100:                                         @ end function   	pop {r2-r12,lr}                          @ restaur registers    bx lr                                    @ return/***************************************************//*   multiplication 2 registers (64 bits) unsigned *//*   result in 3 registers 96 bits                 *//***************************************************//* r0 low bits number 1    *//* r1 high bits number 1    *//* r2 low bits number 2    *//* r3 high bits number 2    *//* r0 returns low bits résult   *//* r1 returns median bits résult *//* r2 returns high bits résult  *//* if overflow , flag carry is set else is clear */multiplicationR96U:    push {r3-r8,lr}           @ save registers    umull r5,r6,r0,r2         @ mult low bits    umull r4,r8,r0,r3         @ mult low bits 1 high bits 2    mov r0,r5                 @ result low bits ok    adds r4,r6                @ add results    addcs  r8,#1              @ carry    umull r6,r7,r1,r2         @ mult high bits 1 low bits 2    adds r4,r6                @ add results    addcs  r8,#1              @ carry     adds r8,r7                @ add results    bcs 99f                   @ overflow ?    umull r6,r7,r1,r3         @ mult high bits 1 high bits 2    cmp r7,#0                 @ error overflow ?    bne 99f       adds r8,r6                @ add results    bcs 99f                   @ error overflow    mov r1,r4                 @ return median bytes    mov r2,r8                 @ return high bytes    msr cpsr_f, #0            @ no error overflow zero -> flags    b 100f99:                           @ display message overflow	ldr r0,iAdrszMessMultOver @	bl affichageMess    mov r0,#0    mov r1,#0     msr cpsr_f, #1<<29        @ maj flag carry à 1  et tous les autres à 0100:                          @ end function     	pop {r3-r8,lr}            @ restaur registers    bx lr                     @ return iAdrszMessMultOver:         .int szMessMultOver/***************************************************//*   division number (3 registers) 92 bits by number (2 registers) 64 bits *//*           unsigned                            *//***************************************************//* r0 low bits dividende *//* r1 median bits dividende *//* r2 high bits dividende *//* r3 low bits divisor  *//* r4 high bits divis0r  *//* r0 returns low bits quotient *//* r1 returns median bits quotient *//* r2 returns high bits quotien *//* r3 returns low bits remainder *//* r4 returns high bits remainder *//* remainder do not is 3 registers */divisionReg96DU:    push {r5-r10,lr}    @ save registers    mov r7,r3           @ low bits divisor    mov r8,r4           @ high bits divisor    mov r4,r0           @ low bits dividende -> low bits quotient    mov r5,r1           @ median bits dividende  -> median bits quotient    mov r6,r2           @ high bits dividende -> high bits quotient                         @     mov r0,#0           @ low bits remainder    mov r1,#0           @ median bits remainder    mov r2,#0           @ high bits remainder (not useful)    mov r9,#96          @ counter loop (32 bits * 3)    mov r10,#0          @ last bit1:    lsl   r2,#1         @ shift left high bits remainder    lsls  r1,#1         @ shift left median bits remainder    orrcs r2,#1         @ left bit median -> right bit high    lsls r0,#1          @ shift left low bits remainder    orrcs r1,#1         @ left bit low -> right bit median    lsls r6,#1          @ shift left high bits quotient    orrcs r0,#1         @ left bit high -> right bit low remainder    lsls r5,#1          @ shift left median bits quotient    orrcs r6,#1         @ left bit median -> right bit high    lsls r4,#1          @ shift left low bits quotient    orrcs r5,#1         @ left bit low -> right bit median    orr r4,r10          @ last bit -> bit 0 quotient    mov r10,#0          @ raz du bit                        @ compare  remainder and divisor    cmp r2,#0           @ high bit remainder    bne 2f    cmp r1,r8           @ compare median bits     blo 3f              @ lower    bhi 2f              @ highter    cmp r0,r7           @ equal -> compare low bits    blo 3f              @ lower2:                      @ remainder > divisor    subs r0,r7          @ sub divisor of remainder    sbcs r1,r8    mov r10,#0          @ reuse ponctuelle  r10    sbc r2,r2,r10       @ carry     mov r10,#1          @ last bit à 13:    subs r9,#1          @ increment counter loop    bgt 1b              @ and loop    lsl r6,#1           @ shift left high bits quotient    lsls r5,#1          @ shift left median bits quotient    orrcs r6,#1         @ left bit median -> right bit high    lsls r4,#1          @ shift left low bits quotient    orrcs r5,#1         @ left bit low -> right bit median    orr r4,r10          @ last bit -> bit 0 quotient    mov r3,r0           @ low bits remainder    mov r0,r4           @ low bits quotient    mov r4,r1           @ high bits remainder    mov r1,r5           @ median bits quotient    //mov r5,r2    mov r2,r6           @ high bits quotient 100:                    @ end function     	pop {r5-r10,lr}     @ restaur registers    bx lr               @ return  /***************************************************//*   Conversion double integer 64bits in ascii     *//***************************************************//* r0 contains low bits     *//* r1 contains high bits    *//* r2 contains address area */conversionRegDoubleU:    push {r0-r5,lr}         @ save registers    mov r5,r2    mov r4,#19              @ start location    mov r2,#10              @ conversion decimale 1:                          @ begin loop     bl divisionReg64U       @ division by 10    add r3,#48              @ -> digit ascii    strb r3,[r5,r4]         @ store digit in area index r4    sub r4,r4,#1            @ decrement index    cmp r0,#0               @ low bits quotient = zero ?    bne 1b	                @ no -> loop    cmp r1,#0               @ high bits quotient = zero ?     bne 1b                  @ no -> loop                            @ spaces -> begin area     mov r3,#' '             @ space2:    strb r3,[r5,r4]         @ store space in area     subs r4,r4,#1           @ decrement index    bge 2b                  @ and loop if > zéro  100:                        @ end fonction     	pop {r0-r5,lr}          @ restaur registers    bx lr                   @ return/***************************************************//*   division number 64 bits / number 32 bits      *//***************************************************//* r0 contains low bits dividende  *//* r1 contains high bits dividente *//* r2 contains divisor             *//* r0 returns low bits quotient    *//* r1 returns high bits quotient   *//* r3 returns remainder            */divisionReg64U:    push {r4,r5,lr}    @ save registers    mov r5,#0          @ raz remainder R    mov r3,#64         @ loop counter    mov r4,#0          @ last bit1:    lsl r5,#1          @ shift left remainder one bit    lsls r1,#1         @ shift left high bits quotient one bit    orrcs r5,#1        @ and bit -> remainder    lsls r0,#1         @ shift left low bits quotient one bit    orrcs r1,#1        @ and left bit -> high bits     orr r0,r4          @ last bit  quotient    mov r4,#0          @ raz last bit    cmp r5,r2          @ compare remainder divisor    subhs r5,r2        @ if highter sub divisor of remainder    movhs r4,#1        @  and 1 -> last bit3:    subs r3,#1         @ decrement counter loop    bgt 1b             @ and loop if not zero    lsl r1,#1          @ else shift left higt bits quotient    lsls r0,#1         @ and shift  left low bits      orrcs r1,#1    orr r0,r4          @ last bit quotient    mov r3,r5100:                   @ end function    pop {r4,r5,lr}     @ restaur registers    bx lr              @ return `
Output:
```[email protected]:~/asm/rosetta/ASS3 \$ loopsinc96
Index  : 1          Value  :                   43
Index  : 2          Value  :                   89
Index  : 3          Value  :                  179
Index  : 4          Value  :                  359
Index  : 5          Value  :                  719
Index  : 6          Value  :                 1439
Index  : 7          Value  :                 2879
Index  : 8          Value  :                 5779
Index  : 9          Value  :                11579
Index  : 10         Value  :                23159
Index  : 11         Value  :                46327
Index  : 12         Value  :                92657
Index  : 13         Value  :               185323
Index  : 14         Value  :               370661
Index  : 15         Value  :               741337
Index  : 16         Value  :              1482707
Index  : 17         Value  :              2965421
Index  : 18         Value  :              5930887
Index  : 19         Value  :             11861791
Index  : 20         Value  :             23723597
Index  : 21         Value  :             47447201
Index  : 22         Value  :             94894427
Index  : 23         Value  :            189788857
Index  : 24         Value  :            379577741
Index  : 25         Value  :            759155483
Index  : 26         Value  :           1518310967
Index  : 27         Value  :           3036621941
Index  : 28         Value  :           6073243889
Index  : 29         Value  :          12146487779
Index  : 30         Value  :          24292975649
Index  : 31         Value  :          48585951311
Index  : 32         Value  :          97171902629
Index  : 33         Value  :         194343805267
Index  : 34         Value  :         388687610539
Index  : 35         Value  :         777375221081
Index  : 36         Value  :        1554750442183
Index  : 37         Value  :        3109500884389
Index  : 38         Value  :        6219001768781
Index  : 39         Value  :       12438003537571
Index  : 40         Value  :       24876007075181
Index  : 41         Value  :       49752014150467
Index  : 42         Value  :       99504028301131
```

## Arturo

Translation of: Python
`i: 42n: 0 while [n<42][	if? prime? i [		n: n+1		print ["n =" pad to :string n 2 pad to :string i 20]		i: i + i	]	else [		i: i + 1	]]`
Output:
```n =  1                   43
n =  2                   89
n =  3                  179
n =  4                  359
n =  5                  719
n =  6                 1439
n =  7                 2879
n =  8                 5779
n =  9                11579
n = 10                23159
n = 11                46327
n = 12                92657
n = 13               185323
n = 14               370661
n = 15               741337
n = 16              1482707
n = 17              2965421
n = 18              5930887
n = 19             11861791
n = 20             23723597
n = 21             47447201
n = 22             94894427
n = 23            189788857
n = 24            379577741
n = 25            759155483
n = 26           1518310967
n = 27           3036621941
n = 28           6073243889
n = 29          12146487779
n = 30          24292975649
n = 31          48585951311
n = 32          97171902629
n = 33         194343805267
n = 34         388687610539
n = 35         777375221081
n = 36        1554750442183
n = 37        3109500884389
n = 38        6219001768781
n = 39       12438003537571
n = 40       24876007075181
n = 41       49752014150467
n = 42       99504028301131```

## AutoHotkey

`i:= 42, n:= 1, result := ""while (n<43){	if isPrime(i)		result .= n ":`t" RegExReplace(i, "\B(?=(\d{3})+\$)", ",") "`n", i*=2, n++	else 		i++}MsgBox, 262208, , % resultreturn isPrime(num){	if !Mod(num, 2) || !Mod(num, 3) 		return false	lim := Sqrt(num),	i := 5	while (i<lim){		if !Mod(num, i)			return false		i+=2	}	return true}`
Output:
```1:	43
2:	89
3:	179
4:	359
5:	719
6:	1,439
7:	2,879
8:	5,779
9:	11,579
10:	23,159
11:	46,327
12:	92,657
13:	185,323
14:	370,661
15:	741,337
16:	1,482,707
17:	2,965,421
18:	5,930,887
19:	11,861,791
20:	23,723,597
21:	47,447,201
22:	94,894,427
23:	189,788,857
24:	379,577,741
25:	759,155,483
26:	1,518,310,967
27:	3,036,621,941
28:	6,073,243,889
29:	12,146,487,779
30:	24,292,975,649
31:	48,585,951,311
32:	97,171,902,629
33:	194,343,805,267
34:	388,687,610,539
35:	777,375,221,081
36:	1,554,750,442,183
37:	3,109,500,884,389
38:	6,219,001,768,781
39:	12,438,003,537,571
40:	24,876,007,075,181
41:	49,752,014,150,467
42:	99,504,028,301,131```

## AWK

` # syntax: GAWK -f LOOPS_INCREMENT_LOOP_INDEX_WITHIN_LOOP_BODY.AWKBEGIN {    limit = 42    n = 0    for (i=limit; n<limit; i++) {      if (is_prime(i)) {        printf("%2d %19'd\n",++n,i)        i += i - 1      }    }    exit(0)}function is_prime(n,  d) {    if (n % 2 == 0) { return(n == 2) }    if (n % 3 == 0) { return(n == 3) }    d = 5    while (d*d <= n) {      if (n % d == 0) { return(0) }      d += 2      if (n % d == 0) { return(0) }      d += 4    }    return(1)} `
Output:
``` 1                  43
2                  89
3                 179
4                 359
5                 719
6               1,439
7               2,879
8               5,779
9              11,579
10              23,159
11              46,327
12              92,657
13             185,323
14             370,661
15             741,337
16           1,482,707
17           2,965,421
18           5,930,887
19          11,861,791
20          23,723,597
21          47,447,201
22          94,894,427
23         189,788,857
24         379,577,741
25         759,155,483
26       1,518,310,967
27       3,036,621,941
28       6,073,243,889
29      12,146,487,779
30      24,292,975,649
31      48,585,951,311
32      97,171,902,629
33     194,343,805,267
34     388,687,610,539
35     777,375,221,081
36   1,554,750,442,183
37   3,109,500,884,389
38   6,219,001,768,781
39  12,438,003,537,571
40  24,876,007,075,181
41  49,752,014,150,467
42  99,504,028,301,131
```

## BASIC256

`function isPrime(number)	if (number % 2 = 0) or (number % 3 = 0) then return false	lim = sqr(number) 	for i = 5 to lim step 2		if number % i = 0 then return false	next i 	return trueend function i = 42counter = 0while counter < 42	if isPrime(i) then		counter += 1		print "n = "; counter, i		i += i - 1	end if	i += 1end whileend`

## C

The following uses a 'for' rather than a 'do/while' loop but otherwise is similar to the Kotlin entry.

The 'thousands separator' aspect (using the ' flag in printf and setting the locale appropriately) works fine when compiled with gcc on Ubuntu 14.04 but may not work on some other systems as this is not a standard flag.

`#include <stdio.h>#include <locale.h> #define LIMIT 42 int is_prime(long long n) {    if (n % 2 == 0) return n == 2;    if (n % 3 == 0) return n == 3;    long long d = 5;    while (d * d <= n) {        if (n % d == 0) return 0;        d += 2;        if (n % d == 0) return 0;        d += 4;    }    return 1;} int main() {    long long i;    int n;    setlocale(LC_NUMERIC, "");    for (i = LIMIT, n = 0; n < LIMIT; i++)        if (is_prime(i)) {            n++;            printf("n = %-2d  %'19lld\n", n, i);            i += i - 1;        }    return 0;}`
Output:
```Same as Kotlin entry
```

## C#

` using System;using System.Globalization; namespace PrimeNumberLoopcs{    class Program    {        static bool isPrime(double number)        {            for(double i = number - 1; i > 1; i--)            {                if (number % i == 0)                    return false;            }            return true;        }        static void Main(string[] args)        {            NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat;            nfi.NumberDecimalDigits = 0;            double i = 42;            int n = 0;            while (n < 42)            {                if (isPrime(i))                {                    n++;                    Console.WriteLine("n = {0,-20} {1,20}", n, i.ToString("N", nfi));                    i += i - 1;                }                i++;            }        }    }}`
Output:
```n = 1                                      43
n = 2                                      89
n = 3                                     179
n = 4                                     359
n = 5                                     719
n = 6                                   1,439
n = 7                                   2,879
n = 8                                   5,779
n = 9                                  11,579
n = 10                                 23,159
n = 11                                 46,327
n = 12                                 92,657
n = 13                                185,323
n = 14                                370,661
n = 15                                741,337
n = 16                              1,482,707
n = 17                              2,965,421
n = 18                              5,930,887
n = 19                             11,861,791
n = 20                             23,723,597
n = 21                             47,447,201
n = 22                             94,894,427
n = 23                            189,788,857
n = 24                            379,577,741
n = 25                            759,155,483
n = 26                          1,518,310,967
n = 27                          3,036,621,941
n = 28                          6,073,243,889
n = 29                         12,146,487,779
n = 30                         24,292,975,649
n = 31                         48,585,951,311
n = 32                         97,171,902,629
n = 33                        194,343,805,267
n = 34                        388,687,610,539
n = 35                        777,375,221,081
n = 36                      1,554,750,442,183
n = 37                      3,109,500,884,389
n = 38                      6,219,001,768,781
n = 39                     12,438,003,537,571
n = 40                     24,876,007,075,181
n = 41                     49,752,014,150,467
n = 42                     99,504,028,301,131
```

## C++

` #include "stdafx.h"#include <iostream>#include <math.h> using namespace std; bool isPrime(double number){        for (double i = number - 1; i >= 2; i--) {        if (fmod(number, i) == 0)	    return false;    }    return true;}int main(){    double i = 42;    int n = 0;    while (n < 42)    {        if (isPrime(i))        {            n++;	    cout.width(1); cout << left << "n = " << n;            //Only for Text Alignment            if (n < 10)	    {	        cout.width(40); cout << right << i << endl;	    }	    else	    {		cout.width(39); cout << right << i << endl;	    }            i += i - 1;	}	i++;    }    return 0;}`

## Common Lisp

` (defun primep (n)                            ; https://stackoverflow.com/questions/15817350/  (cond ((= 2 n) t)                          ; Hard-code "2 is a prime"        ((= 3 n) t)                          ; Hard-code "3 is a prime"        ((evenp n) nil)                      ; If we're looking at an even now, it's not a prime        (t                                   ; If it is divisible by an odd number below its square root, it's not prime	 (do* ((i 3 (incf i 2)))             ; Initialize to 3 and increment by 2 on every loop	      ((or (> i (isqrt n))           ; Break condition index exceeds its square root		   (zerop (mod n i)))        ; Break condition it is divisible	       (not (zerop (mod n i))))))))  ; Returns not divisible, aka prime (do ((i 42)                                  ; Initialize index to 42     (c 0))                                  ; Initialize count of primes to 0    ((= c 42))                               ; Break condition when there are 42 primes  (incf i)                                   ; Increments index by unity  (if (primep i)(progn (incf c)              ; If prime increment count of primes		       (format t "~&~5<~d~;->~>~20<~:d~>" c i) ; Display count of primes found and the prime		       (incf i (decf i)))))  ; Increment index to previous index plus the prime `
Output:
```1  ->                  43
2  ->                  89
3  ->                 179
4  ->                 359
5  ->                 719
6  ->               1,439
7  ->               2,879
8  ->               5,779
9  ->              11,579
10 ->              23,159
11 ->              46,327
12 ->              92,657
13 ->             185,323
14 ->             370,661
15 ->             741,337
16 ->           1,482,707
17 ->           2,965,421
18 ->           5,930,887
19 ->          11,861,791
20 ->          23,723,597
21 ->          47,447,201
22 ->          94,894,427
23 ->         189,788,857
24 ->         379,577,741
25 ->         759,155,483
26 ->       1,518,310,967
27 ->       3,036,621,941
28 ->       6,073,243,889
29 ->      12,146,487,779
30 ->      24,292,975,649
31 ->      48,585,951,311
32 ->      97,171,902,629
33 ->     194,343,805,267
34 ->     388,687,610,539
35 ->     777,375,221,081
36 ->   1,554,750,442,183
37 ->   3,109,500,884,389
38 ->   6,219,001,768,781
39 ->  12,438,003,537,571
40 ->  24,876,007,075,181
41 ->  49,752,014,150,467
42 ->  99,504,028,301,131
```

## Delphi

Translation of: C#
` program Increment_loop_index_within_loop_body; {\$APPTYPE CONSOLE} uses  System.SysUtils; function IsPrime(const a: UInt64): Boolean;var  d: UInt64;begin  if (a < 2) then    exit(False);   if (a mod 2) = 0 then    exit(a = 2);   if (a mod 3) = 0 then    exit(a = 3);   d := 5;   while (d * d <= a) do  begin    if (a mod d = 0) then      Exit(false);    inc(d, 2);     if (a mod d = 0) then      Exit(false);    inc(d, 4);  end;   Result := True;end; var  i, n: UInt64; begin  FormatSettings.ThousandSeparator:= ',';  i := 42;  n := 0;  while (n < 42) do  begin    if (isPrime(i)) then    begin      inc(n);      Writeln('n = ', n: -20, ' ', floattostrF(i, ffNumber, 20,0):20);      i := 2 * i - 1;    end;    inc(i);  end;  readln;end.`
Output:

Same of #C#.

## Dyalect

`func isPrime(number) {    if number <= 1 {        return false    }    else if number % 2 == 0 {        return number == 2    }     var i = 3     while (i * i) < number {        if number % i == 0 {            return false        }        i += 2    }     return true} var i = 42var n = 0 while n < 42 {    if isPrime(i) {        n += 1        print("n = \(n)\t\(i)")        i += i - 1    }    i += 1}`

Output:

```n = 1   43
n = 2   89
n = 3   179
n = 4   359
n = 5   719
n = 6   1439
n = 7   2879
n = 8   5779
n = 9   11579
n = 10  23159
n = 11  46327
n = 12  92657
n = 13  185323
n = 14  370661
n = 15  741337
n = 16  1482707
n = 17  2965421
n = 18  5930887
n = 19  11861791
n = 20  23723597
n = 21  47447201
n = 22  94894427
n = 23  189788857
n = 24  379577741
n = 25  759155483
n = 26  1518310967
n = 27  3036621941
n = 28  6073243889
n = 29  12146487779
n = 30  24292975649
n = 31  48585951311
n = 32  97171902629
n = 33  194343805267
n = 34  388687610539
n = 35  777375221081
n = 36  1554750442183
n = 37  3109500884389
n = 38  6219001768781
n = 39  12438003537571
n = 40  24876007075181
n = 41  49752014150467
n = 42  99504028301131```

## F#

This task uses Extensible Prime Generator (F#)

` // Well I don't do loops. Nigel Galloway: March 17th., 2019. Let me try to explain where the loopy variables are, for the imperatively constrained.  // cUL allows me to claim the rather trivial extra credit (commas in the numbers)let cUL=let g=System.Globalization.CultureInfo("en-GB") in (fun (n:uint64)->n.ToString("N0",g))// fN is primality by trial divisionlet fN g=pCache|>Seq.map uint64|>Seq.takeWhile(fun n->n*n<g)|>Seq.forall(fun n->g%n>0UL)// unfold is sort of a loop incremented by 1 in this caselet fG n=Seq.unfold(fun n->Some(n,(n+1UL))) n|>Seq.find(fN)// unfold is sort of a loop with fG as an internal loop incremented by the exit value of the internal loop in this case.Seq.unfold(fun n->let n=fG n in Some(n,n+n)) 42UL|>Seq.take 42|>Seq.iteri(fun n g->printfn "%2d -> %s"  (n+1) (cUL g)) `
Output:
``` 1 -> 43
2 -> 89
3 -> 179
4 -> 359
5 -> 719
6 -> 1,439
7 -> 2,879
8 -> 5,779
9 -> 11,579
10 -> 23,159
11 -> 46,327
12 -> 92,657
13 -> 185,323
14 -> 370,661
15 -> 741,337
16 -> 1,482,707
17 -> 2,965,421
18 -> 5,930,887
19 -> 11,861,791
20 -> 23,723,597
21 -> 47,447,201
22 -> 94,894,427
23 -> 189,788,857
24 -> 379,577,741
25 -> 759,155,483
26 -> 1,518,310,967
27 -> 3,036,621,941
28 -> 6,073,243,889
29 -> 12,146,487,779
30 -> 24,292,975,649
31 -> 48,585,951,311
32 -> 97,171,902,629
33 -> 194,343,805,267
34 -> 388,687,610,539
35 -> 777,375,221,081
36 -> 1,554,750,442,183
37 -> 3,109,500,884,389
38 -> 6,219,001,768,781
39 -> 12,438,003,537,571
40 -> 24,876,007,075,181
41 -> 49,752,014,150,467
42 -> 99,504,028,301,131
```

## Factor

Explicit loop indices are non-idiomatic, but Factor is certainly capable of using them. Factor has a for loop near-equivalent, `<range> [ ] each`, but since it doesn't mesh well with mutation, a while loop is used.

### Using two numbers on the data stack

`USING: formatting kernel math math.primestools.memory.private ;IN: rosetta-code.loops-inc-body 420[ dup 42 < ] [    over prime? [        1 + 2dup swap commas        "n = %-2d  %19s\n" printf        [ dup + 1 - ] dip    ] when    [ 1 + ] dip] while2drop`

### Using lexical variables

Factor provides lexical variables for situations where they improve readability.

`USING: formatting kernel math math.primestools.memory.private ;IN: rosetta-code.loops-inc-body [let    42 :> i!    0  :> n!    [ n 42 < ] [        i prime? [            n 1 + n!            n i commas "n = %-2d  %19s\n" printf            i i + 1 - i!        ] when        i 1 + i!    ] while]`
Output:
```n = 1                    43
n = 2                    89
n = 3                   179
n = 4                   359
n = 5                   719
n = 6                 1,439
n = 7                 2,879
n = 8                 5,779
n = 9                11,579
n = 10               23,159
n = 11               46,327
n = 12               92,657
n = 13              185,323
n = 14              370,661
n = 15              741,337
n = 16            1,482,707
n = 17            2,965,421
n = 18            5,930,887
n = 19           11,861,791
n = 20           23,723,597
n = 21           47,447,201
n = 22           94,894,427
n = 23          189,788,857
n = 24          379,577,741
n = 25          759,155,483
n = 26        1,518,310,967
n = 27        3,036,621,941
n = 28        6,073,243,889
n = 29       12,146,487,779
n = 30       24,292,975,649
n = 31       48,585,951,311
n = 32       97,171,902,629
n = 33      194,343,805,267
n = 34      388,687,610,539
n = 35      777,375,221,081
n = 36    1,554,750,442,183
n = 37    3,109,500,884,389
n = 38    6,219,001,768,781
n = 39   12,438,003,537,571
n = 40   24,876,007,075,181
n = 41   49,752,014,150,467
n = 42   99,504,028,301,131
```

## Fortran

Fortran does not allow to modify the index inside the loop.

`do i=1,10  write(*,*) i  i=i+1end do`
```Error - I is currently being used as a DO or implied DO control variable
Compilation failed.
```

### Fortran 95

`! Loops Increment loop index within loop body - 17/07/2018      integer*8 n      imax=42      i=0; n=42      Do While(i<imax)        If (isprime(n)==1) Then          i=i+1          Write (*,'(I2,1X,I20)') i,n          n=n+n-1        EndIf        n=n+1      EndDo      End       Function isprime(n)        integer*8 n,i        If (n==2 .OR. n==3) Then          isprime=1          return        ElseIf (Mod(n,2)==0 .OR. Mod(n,3)==0) Then          isprime=0          return        Else          i=5          Do While(i*i<=n)            If (Mod(n,i)==0 .OR. Mod(n,i+2)==0) Then              isprime=0              return            EndIf            i=i+6          EndDo          isprime=1          return        EndIf      EndFunction`
Output:
``` 1                   43
2                   89
3                  179
4                  359
5                  719
6                 1439
7                 2879
8                 5779
9                11579
10                23159
11                46327
12                92657
13               185323
14               370661
15               741337
16              1482707
17              2965421
18              5930887
19             11861791
20             23723597
21             47447201
22             94894427
23            189788857
24            379577741
25            759155483
26           1518310967
27           3036621941
28           6073243889
29          12146487779
30          24292975649
31          48585951311
32          97171902629
33         194343805267
34         388687610539
35         777375221081
36        1554750442183
37        3109500884389
38        6219001768781
39       12438003537571
40       24876007075181
41       49752014150467
42       99504028301131
```

### Fortran IV

The limit is set to 25 due to the size of integer in Fortran IV.

`C LOOPS INCREMENT LOOP INDEX WITHIN LOOP BODY - 17/07/2018      IMAX=25      I=0      N=42  10  IF(I.GE.IMAX)GOTO 30        IF(ISPRIME(N).NE.1)GOTO 20          I=I+1          WRITE(*,301) I,N 301      FORMAT(I2,1X,I10)          N=N+N-1  20    N=N+1      GOTO 10  30  CONTINUE      END       FUNCTION ISPRIME(M)        IF(M.NE.2 .AND. M.NE.3)GOTO 10          ISPRIME=1          RETURN  10    IF(MOD(M,2).NE.0 .AND. MOD(M,3).NE.0)GOTO 20          ISPRIME=0          RETURN  20      I=5  30      IF(I*I.GT.M)GOTO 50            IF(MOD(M,I).NE.0 .AND. MOD(M,I+2).NE.0)GOTO 40              ISPRIME=0              RETURN  40        I=I+6          GOTO 30   50      ISPRIME=1          RETURN      END`
Output:
``` 1         43
2         89
3        179
4        359
5        719
6       1439
7       2879
8       5779
9      11579
10      23159
11      46327
12      92657
13     185323
14     370661
15     741337
16    1482707
17    2965421
18    5930887
19   11861791
20   23723597
21   47447201
22   94894427
23  189788857
24  379577741
25  759155483
```

## FreeBASIC

`' version 18-01-2019' compile with: fbc -s console Function isprime(number As ULongInt) As UInteger     If number Mod 2 = 0 Then Return 0    If number Mod 3 = 0 Then Return 0    Dim As UInteger i, max = Sqr(number)     For i = 5 To max Step 2        If number Mod i = 0 Then Return 0    Next     Return 1 End Function ' ------=< MAIN >=------ Dim As UInteger counterDim As ULongInt i Print : Printcounter = 0For i = 42 To &HFFFFFFFFFFFFFFFF    ' for next loop, loop maximum = 2^64-1    If isprime(i) Then        counter += 1        Print Using "n =### ##################,"; counter; i        If counter >= 42 Then Exit for        i += i -1    End IfNext ' empty keyboard bufferWhile InKey <> "" : WendPrint : Print "hit any key to end program"SleepEnd`
Output:
```n =  1                  43
n =  2                  89
n =  3                 179
n =  4                 359
n =  5                 719
n =  6               1,439
n =  7               2,879
n =  8               5,779
n =  9              11,579
n = 10              23,159
n = 11              46,327
n = 12              92,657
n = 13             185,323
n = 14             370,661
n = 15             741,337
n = 16           1,482,707
n = 17           2,965,421
n = 18           5,930,887
n = 19          11,861,791
n = 20          23,723,597
n = 21          47,447,201
n = 22          94,894,427
n = 23         189,788,857
n = 24         379,577,741
n = 25         759,155,483
n = 26       1,518,310,967
n = 27       3,036,621,941
n = 28       6,073,243,889
n = 29      12,146,487,779
n = 30      24,292,975,649
n = 31      48,585,951,311
n = 32      97,171,902,629
n = 33     194,343,805,267
n = 34     388,687,610,539
n = 35     777,375,221,081
n = 36   1,554,750,442,183
n = 37   3,109,500,884,389
n = 38   6,219,001,768,781
n = 39  12,438,003,537,571
n = 40  24,876,007,075,181
n = 41  49,752,014,150,467
n = 42  99,504,028,301,131```

## Go

This uses Go's 'for' loop but is otherwise similar to the Kotlin entry.

The 'thousands separator' aspect is dealt with by a couple of external packages (in the 'import' declarations) which can be installed using 'go get'.

`package main import(    "golang.org/x/text/language"    "golang.org/x/text/message") func isPrime(n uint64) bool {    if n % 2 == 0 {        return n == 2    }    if n % 3 == 0 {        return n == 3    }    d := uint64(5)    for d * d <= n {        if n % d == 0 {            return false        }        d += 2        if n % d == 0 {            return false        }         d += 4    }    return true} const limit = 42 func main() {    p := message.NewPrinter(language.English)    for i, n := uint64(limit), 0; n < limit; i++ {        if isPrime(i) {            n++            p.Printf("n = %-2d  %19d\n", n, i)            i += i - 1        }    }}`
Output:
```Same as Kotlin entry
```

No index mutations or loops. Recursion is used.

`import Data.Listimport Control.Monad (guard) isPrime :: Int -> BoolisPrime n  | n <= 3 = n > 1  | n `mod` 2 == 0 || n `mod` 3 == 0 = False  | otherwise = l2 5 n  where l2 d n = x > n || l3 d n          where x = d * d                l3 d n                  | n `mod` d == 0       = False                  | n `mod` (d + 2) == 0 = False                  | otherwise = l2 (d + 6) n showPrime :: Int -> Int -> [(Int, Int)]showPrime i n = if isPrime i                then (n, i) : showPrime (i+i) (n+1)                else showPrime (i+1) n digitGroup :: Int -> StringdigitGroup = intercalate "," . reverse . map show . unfoldr (\n -> guard (n /= 0) >> pure (n `mod` 1000, n `div` 1000)) display :: (Int, Int) -> Stringdisplay (i, p) = show i ++ " " ++ digitGroup p main = mapM_ (putStrLn . display) \$ take 42 \$ showPrime 42 1`
Output:
```1 43
2 89
3 179
4 359
5 719
6 1,439
7 2,879
8 5,779
9 11,579
10 23,159
11 46,327
12 92,657
13 185,323
14 370,661
15 741,337
16 1,482,707
17 2,965,421
18 5,930,887
19 11,861,791
20 23,723,597
21 47,447,201
22 94,894,427
23 189,788,857
24 379,577,741
25 759,155,483
26 1,518,310,967
27 3,36,621,941
28 6,73,243,889
29 12,146,487,779
30 24,292,975,649
31 48,585,951,311
32 97,171,902,629
33 194,343,805,267
34 388,687,610,539
35 777,375,221,81
36 1,554,750,442,183
37 3,109,500,884,389
38 6,219,1,768,781
39 12,438,3,537,571
40 24,876,7,75,181
41 49,752,14,150,467
42 99,504,28,301,131
```

And for minor variation, we could import isPrime from Data.Numbers.Primes, and define the comma-grouping of large integers in terms of chunksof:

`import Data.Numbers.Primesimport Data.List (intercalate)import Data.List.Split (chunksOf) series :: Integer -> Integer -> [(Integer, Integer)]series = go  where    go i n      | isPrime i = (n, i) : go (i + i) (succ n)      | otherwise = go (succ i) n showPair :: (Integer, Integer) -> StringshowPair (i, n) = show i ++ " -> " ++ showInteger n showInteger :: Integer -> StringshowInteger = reverse . intercalate "," . chunksOf 3 . reverse . show main :: IO ()main = mapM_ (putStrLn . showPair) (take 42 \$ series 42 1)`

## Haxe

Haxe's for-loop does allow the index to be modified in the body of the loop, so a while-loop is used instead.

`using StringTools;import haxe.Int64; class PrimeNumberLoops {  private static var limit = 42;   static function isPrime(i:Int64):Bool {    if (i == 2 || i == 3) {      return true;    } else if (i % 2 == 0 || i % 3 ==0) {      return false;    }    var idx:haxe.Int64 = 5;    while (idx * idx <= i) {      if (i % idx == 0) return false;      idx += 2;      if (i % idx == 0) return false;      idx += 4;    }    return true;  }   static function main() {    var i:Int64 = 42;    var n:Int64 = 0;    while (n < limit) {      if (isPrime(i)) {        n++;        Sys.println('n \${Int64.toStr(n).lpad(' ', 2)} ' +                    '= \${Int64.toStr(i).lpad(' ', 19)}');        i += i;        continue;      }      i++;    }  }}`
Output:
```n  1 =                  43
n  2 =                  89
n  3 =                 179
n  4 =                 359
n  5 =                 719
n  6 =                1439
n  7 =                2879
n  8 =                5779
n  9 =               11579
n 10 =               23159
n 11 =               46327
n 12 =               92657
n 13 =              185323
n 14 =              370661
n 15 =              741337
n 16 =             1482707
n 17 =             2965421
n 18 =             5930887
n 19 =            11861791
n 20 =            23723597
n 21 =            47447201
n 22 =            94894427
n 23 =           189788857
n 24 =           379577741
n 25 =           759155483
n 26 =          1518310967
n 27 =          3036621941
n 28 =          6073243889
n 29 =         12146487779
n 30 =         24292975649
n 31 =         48585951311
n 32 =         97171902629
n 33 =        194343805267
n 34 =        388687610539
n 35 =        777375221081
n 36 =       1554750442183
n 37 =       3109500884389
n 38 =       6219001768781
n 39 =      12438003537571
n 40 =      24876007075181
n 41 =      49752014150467
n 42 =      99504028301131
```

## J

Fun with j. The verb tacit_loop implements the computation.

` tacit_loop =: _1&(>:@:{`[`]})@:(, (1&p: # _1 2&p.)@:{:)@:]^:(0 ~: (>: #))^:_ x: `

Now derive it from the python solution. The monadic verb loop fairly straightforwardly matches the python solution except that loop returns the vector of computed values rather than displays them.

` isPrime =: 1&p:assert 1 1 0 -: isPrime 2 3 4   NB. test and example loop =: verb define i =. x: y n =. i. 0 while. y > # n do.  if. isPrime i do.   n =. n , i   i =. _1 2 p. i  end.  i =. i + 1 end. n ) `

Store the vector of indexes using its tail as the current index, removing the `n' variable. In doing so the last item of `i' is not part of the solution, hence change less than to less or equal, and discard the tail value. Also extract the conversion to extended precision x: .

` loop =: verb [email protected]:x: i =. y while. y >: # i do.  if. isPrime {: i do.   i =. (, _1 2 p. {:) i  end.  i =. _1 (>:@:{)`[`]} i end. }: i) `

Replace the "if" statement with a computation. This one works by appending onto the solution vector isPrime copies of the proposed new index.

` loop =: verb [email protected]:x: i =. y while. y >: # i do.  i =. (, (isPrime # _1 2&p.)@:{:) i  i =. _1 (>:@:{)`[`]} i end. }: i) `

Names are an issue brought forth in the j forums. Names have most meaning to the person who wrote them, so there's a bit of J philosophy that says "show the code". J doesn't enforce "code only", and definitions can encapsulate useful chunks of code. If the names I've chosen don't work in your experience or language you could replace them with `a' and `b'.

` save_if_prime =: , (isPrime # _1 2&p.)@:{:increment_tail =: _1&(>:@:{`[`]}) loop =: verb [email protected]:x: i =. y while. y >: # i do.  i =. save_if_prime i  i =. increment_tail i end. }: i) `

Why make two assignments when j can increment at save?

` loop =: verb [email protected]:x: i =. y while. y >: # i do.  i =. [email protected]:save_if_prime i end. }: i) `

Next replace the while loop with double application of J's generalized power conjunction.

` While =: conjunction def 'u^:(0~:v)^:_' loop =: verb [email protected]:x: i =. y }: [email protected]:save_if_prime While(y >: #) i) `

By inspection the variable `i' doesn't contribute anything useful whatsoever. The verb's argument, y, remains. Finally, implemented as an hook verb trains with 'y' and `i' as left ([) and right (]) arguments the complete definitions for tacit_loop are

` isPrime =: 1&p:save_if_prime =: , (isPrime # _1 2&p.)@:{:increment_tail =: _1&(>:@:{`[`]})While =: conjunction def 'u^:(0~:v)^:_'tacit_loop =: [: }: ([email protected]:[email protected]:]While(>: #) x:) `

Include the index numbers with demonstration:

`    9!:37 ] 0 2048 0 222  NB. output control permit lines of 2^11 columns    (>:@:i. ,: tacit_loop) 42 1  2   3   4   5    6    7    8     9    10    11    12     13     14     15      16      17      18       19       20       21       22        23        24        25         26         27         28          29          30          31          32           33           34           35            36            37            38             39             40             41             4243 89 179 359 719 1439 2879 5779 11579 23159 46327 92657 185323 370661 741337 1482707 2965421 5930887 11861791 23723597 47447201 94894427 189788857 379577741 759155483 1518310967 3036621941 6073243889 12146487779 24292975649 48585951311 97171902629 194343805267 388687610539 777375221081 1554750442183 3109500884389 6219001768781 12438003537571 24876007075181 49752014150467 99504028301131     NB. fix the definition.  Here's the code.   tacit_loop f.[: }: (_1&(>:@:{`[`]})@:(, (1&p: # _1 2&p.)@:{:)@:]^:(0 ~: (>: #))^:_ x:)  `
If the loop must require the output side effect, this save_if_prime definition does the trick. Without the output hook it is probably more efficient than the copying version because it evaluates the hook
`(, _1 2&[email protected]:{:)`
only when isPrime is true.
`    extra_credit =: ([: }. ,@(',' ,.~ _3 [\ ])&.|[email protected]:":)&>   show =: [ ([: [email protected]:[email protected]:({. , ' ' , {:)@:extra_credit # , {:)   save_if_prime =: (, _1 2&[email protected]:{:)@:show^:([email protected]:{:)   [email protected]:tacit_loop 421 432 893 1794 3595 7196 1,4397 2,8798 5,7799 11,57910 23,15911 46,32712 92,65713 185,32314 370,66115 741,33716 1,482,70717 2,965,42118 5,930,88719 11,861,79120 23,723,59721 47,447,20122 94,894,42723 189,788,85724 379,577,74125 759,155,48326 1,518,310,96727 3,036,621,94128 6,073,243,88929 12,146,487,77930 24,292,975,64931 48,585,951,31132 97,171,902,62933 194,343,805,26734 388,687,610,53935 777,375,221,08136 1,554,750,442,18337 3,109,500,884,38938 6,219,001,768,78139 12,438,003,537,57140 24,876,007,075,18141 49,752,014,150,46742 99,504,028,301,131 `

## Java

The following uses a 'for' rather than a 'do/while' loop but otherwise is similar to the Kotlin entry.

`public class LoopIncrementWithinBody {     static final int LIMIT = 42;     static boolean isPrime(long n) {        if (n % 2 == 0) return n == 2;        if (n % 3 == 0) return n == 3;        long d = 5;        while (d * d <= n) {            if (n % d == 0) return false;            d += 2;            if (n % d == 0) return false;            d += 4;        }        return true;    }     public static void main(String[] args) {        long i;        int n;        for (i = LIMIT, n = 0; n < LIMIT; i++)            if (isPrime(i)) {                n++;                System.out.printf("n = %-2d  %,19d\n", n, i);                i += i - 1;            }    }}`
Output:
```Same as Kotlin entry
```

## jq

Works with: jq

Works with gojq, the Go implementation of jq

jq's looping constructs that have a loop index do not allow that index to be modified within the loop as such indices are "read-only", but all the looping constructs allow an index to be be defined and modified, as illustrated by the following example, which uses "i" as the loop index.

This entry uses the jq implementation of is_prime as shown at Erdős-primes#jq.

`{i:42, count:0}| while( .count <= 42;    .emit = null    | .i += 1    | if .i|is_prime       then      .count += 1      | .emit = "count at \(.i) is \(.count)"      | .i = .i + .i - 1      else .      end )| select(.emit).emit`
Output:
```count at 43 is 1
count at 89 is 2
count at 179 is 3
count at 359 is 4
count at 719 is 5
count at 1439 is 6
count at 2879 is 7
count at 5779 is 8
count at 11579 is 9
count at 23159 is 10
count at 46327 is 11
count at 92657 is 12
count at 185323 is 13
count at 370661 is 14
count at 741337 is 15
count at 1482707 is 16
count at 2965421 is 17
count at 5930887 is 18
count at 11861791 is 19
count at 23723597 is 20
count at 47447201 is 21
count at 94894427 is 22
count at 189788857 is 23
count at 379577741 is 24
count at 759155483 is 25
count at 1518310967 is 26
count at 3036621941 is 27
count at 6073243889 is 28
count at 12146487779 is 29
count at 24292975649 is 30
count at 48585951311 is 31
count at 97171902629 is 32
count at 194343805267 is 33
count at 388687610539 is 34
count at 777375221081 is 35
count at 1554750442183 is 36
count at 3109500884389 is 37
count at 6219001768781 is 38
count at 12438003537571 is 39
count at 24876007075181 is 40
count at 49752014150467 is 41
count at 99504028301131 is 42
```

## Julia

Julia's `for` loop iterator is an iterator type which cannot be incremented as a simple variable would to change looping.

`using Primes, Formatting function doublemyindex(n=42)    shown = 0    i = BigInt(n)    while shown < n        if isprime(i + 1)            shown += 1            println("The index is ", format(shown, commas=true), " and ",                                      format(i + 1, commas=true), " is prime.")            i += i        end        i += 1    endend doublemyindex() `
Output:
```
The index is 1 and 43 is prime.
The index is 2 and 89 is prime.
The index is 3 and 179 is prime.
The index is 4 and 359 is prime.
The index is 5 and 719 is prime.
The index is 6 and 1,439 is prime.
The index is 7 and 2,879 is prime.
The index is 8 and 5,779 is prime.
The index is 9 and 11,579 is prime.
The index is 10 and 23,159 is prime.
The index is 11 and 46,327 is prime.
The index is 12 and 92,657 is prime.
The index is 13 and 185,323 is prime.
The index is 14 and 370,661 is prime.
The index is 15 and 741,337 is prime.
The index is 16 and 1,482,707 is prime.
The index is 17 and 2,965,421 is prime.
The index is 18 and 5,930,887 is prime.
The index is 19 and 11,861,791 is prime.
The index is 20 and 23,723,597 is prime.
The index is 21 and 47,447,201 is prime.
The index is 22 and 94,894,427 is prime.
The index is 23 and 189,788,857 is prime.
The index is 24 and 379,577,741 is prime.
The index is 25 and 759,155,483 is prime.
The index is 26 and 1,518,310,967 is prime.
The index is 27 and 3,036,621,941 is prime.
The index is 28 and 6,073,243,889 is prime.
The index is 29 and 12,146,487,779 is prime.
The index is 30 and 24,292,975,649 is prime.
The index is 31 and 48,585,951,311 is prime.
The index is 32 and 97,171,902,629 is prime.
The index is 33 and 194,343,805,267 is prime.
The index is 34 and 388,687,610,539 is prime.
The index is 35 and 777,375,221,081 is prime.
The index is 36 and 1,554,750,442,183 is prime.
The index is 37 and 3,109,500,884,389 is prime.
The index is 38 and 6,219,001,768,781 is prime.
The index is 39 and 12,438,003,537,571 is prime.
The index is 40 and 24,876,007,075,181 is prime.
The index is 41 and 49,752,014,150,467 is prime.
The index is 42 and 99,504,028,301,131 is prime.

```

## Kotlin

Unlike many other C-family languages (notably Java), Kotlin's 'for' statement doesn't allow either the iteration variable or the step to be modified within the loop body.

So instead we use a do/while loop here which has no such restrictions.

`// version 1.2.60 fun isPrime(n: Long): Boolean {    if (n % 2L == 0L) return n == 2L    if (n % 3L == 0L) return n == 3L    var d = 5L    while (d * d <= n) {        if (n % d == 0L) return false        d += 2L        if (n % d == 0L) return false        d += 4L    }    return true} fun main(args: Array<String>) {    var i = 42L    var n = 0    do {        if (isPrime(i)) {            n++            System.out.printf("n = %-2d  %,19d\n", n, i)            i += i - 1        }        i++    }    while (n < 42)}`
Output:
```n = 1                    43
n = 2                    89
n = 3                   179
n = 4                   359
n = 5                   719
n = 6                 1,439
n = 7                 2,879
n = 8                 5,779
n = 9                11,579
n = 10               23,159
n = 11               46,327
n = 12               92,657
n = 13              185,323
n = 14              370,661
n = 15              741,337
n = 16            1,482,707
n = 17            2,965,421
n = 18            5,930,887
n = 19           11,861,791
n = 20           23,723,597
n = 21           47,447,201
n = 22           94,894,427
n = 23          189,788,857
n = 24          379,577,741
n = 25          759,155,483
n = 26        1,518,310,967
n = 27        3,036,621,941
n = 28        6,073,243,889
n = 29       12,146,487,779
n = 30       24,292,975,649
n = 31       48,585,951,311
n = 32       97,171,902,629
n = 33      194,343,805,267
n = 34      388,687,610,539
n = 35      777,375,221,081
n = 36    1,554,750,442,183
n = 37    3,109,500,884,389
n = 38    6,219,001,768,781
n = 39   12,438,003,537,571
n = 40   24,876,007,075,181
n = 41   49,752,014,150,467
n = 42   99,504,028,301,131```

Although Kotlin is predominantly an object-oriented/procedural language, it does have some features which enable one to program in a functional style. These features include 'tail recursion' which, of course, is commonly used in place of loops in purely functional languages.

In such cases, the Kotlin compiler optimizes out the recursion, leaving behind a fast and efficient loop based version instead.

The following version uses a tail recursive function rather than a while loop to achieve the same effect:

`// version 1.2.60 fun isPrime(n: Long): Boolean {    if (n % 2L == 0L) return n == 2L    if (n % 3L == 0L) return n == 3L    var d = 5L    while (d * d <= n) {        if (n % d == 0L) return false        d += 2L        if (n % d == 0L) return false        d += 4L    }    return true} tailrec fun loop(index: Long, numPrimes: Int) {    if (numPrimes == 42) return    var i = index    var n = numPrimes     if (isPrime(i)) {        n++        System.out.printf("n = %-2d  %,19d\n", n, i)        loop(2 * i - 1, n)    }    else loop(++i, n)} fun main(args: Array<String>) {        loop(42, 0)}`
Output:
```Same as 'while' loop version.
```

## Ksh

` #!/bin/ksh # Increment loop index within loop body #	# Variables:#integer INDX_START=42 N_PRIMES=42 #	# Functions:# #	# Function _isprime(n) return 1 for prime, 0 for not prime#function _isprime {	typeset _n ; integer _n=\$1	typeset _i ; integer _i 	(( _n < 2 )) && return 0	for (( _i=2 ; _i*_i<=_n ; _i++ )); do		(( ! ( _n % _i ) )) && return 0	done	return 1}  ####### main # ######integer i n=0for ((i=INDX_START; n<N_PRIMES; i++)); do	_isprime \${i}	if (( \$? )); then		printf "%,18d is prime, %2d primes found(so far)\n" \${i} \$((++n))		(( i+=\$i ))	fidone`
Output:
```
43 is prime,  1 primes found(so far)
89 is prime,  2 primes found(so far)
179 is prime,  3 primes found(so far)
359 is prime,  4 primes found(so far)
719 is prime,  5 primes found(so far)
1,439 is prime,  6 primes found(so far)
2,879 is prime,  7 primes found(so far)
5,779 is prime,  8 primes found(so far)
11,579 is prime,  9 primes found(so far)
23,159 is prime, 10 primes found(so far)
46,327 is prime, 11 primes found(so far)
92,657 is prime, 12 primes found(so far)
185,323 is prime, 13 primes found(so far)
370,661 is prime, 14 primes found(so far)
741,337 is prime, 15 primes found(so far)
1,482,707 is prime, 16 primes found(so far)
2,965,421 is prime, 17 primes found(so far)
5,930,887 is prime, 18 primes found(so far)
11,861,791 is prime, 19 primes found(so far)
23,723,597 is prime, 20 primes found(so far)
47,447,201 is prime, 21 primes found(so far)
94,894,427 is prime, 22 primes found(so far)
189,788,857 is prime, 23 primes found(so far)
379,577,741 is prime, 24 primes found(so far)
759,155,483 is prime, 25 primes found(so far)
1,518,310,967 is prime, 26 primes found(so far)
3,036,621,941 is prime, 27 primes found(so far)
6,073,243,889 is prime, 28 primes found(so far)
12,146,487,779 is prime, 29 primes found(so far)
24,292,975,649 is prime, 30 primes found(so far)
48,585,951,311 is prime, 31 primes found(so far)
97,171,902,629 is prime, 32 primes found(so far)
194,343,805,267 is prime, 33 primes found(so far)
388,687,610,539 is prime, 34 primes found(so far)
777,375,221,081 is prime, 35 primes found(so far)
1,554,750,442,183 is prime, 36 primes found(so far)
3,109,500,884,389 is prime, 37 primes found(so far)
6,219,001,768,781 is prime, 38 primes found(so far)

12,438,003,537,571 is prime, 39 primes found(so far)
24,876,007,075,181 is prime, 40 primes found(so far)
49,752,014,150,467 is prime, 41 primes found(so far)

99,504,028,301,131 is prime, 42 primes found(so far)```

## Lua

`-- Returns boolean indicate whether x is primefunction isPrime (x)  if x < 2 then return false end  if x < 4 then return true end  if x % 2 == 0 then return false end  for d = 3, math.sqrt(x), 2 do    if x % d == 0 then return false end  end  return trueend -- Main procedurelocal n, i = 0, 42while n < 42 do  if isPrime(i) then    n = n + 1    print("n = " .. n, i)    i = 2 * i - 1  end  i = i + 1end`
Output:
```n = 1   43
n = 2   89
n = 3   179
n = 4   359
n = 5   719
n = 6   1439
n = 7   2879
n = 8   5779
n = 9   11579
n = 10  23159
n = 11  46327
n = 12  92657
n = 13  185323
n = 14  370661
n = 15  741337
n = 16  1482707
n = 17  2965421
n = 18  5930887
n = 19  11861791
n = 20  23723597
n = 21  47447201
n = 22  94894427
n = 23  189788857
n = 24  379577741
n = 25  759155483
n = 26  1518310967
n = 27  3036621941
n = 28  6073243889
n = 29  12146487779
n = 30  24292975649
n = 31  48585951311
n = 32  97171902629
n = 33  194343805267
n = 34  388687610539
n = 35  777375221081
n = 36  1554750442183
n = 37  3109500884389
n = 38  6219001768781
n = 39  12438003537571
n = 40  24876007075181
n = 41  49752014150467
n = 42  99504028301131```

## M2000 Interpreter

` Module CheckIt {      Function IsPrime (x) {            if x<=5 OR frac(x) then {                  if x = 2 OR x = 3 OR x = 5 then =true                  Break            }            if x mod 2 else exit            if x mod 3 else exit            x1=sqrt(x): [email protected]            {if x mod d else exit                  d += [email protected]: if d>x1 then =true : exit                  if x mod d else exit                  d += [email protected]: if d<= x1 else =true: exit                  loop             }      }      \\ For Next loops or For {} loops can't change iterator variable (variable has a copy of real iterator)      \\ In those loops we have to use Continue to skip lines and repeat the loop.      \\ so we have to use Block iterator, using Loop which set a flag current block to repeat itself once.      def long Limit=42, n      def decimal i      i=Limit      {            if n<Limit Else exit            if isPrime(i)  then n++ : Print format\$("n={0::2}: {1:-20}", n, str\$(i,"#,###")) : i+=i-1            i++            loop       }}CheckIt `
Output:
```Same as Kotlin entry
```

## Maple

A translation of Kotlin entry

`i := 42:count := 0:while(count < 42) do	i := i+1:	if type(i,prime) then		count := count + 1:		printf("n=%-2d     %19d\n", count,i):		i := 2*i -1:	end if:end do:`
Output:
```n=1                       43
n=2                       89
n=3                      179
n=4                      359
n=5                      719
n=6                     1439
n=7                     2879
n=8                     5779
n=9                    11579
n=10                   23159
n=11                   46327
n=12                   92657
n=13                  185323
n=14                  370661
n=15                  741337
n=16                 1482707
n=17                 2965421
n=18                 5930887
n=19                11861791
n=20                23723597
n=21                47447201
n=22                94894427
n=23               189788857
n=24               379577741
n=25               759155483
n=26              1518310967
n=27              3036621941
n=28              6073243889
n=29             12146487779
n=30             24292975649
n=31             48585951311
n=32             97171902629
n=33            194343805267
n=34            388687610539
n=35            777375221081
n=36           1554750442183
n=37           3109500884389
n=38           6219001768781
n=39          12438003537571
n=40          24876007075181
n=41          49752014150467
n=42          99504028301131```

## Mathematica / Wolfram Language

`{i, n} = {42, 0};While[n < 42, If[PrimeQ[i],  Print["n=", n++, "\t", i];  i += i - 1;  ]; i++; ]`
Output:
```n=0	43
n=1	89
n=2	179
n=3	359
n=4	719
n=5	1439
n=6	2879
n=7	5779
n=8	11579
n=9	23159
n=10	46327
n=11	92657
n=12	185323
n=13	370661
n=14	741337
n=15	1482707
n=16	2965421
n=17	5930887
n=18	11861791
n=19	23723597
n=20	47447201
n=21	94894427
n=22	189788857
n=23	379577741
n=24	759155483
n=25	1518310967
n=26	3036621941
n=27	6073243889
n=28	12146487779
n=29	24292975649
n=30	48585951311
n=31	97171902629
n=32	194343805267
n=33	388687610539
n=34	777375221081
n=35	1554750442183
n=36	3109500884389
n=37	6219001768781
n=38	12438003537571
n=39	24876007075181
n=40	49752014150467
n=41	99504028301131```

## Microsoft Small Basic

Small Basic allows to modify the index inside the loop.

`'Loops Increment loop index within loop body - 16/07/2018imax=42i=0n=42While i<imax  isprime_n()  If ret_isprime_n Then    i=i+1    format_i()    format_n()    TextWindow.WriteLine("i="+ret_format_i+" : "+ret_format_n)    n=n+n-1  EndIf  n=n+1EndWhile Sub isprime_n   If n=2 Or n=3 Then    ret_isprime_n="True"  ElseIf Math.Remainder(n,2)=0 Or Math.Remainder(n,3)=0 Then     ret_isprime_n="False"  Else    j=5    While j*j<=n      If Math.Remainder(n,j)=0 Or Math.Remainder(n,j+2)=0 Then         ret_isprime_n="False"        Goto exitsub      EndIf      j=j+6    EndWhile    ret_isprime_n="True"  EndIfexitsub:EndSub 'isprime_n Sub format_i  ret_format_i=Text.GetSubText("   ",1,3-Text.GetLength(i))+iEndSub 'format_i Sub format_n  nn=""   l=-1  For k=Text.GetLength(n) To 1 Step -1    l=l+1    cc=Text.GetSubText(n,k,1)    If l=3 Then      cv=","      l=0    Else      cv=""    EndIf    nn=Text.Append(cc,Text.Append(cv,nn))  EndFor  space="                    "  nn=Text.GetSubText(space,1,Text.GetLength(space)-Text.GetLength(nn))+nn  ret_format_n=nnEndSub 'format_n`
Output:
```i= 1 :                   43
i= 2 :                   89
i= 3 :                  179
i= 4 :                  359
i= 5 :                  719
i= 6 :                1,439
i= 7 :                2,879
i= 8 :                5,779
i= 9 :               11,579
i=10 :               23,159
i=11 :               46,327
i=12 :               92,657
i=13 :              185,323
i=14 :              370,661
i=15 :              741,337
i=16 :            1,482,707
i=17 :            2,965,421
i=18 :            5,930,887
i=19 :           11,861,791
i=20 :           23,723,597
i=21 :           47,447,201
i=22 :           94,894,427
i=23 :          189,788,857
i=24 :          379,577,741
i=25 :          759,155,483
i=26 :        1,518,310,967
i=27 :        3,036,621,941
i=28 :        6,073,243,889
i=29 :       12,146,487,779
i=30 :       24,292,975,649
i=31 :       48,585,951,311
i=32 :       97,171,902,629
i=33 :      194,343,805,267
i=34 :      388,687,610,539
i=35 :      777,375,221,081
i=36 :    1,554,750,442,183
i=37 :    3,109,500,884,389
i=38 :    6,219,001,768,781
i=39 :   12,438,003,537,571
i=40 :   24,876,007,075,181
i=41 :   49,752,014,150,467
i=42 :   99,504,028,301,131
```

## Nanoquery

Translation of: Java
`limit = 42 def isPrime(n)    if ((n % 2) = 0) or ((n % 3) = 0)        return false    end    d = 5    while (d * d) <= n        if (n % d) = 0            return false        end        d += 2        if (n % d) = 0            return false        end        d += 4    end    return trueend i = limitfor (n = 0) (n < limit) (i += 1)    if isPrime(i)        n += 1        print format("n = %-2d  %,19d\n", n, i)        i += i - 1    endend`
Output:
```n = 1                    43
n = 2                    89
n = 3                   179
n = 4                   359
n = 5                   719
n = 6                 1,439
n = 7                 2,879
n = 8                 5,779
n = 9                11,579
n = 10               23,159
n = 11               46,327
n = 12               92,657
n = 13              185,323
n = 14              370,661
n = 15              741,337
n = 16            1,482,707
n = 17            2,965,421
n = 18            5,930,887
n = 19           11,861,791
n = 20           23,723,597
n = 21           47,447,201
n = 22           94,894,427
n = 23          189,788,857
n = 24          379,577,741
n = 25          759,155,483
n = 26        1,518,310,967
n = 27        3,036,621,941
n = 28        6,073,243,889
n = 29       12,146,487,779
n = 30       24,292,975,649
n = 31       48,585,951,311
n = 32       97,171,902,629
n = 33      194,343,805,267
n = 34      388,687,610,539
n = 35      777,375,221,081
n = 36    1,554,750,442,183
n = 37    3,109,500,884,389
n = 38    6,219,001,768,781
n = 39   12,438,003,537,571
n = 40   24,876,007,075,181
n = 41   49,752,014,150,467
n = 42   99,504,028,301,131```

## NewLISP

` #! /usr/local/bin/newlisp (define (prime? n) (and    (set 'lst (factor n))   (= (length lst) 1))) (define (thousands_separator i)    (setq i (string i))    (setq len (length i))    (setq i (reverse (explode i)))    (setq o "")    (setq count3 0)    (dolist (x i)        (setq o (string o x))        (inc count3)        (if (and (= 3 count3) (< (+ \$idx 1) len))            (begin            (setq o (string o "_"))            (setq count3 0))))     (reverse o))  ;- - - Main begins here(setq i 42)(setq n 0)(while (< n 42)    (if (prime? i)        (begin            (inc n)            (println (string "n = " n " -> " (thousands_separator i)))            (setq i (+ i i -1))))    (inc i)        ) (exit) `
```n = 1 -> 43
n = 2 -> 89
n = 3 -> 179
n = 4 -> 359
n = 5 -> 719
n = 6 -> 1_439
n = 7 -> 2_879
n = 8 -> 5_779
n = 9 -> 11_579
n = 10 -> 23_159
n = 11 -> 46_327
n = 12 -> 92_657
n = 13 -> 185_323
n = 14 -> 370_661
n = 15 -> 741_337
n = 16 -> 1_482_707
n = 17 -> 2_965_421
n = 18 -> 5_930_887
n = 19 -> 11_861_791
n = 20 -> 23_723_597
n = 21 -> 47_447_201
n = 22 -> 94_894_427
n = 23 -> 189_788_857
n = 24 -> 379_577_741
n = 25 -> 759_155_483
n = 26 -> 1_518_310_967
n = 27 -> 3_036_621_941
n = 28 -> 6_073_243_889
n = 29 -> 12_146_487_779
n = 30 -> 24_292_975_649
n = 31 -> 48_585_951_311
n = 32 -> 97_171_902_629
n = 33 -> 194_343_805_267
n = 34 -> 388_687_610_539
n = 35 -> 777_375_221_081
n = 36 -> 1_554_750_442_183
n = 37 -> 3_109_500_884_389
n = 38 -> 6_219_001_768_781
n = 39 -> 12_438_003_537_571
n = 40 -> 24_876_007_075_181
n = 41 -> 49_752_014_150_467
n = 42 -> 99_504_028_301_131

```

## Nim

In Nim, loop index is read-only, so we have to use a normal variable and increment it as needed.

` import strformatfrom strutils import insertSep func isPrime(i: int): bool =  if i == 2 or i == 3: return true  elif i mod 2 == 0 or i mod 3 == 0: return false  var idx = 5  while idx*idx <= i:    if i mod idx == 0: return false    idx.inc 2    if i mod idx == 0: return false    idx.inc 4  result = true const limit = 42proc main =  var    i = 42    n = 0  while n < limit:    if i.isPrime:      inc n      echo &"""n {n:>2} = {(\$i).insertSep(sep=','):>19}"""      i.inc i      continue    inc i main() `
Output:
```n  1 =                  43
n  2 =                  89
n  3 =                 179
n  4 =                 359
n  5 =                 719
n  6 =               1,439
n  7 =               2,879
n  8 =               5,779
n  9 =              11,579
n 10 =              23,159
n 11 =              46,327
n 12 =              92,657
n 13 =             185,323
n 14 =             370,661
n 15 =             741,337
n 16 =           1,482,707
n 17 =           2,965,421
n 18 =           5,930,887
n 19 =          11,861,791
n 20 =          23,723,597
n 21 =          47,447,201
n 22 =          94,894,427
n 23 =         189,788,857
n 24 =         379,577,741
n 25 =         759,155,483
n 26 =       1,518,310,967
n 27 =       3,036,621,941
n 28 =       6,073,243,889
n 29 =      12,146,487,779
n 30 =      24,292,975,649
n 31 =      48,585,951,311
n 32 =      97,171,902,629
n 33 =     194,343,805,267
n 34 =     388,687,610,539
n 35 =     777,375,221,081
n 36 =   1,554,750,442,183
n 37 =   3,109,500,884,389
n 38 =   6,219,001,768,781
n 39 =  12,438,003,537,571
n 40 =  24,876,007,075,181
n 41 =  49,752,014,150,467
n 42 =  99,504,028,301,131
```

## Perl

Messing with the loop iterator value doesn't go well in Perl, so use the while loop alternative. The `ntheory` module is used to test for primes.

Translation of: Kotlin
Library: ntheory
`use ntheory qw(is_prime); \$i = 42;while (\$n < 42) {    if (is_prime(\$i)) {        \$n++;        printf "%2d %21s\n", \$n, commatize(\$i);        \$i += \$i - 1;    }    \$i++;} sub commatize {    (my \$s = reverse shift) =~ s/(.{3})/\$1,/g;    \$s =~ s/,\$//;    \$s = reverse \$s;}`
Output:
``` 1                    43
2                    89
3                   179
4                   359
5                   719
6                 1,439
7                 2,879
8                 5,779
9                11,579
10                23,159
11                46,327
12                92,657
13               185,323
14               370,661
15               741,337
16             1,482,707
17             2,965,421
18             5,930,887
19            11,861,791
20            23,723,597
21            47,447,201
22            94,894,427
23           189,788,857
24           379,577,741
25           759,155,483
26         1,518,310,967
27         3,036,621,941
28         6,073,243,889
29        12,146,487,779
30        24,292,975,649
31        48,585,951,311
32        97,171,902,629
33       194,343,805,267
34       388,687,610,539
35       777,375,221,081
36     1,554,750,442,183
37     3,109,500,884,389
38     6,219,001,768,781
39    12,438,003,537,571
40    24,876,007,075,181
41    49,752,014,150,467
42    99,504,028,301,131```

## Phix

Phix does not allow for loop variables to be modified, so we must use a while loop and manual increment for this sort of thing.

```atom i=42, n=1
while n<=42 do
if is_prime(i) then
printf(1,"n = %-2d  %,19d\n", {n, i})
n += 1
i += i-1
end if
i += 1
end while
```
Output:
```n = 1                    43
n = 2                    89
n = 3                   179
n = 4                   359
n = 5                   719
n = 6                 1,439
n = 7                 2,879
n = 8                 5,779
n = 9                11,579
n = 10               23,159
n = 11               46,327
n = 12               92,657
n = 13              185,323
n = 14              370,661
n = 15              741,337
n = 16            1,482,707
n = 17            2,965,421
n = 18            5,930,887
n = 19           11,861,791
n = 20           23,723,597
n = 21           47,447,201
n = 22           94,894,427
n = 23          189,788,857
n = 24          379,577,741
n = 25          759,155,483
n = 26        1,518,310,967
n = 27        3,036,621,941
n = 28        6,073,243,889
n = 29       12,146,487,779
n = 30       24,292,975,649
n = 31       48,585,951,311
n = 32       97,171,902,629
n = 33      194,343,805,267
n = 34      388,687,610,539
n = 35      777,375,221,081
n = 36    1,554,750,442,183
n = 37    3,109,500,884,389
n = 38    6,219,001,768,781
n = 39   12,438,003,537,571
n = 40   24,876,007,075,181
n = 41   49,752,014,150,467
n = 42   99,504,028,301,131
```

## Python

### Procedural

`def isPrime(n):    for x in 2, 3:        if not n % x:            return n == x    d = 5    while d * d <= n:        for x in 2, 4:            if not n % d:                return False            d += x    return True i = 42n = 0while n < 42:    if isPrime(i):        n += 1        print('n = {:2} {:20,}'.format(n, i))        i += i - 1    i += 1`
Output:
```n =  1                   43
n =  2                   89
n =  3                  179
n =  4                  359
n =  5                  719
n =  6                1,439
n =  7                2,879
n =  8                5,779
n =  9               11,579
n = 10               23,159
n = 11               46,327
n = 12               92,657
n = 13              185,323
n = 14              370,661
n = 15              741,337
n = 16            1,482,707
n = 17            2,965,421
n = 18            5,930,887
n = 19           11,861,791
n = 20           23,723,597
n = 21           47,447,201
n = 22           94,894,427
n = 23          189,788,857
n = 24          379,577,741
n = 25          759,155,483
n = 26        1,518,310,967
n = 27        3,036,621,941
n = 28        6,073,243,889
n = 29       12,146,487,779
n = 30       24,292,975,649
n = 31       48,585,951,311
n = 32       97,171,902,629
n = 33      194,343,805,267
n = 34      388,687,610,539
n = 35      777,375,221,081
n = 36    1,554,750,442,183
n = 37    3,109,500,884,389
n = 38    6,219,001,768,781
n = 39   12,438,003,537,571
n = 40   24,876,007,075,181
n = 41   49,752,014,150,467
n = 42   99,504,028,301,131```

### Functional

This task is defined in terms of procedural 'loops', which can generally be understood in functional terms as implementations of folds or maps. An analogous functional construction here might be a non-finite generator, or the iterative application of a function (over a tuple of values) to a seed value, for example:

`'''Loops/Increment loop index within loop body.''' from itertools import islice, takewhilefrom functools import reduceimport operator  # main :: IO ()def main():    '''Defines a list value, while printing a stream       of intermediate values during computation.    '''    gt = curry(operator.gt)    fst = operator.itemgetter(0)     list(takewhile(compose(gt(43), fst), series()))  # series :: (Int, Int) -> [(Int, Int)]def series():    '''Non finite series, defined as a generator       with IO side-effects (to the print channel).    '''    def go(tpl):        if isPrime(tpl[1]):            # Side effect.            print(showTuple(tpl))            # Value.            return splitArrow(succ)(dbl)(tpl)        else:            return secondArrow(succ)(tpl)     return iterate(go)(        (1, 42)    )  # isPrime :: Int -> Booldef isPrime(n):    '''True if n is prime.'''    if n in (2, 3):        return True    if 2 > n or 0 == n % 2:        return False    if 9 > n:        return True    if 0 == n % 3:        return False     def p(x):        return 0 == n % x or 0 == n % (2 + x)     return not any(map(p, range(5, 1 + int(n ** 0.5), 6)))  # showTuple :: (Int, Int) -> Stringdef showTuple(tpl):    '''Second integer shown with comma-chunked digits.'''    return '{:2} -> {:20,}'.format(*tpl)  # -------------------------GENERIC------------------------- # compose :: ((a -> a), ...) -> (a -> a)def compose(*fs):    '''Composition, from right to left,       of a series of functions.    '''    return lambda x: reduce(        lambda a, f: f(a),        fs[::-1], x    )  # curry :: ((a, b) -> c) -> a -> b -> cdef curry(f):    '''A curried function derived       from an uncurried function.    '''    return lambda x: lambda y: f(x, y)  # dbl :: Int -> Int -> Intdef dbl(x):    '''2 * x'''    return x + x  # drop :: Int -> [a] -> [a]# drop :: Int -> String -> Stringdef drop(n):    '''The sublist of xs beginning at       (zero-based) index n.    '''    def go(xs):        take(n)(xs)        return xs    return go  # iterate :: (a -> a) -> a -> Gen [a]def iterate(f):    '''An infinite list of repeated       applications of f to x.    '''    def go(x):        v = x        while True:            yield v            v = f(v)    return go  # secondArrow :: (b -> c) -> (a, b...) -> (a, c ...)def secondArrow(f):    '''A simple function lifted to one which applies       to a tuple, transforming only its second value.    '''    return lambda tpl: (tpl[0], f(tpl[1]))  # splitArrow (***) :: (a -> b) -> (c -> d) -> ((a, c) -> (b, d))def splitArrow(f):    '''A function from (x, y) to a tuple of (f(x), g(y))    '''    return lambda g: lambda tpl: (f(tpl[0]), g(tpl[1]))  # succ :: Enum a => a -> adef succ(x):    '''The successor of a value.       For numeric types, (1 +).    '''    return 1 + x  # take :: Int -> [a] -> [a]# take :: Int -> String -> Stringdef take(n):    '''The prefix of xs of length n,       or xs itself if n > length xs.    '''    return lambda xs: list(islice(xs, n))  # MAIN ---if __name__ == '__main__':    main()`
Output:
``` 1 ->                   43
2 ->                   89
3 ->                  179
4 ->                  359
5 ->                  719
6 ->                1,439
7 ->                2,879
8 ->                5,779
9 ->               11,579
10 ->               23,159
11 ->               46,327
12 ->               92,657
13 ->              185,323
14 ->              370,661
15 ->              741,337
16 ->            1,482,707
17 ->            2,965,421
18 ->            5,930,887
19 ->           11,861,791
20 ->           23,723,597
21 ->           47,447,201
22 ->           94,894,427
23 ->          189,788,857
24 ->          379,577,741
25 ->          759,155,483
26 ->        1,518,310,967
27 ->        3,036,621,941
28 ->        6,073,243,889
29 ->       12,146,487,779
30 ->       24,292,975,649
31 ->       48,585,951,311
32 ->       97,171,902,629
33 ->      194,343,805,267
34 ->      388,687,610,539
35 ->      777,375,221,081
36 ->    1,554,750,442,183
37 ->    3,109,500,884,389
38 ->    6,219,001,768,781
39 ->   12,438,003,537,571
40 ->   24,876,007,075,181
41 ->   49,752,014,150,467
42 ->   99,504,028,301,131```

## R

R cannot complete this task with a for loop. See https://stackoverflow.com/a/5913329/ . Instead, we must go down the same path as the Kotlin solution. Because it is sufficient for numbers this small, we will save ourselves some work and use the gmp library's isprime function for checking if a number is prime.

`i <- 42primeCount <- 0while(primeCount < 42){  if(gmp::isprime(i) == 2)#1 means "probably prime" and won't come up for numbers this small, 2 is what we want.  {    primeCount <- primeCount + 1    extraCredit <- format(i, big.mark=",", scientific = FALSE)    cat("Prime count:", paste0(primeCount, ";"), "The prime just found was:", extraCredit, "\n")    i <- i + i#This is missing the -1 from the Kotlin solution. There is no need to check i + i (it's even).  }  i <- i + 1}`
Output:
```Prime count: 1; The prime just found was: 43
Prime count: 2; The prime just found was: 89
Prime count: 3; The prime just found was: 179
Prime count: 4; The prime just found was: 359
Prime count: 5; The prime just found was: 719
Prime count: 6; The prime just found was: 1,439
Prime count: 7; The prime just found was: 2,879
Prime count: 8; The prime just found was: 5,779
Prime count: 9; The prime just found was: 11,579
Prime count: 10; The prime just found was: 23,159
Prime count: 11; The prime just found was: 46,327
Prime count: 12; The prime just found was: 92,657
Prime count: 13; The prime just found was: 185,323
Prime count: 14; The prime just found was: 370,661
Prime count: 15; The prime just found was: 741,337
Prime count: 16; The prime just found was: 1,482,707
Prime count: 17; The prime just found was: 2,965,421
Prime count: 18; The prime just found was: 5,930,887
Prime count: 19; The prime just found was: 11,861,791
Prime count: 20; The prime just found was: 23,723,597
Prime count: 21; The prime just found was: 47,447,201
Prime count: 22; The prime just found was: 94,894,427
Prime count: 23; The prime just found was: 189,788,857
Prime count: 24; The prime just found was: 379,577,741
Prime count: 25; The prime just found was: 759,155,483
Prime count: 26; The prime just found was: 1,518,310,967
Prime count: 27; The prime just found was: 3,036,621,941
Prime count: 28; The prime just found was: 6,073,243,889
Prime count: 29; The prime just found was: 12,146,487,779
Prime count: 30; The prime just found was: 24,292,975,649
Prime count: 31; The prime just found was: 48,585,951,311
Prime count: 32; The prime just found was: 97,171,902,629
Prime count: 33; The prime just found was: 194,343,805,267
Prime count: 34; The prime just found was: 388,687,610,539
Prime count: 35; The prime just found was: 777,375,221,081
Prime count: 36; The prime just found was: 1,554,750,442,183
Prime count: 37; The prime just found was: 3,109,500,884,389
Prime count: 38; The prime just found was: 6,219,001,768,781
Prime count: 39; The prime just found was: 12,438,003,537,571
Prime count: 40; The prime just found was: 24,876,007,075,181
Prime count: 41; The prime just found was: 49,752,014,150,467
Prime count: 42; The prime just found was: 99,504,028,301,131```

## Racket

Racket's `for` doesn't allow modification of index on the fly. The usual idiom for writing this kind of loop is to use named let, as shown here.

`#lang racket (require math/number-theory) (define (comma x)  (string-join   (reverse    (for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])      (cond        [(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]        [else (string digit)])))   "")) (let loop ([x 42] [cnt 0])  (cond    [(= cnt 42) (void)]    [(prime? x) (printf "~a: ~a\n" (add1 cnt) (comma x))                (loop (* 2 x) (add1 cnt))]    [else (loop (add1 x) cnt)]))`
Output:
```1: 43
2: 89
3: 179
4: 359
5: 719
6: 1,439
7: 2,879
8: 5,779
9: 11,579
10: 23,159
11: 46,327
12: 92,657
13: 185,323
14: 370,661
15: 741,337
16: 1,482,707
17: 2,965,421
18: 5,930,887
19: 11,861,791
20: 23,723,597
21: 47,447,201
22: 94,894,427
23: 189,788,857
24: 379,577,741
25: 759,155,483
26: 1,518,310,967
27: 3,036,621,941
28: 6,073,243,889
29: 12,146,487,779
30: 24,292,975,649
31: 48,585,951,311
32: 97,171,902,629
33: 194,343,805,267
34: 388,687,610,539
35: 777,375,221,081
36: 1,554,750,442,183
37: 3,109,500,884,389
38: 6,219,001,768,781
39: 12,438,003,537,571
40: 24,876,007,075,181
41: 49,752,014,150,467
42: 99,504,028,301,131
```

## Raku

(formerly Perl 6) Hmm.

Demonstrate the best way to accomplish this.

The best way is probably to not use an explicit loop. Just calculate the sequence directly.

`# the actual sequence logicmy @seq = grep *.is-prime, (42, { .is-prime ?? \$_+<1 !! \$_+1 } … *); # display codesay (1+\$_).fmt("%-4s"), @seq[\$_].flip.comb(3).join(',').flip.fmt("%20s") for ^42;`
Output:
```1                     43
2                     89
3                    179
4                    359
5                    719
6                  1,439
7                  2,879
8                  5,779
9                 11,579
10                23,159
11                46,327
12                92,657
13               185,323
14               370,661
15               741,337
16             1,482,707
17             2,965,421
18             5,930,887
19            11,861,791
20            23,723,597
21            47,447,201
22            94,894,427
23           189,788,857
24           379,577,741
25           759,155,483
26         1,518,310,967
27         3,036,621,941
28         6,073,243,889
29        12,146,487,779
30        24,292,975,649
31        48,585,951,311
32        97,171,902,629
33       194,343,805,267
34       388,687,610,539
35       777,375,221,081
36     1,554,750,442,183
37     3,109,500,884,389
38     6,219,001,768,781
39    12,438,003,537,571
40    24,876,007,075,181
41    49,752,014,150,467
42    99,504,028,301,131```

## REXX

`/*REXX pgm displays primes found:  starting Z at 42, if Z is a prime, add Z, else add 1.*/numeric digits 20;              d=digits()       /*ensure enough decimal digits for  Z. */parse arg limit .                                /*obtain optional arguments from the CL*/if limit=='' | limit==","  then limit=42         /*Not specified?  Then use the default.*/n=0                                              /*the count of number of primes found. */     do z=42  until n==limit                     /* ◄──this DO loop's index is modified.*/     if isPrime(z)  then do;  n=n + 1            /*Z  a prime?  Them bump prime counter.*/                              say right('n='n, 9)     right(commas(z), d)                              z=z + z - 1        /*also, bump the  DO  loop index  Z.   */                         end     end   /*z*/                                 /* [↑] a small tribute to Douglas Adams*/exit                                             /*stick a fork in it,  we're all done. *//*──────────────────────────────────────────────────────────────────────────────────────*/commas:  parse arg _;  do j=length(_)-3  to 1  by -3; _=insert(',', _, j); end;   return _/*──────────────────────────────────────────────────────────────────────────────────────*/isPrime: procedure; parse arg #;         if wordpos(#, '2 3 5 7')\==0  then return 1                                         if # // 2==0 | # // 3    ==0  then return 0           do j=5  by 6  until j*j>#;    if # // j==0 | # // (J+2)==0  then return 0           end   /*j*/                           /*           ___                       */         return 1                                /*Exceeded  √ #  ?    Then # is prime. */`
output:
```      n=1                   43
n=2                   89
n=3                  179
n=4                  359
n=5                  719
n=6                1,439
n=7                2,879
n=8                5,779
n=9               11,579
n=10               23,159
n=11               46,327
n=12               92,657
n=13              185,323
n=14              370,661
n=15              741,337
n=16            1,482,707
n=17            2,965,421
n=18            5,930,887
n=19           11,861,791
n=20           23,723,597
n=21           47,447,201
n=22           94,894,427
n=23          189,788,857
n=24          379,577,741
n=25          759,155,483
n=26        1,518,310,967
n=27        3,036,621,941
n=28        6,073,243,889
n=29       12,146,487,779
n=30       24,292,975,649
n=31       48,585,951,311
n=32       97,171,902,629
n=33      194,343,805,267
n=34      388,687,610,539
n=35      777,375,221,081
n=36    1,554,750,442,183
n=37    3,109,500,884,389
n=38    6,219,001,768,781
n=39   12,438,003,537,571
n=40   24,876,007,075,181
n=41   49,752,014,150,467
n=42   99,504,028,301,131
```

## Ring

` # Project : Loops/Increment loop index within loop body load "stdlib.ring"i = 42n = 0while n < 42         if isprime(i)             n = n + 1            see "n = " + n + "    " + i + nl            i = i + i - 1         ok         i = i + 1end `

Output:

```n = 1                    43
n = 2                    89
n = 3                   179
n = 4                   359
n = 5                   719
n = 6                 1,439
n = 7                 2,879
n = 8                 5,779
n = 9                11,579
n = 10               23,159
n = 11               46,327
n = 12               92,657
n = 13              185,323
n = 14              370,661
n = 15              741,337
n = 16            1,482,707
n = 17            2,965,421
n = 18            5,930,887
n = 19           11,861,791
n = 20           23,723,597
n = 21           47,447,201
n = 22           94,894,427
n = 23          189,788,857
n = 24          379,577,741
n = 25          759,155,483
n = 26        1,518,310,967
n = 27        3,036,621,941
n = 28        6,073,243,889
n = 29       12,146,487,779
n = 30       24,292,975,649
n = 31       48,585,951,311
n = 32       97,171,902,629
n = 33      194,343,805,267
n = 34      388,687,610,539
n = 35      777,375,221,081
n = 36    1,554,750,442,183
n = 37    3,109,500,884,389
n = 38    6,219,001,768,781
n = 39   12,438,003,537,571
n = 40   24,876,007,075,181
n = 41   49,752,014,150,467
n = 42   99,504,028,301,131```

## Ruby

` require 'prime' limit = 42i = 42n = 0 while n < limit do  if i.prime? then    n += 1    puts "n = #{n}".ljust(7) + ":" + "#{i.to_s.reverse.scan(/\d{3}|.+/).join(",").reverse}".rjust(19)    i += i  else    i += 1  endend `

Output :

```n = 1  :                 43
n = 2  :                 89
n = 3  :                179
n = 4  :                359
n = 5  :                719
n = 6  :              1,439
n = 7  :              2,879
n = 8  :              5,779
n = 9  :             11,579
n = 10 :             23,159
n = 11 :             46,327
n = 12 :             92,657
n = 13 :            185,323
n = 14 :            370,661
n = 15 :            741,337
n = 16 :          1,482,707
n = 17 :          2,965,421
n = 18 :          5,930,887
n = 19 :         11,861,791
n = 20 :         23,723,597
n = 21 :         47,447,201
n = 22 :         94,894,427
n = 23 :        189,788,857
n = 24 :        379,577,741
n = 25 :        759,155,483
n = 26 :      1,518,310,967
n = 27 :      3,036,621,941
n = 28 :      6,073,243,889
n = 29 :     12,146,487,779
n = 30 :     24,292,975,649
n = 31 :     48,585,951,311
n = 32 :     97,171,902,629
n = 33 :    194,343,805,267
n = 34 :    388,687,610,539
n = 35 :    777,375,221,081
n = 36 :  1,554,750,442,183
n = 37 :  3,109,500,884,389
n = 38 :  6,219,001,768,781
n = 39 : 12,438,003,537,571
n = 40 : 24,876,007,075,181
n = 41 : 49,752,014,150,467
n = 42 : 99,504,028,301,131
```

## Scala

Like most other Block structured languages (apparently with the exception of Java), Scala's 'for' statement is for the sake of fallibility aka side effect or mutability, limited and doesn't allow either the iteration variable or the step to be modified within the loop body. Both are for serious reasons immutable.

### Demonstrate the best way to accomplish this.

So instead we use tail recursion here which, with the use of immutable variables and no side effects, has no such restrictions, and we are save.

Output:
Best seen running in your browser either by ScalaFiddle (ES aka JavaScript, non JVM) or Scastie (remote JVM).
`import scala.annotation.tailrec object LoopIncrementWithinBody extends App {  private val (limit, offset) = (42L, 1)   @tailrec  private def loop(i: Long, n: Int): Unit = {     def isPrime(n: Long) =      n > 1 && ((n & 1) != 0 || n == 2) && (n % 3 != 0 || n == 3) &&        ((5 to math.sqrt(n).toInt by 2).par forall (n % _ != 0))     if (n < limit + offset)      if (isPrime(i)) {        printf("n = %-2d  %,19d%n".formatLocal(java.util.Locale.GERMANY, n, i))        loop(i + i + 1, n + 1)      } else loop(i + 1, n)  }   loop(limit, offset)}`

## Seed7

`\$ include "seed7_05.s7i"; const func boolean: isPrime (in integer: number) is func  result    var boolean: result is FALSE;  local    var integer: count is 2;  begin    if number = 2 then      result := TRUE;    elsif number > 2 then      while number rem count <> 0 and count * count <= number do        incr(count);      end while;      result := number rem count <> 0;    end if;  end func; const proc: main is func  local    var integer: i is 42;    var integer: n is 0;  begin    for i range 42 to integer.last until n >= 42 do      if isPrime(i) then        incr(n);        writeln("n = " <& n lpad 2 <& i lpad 16);        i +:= i - 1;      end if;    end for;  end func;`
Output:
```n =  1              43
n =  2              89
n =  3             179
n =  4             359
n =  5             719
n =  6            1439
n =  7            2879
n =  8            5779
n =  9           11579
n = 10           23159
n = 11           46327
n = 12           92657
n = 13          185323
n = 14          370661
n = 15          741337
n = 16         1482707
n = 17         2965421
n = 18         5930887
n = 19        11861791
n = 20        23723597
n = 21        47447201
n = 22        94894427
n = 23       189788857
n = 24       379577741
n = 25       759155483
n = 26      1518310967
n = 27      3036621941
n = 28      6073243889
n = 29     12146487779
n = 30     24292975649
n = 31     48585951311
n = 32     97171902629
n = 33    194343805267
n = 34    388687610539
n = 35    777375221081
n = 36   1554750442183
n = 37   3109500884389
n = 38   6219001768781
n = 39  12438003537571
n = 40  24876007075181
n = 41  49752014150467
n = 42  99504028301131
```

## Smalltalk

Works with: Smalltalk/X
`numFound := 0.idx := 42.[:exit |    idx := idx + 1.    idx isPrime ifTrue:[        numFound := numFound + 1.        '%d %20d\n' printf:{numFound . idx} on:Transcript.        idx := idx + idx - 1.        numFound == 42 ifTrue:exit    ].] loopWithExit.`

Note: above code uses a public domain printf goodie which is part of many Smalltalk's base libraries; if not present in a particular dialect, use regular print/display/transcribe or whatever is available.

Output:
```1                   43
2                   89
3                  179
4                  359
5                  719
6                 1439
7                 2879
8                 5779
9                11579
10                23159
11                46327
12                92657
13               185323
...
36        1554750442183
37        3109500884389
38        6219001768781
39       12438003537571
40       24876007075181
41       49752014150467
42       99504028301131```

## Standard ML

` fun until done change dolast x =    if done x      then    dolast x      else    until done change dolast (change x);       (* iteration/generic loop *)  val isprime = fn n :IntInf.int  =>let fun butlast (_,t)   = t*t > n fun divide (n,t)    = n mod t = 0 orelse t*t > n fun trymore (n,t)   = (n,t + 2)in  n mod 2 <> 0 andalso until divide trymore butlast (n,3) end; val loop =  fn () =>let fun butthislast (_,p,_) = rev p  fun wegot42 (n,_,_)     = n = 43 fun trymore (n,p,i)     = if isprime i                                    then ( n+1, (n,i)::p , i+i )                                   else ( n ,  p, i+1)in   until wegot42 trymore butthislast  (1,[],42) end ; val printp = fn clist:(int*IntInf.int) list => List.app (fn i=>print ((Int.toString (#1 i) )^" : "^ (IntInf.toString (#2 i) )^"\n")) clist ; `
call
``` printp (loop ()) ;
1 : 43
2 : 89
3 : 179
4 : 359
5 : 719
6 : 1439
7 : 2879
8 : 5779
9 : 11579
10 : 23159
11 : 46327
12 : 92657
13 : 185323
14 : 370661
15 : 741337
16 : 1482707
17 : 2965421
18 : 5930887
19 : 11861791
20 : 23723597
21 : 47447201
22 : 94894427
23 : 189788857
24 : 379577741
25 : 759155483
26 : 1518310967
27 : 3036621941
28 : 6073243889
29 : 12146487779
30 : 24292975649
31 : 48585951311
32 : 97171902629
33 : 194343805267
34 : 388687610539
35 : 777375221081
36 : 1554750442183
37 : 3109500884389
38 : 6219001768781
39 : 12438003537571
40 : 24876007075181
41 : 49752014150467
42 : 99504028301131```

## Tcl

Inspired by Java and Kotlin variants.

Tcl allows modifying the loop variable. Everything can be implemented straightforward.

`proc isPrime n {  if {[expr \$n % 2] == 0} {    return [expr \$n == 2]  }  if {[expr \$n % 3] == 0} {    return [expr \$n == 3]  }  for {set d 5} {[expr \$d * \$d] <= \$n} {incr d 4} {    if {[expr \$n % \$d] == 0} {return 0}    incr d 2    if {[expr \$n % \$d] == 0} {return 0}  }  return 1} set LIMIT 42 for {set i \$LIMIT; set n 0} {\$n < \$LIMIT} {incr i} {  if [isPrime \$i] {    incr n    puts "n=\$n, i=\$i"    incr i [expr \$i -1]  }}`
Output:
```n=1, i=43
n=2, i=89
n=3, i=179
n=4, i=359
n=5, i=719
n=6, i=1439
n=7, i=2879
n=8, i=5779
n=9, i=11579
n=10, i=23159
n=11, i=46327
n=12, i=92657
n=13, i=185323
n=14, i=370661
n=15, i=741337
n=16, i=1482707
n=17, i=2965421
n=18, i=5930887
n=19, i=11861791
n=20, i=23723597
n=21, i=47447201
n=22, i=94894427
n=23, i=189788857
n=24, i=379577741
n=25, i=759155483
n=26, i=1518310967
n=27, i=3036621941
n=28, i=6073243889
n=29, i=12146487779
n=30, i=24292975649
n=31, i=48585951311
n=32, i=97171902629
n=33, i=194343805267
n=34, i=388687610539
n=35, i=777375221081
n=36, i=1554750442183
n=37, i=3109500884389
n=38, i=6219001768781
n=39, i=12438003537571
n=40, i=24876007075181
n=41, i=49752014150467
n=42, i=99504028301131```

## VBA

Visual Basic for Application (VBA) allows to modify the index inside the loop.

Translation of: Visual Basic .NET
Works with: VBA version VBA Excel 2013
`    Sub Main()        'Loops Increment loop index within loop body - 17/07/2018        Dim imax, i As Integer        Dim n As Currency        imax = 42        i = 0: n = 42        Do While i < imax            If IsPrime(n) Then                i = i + 1                Debug.Print ("i=" & RightX(i, 2) & " : " & RightX(Format(n, "#,##0"), 20))                n = n + n - 1            End If            n = n + 1        Loop    End Sub 'Main    Function IsPrime(n As Currency)        Dim i As Currency        If n = 2 Or n = 3 Then            IsPrime = True        ElseIf ModX(n, 2) = 0 Or ModX(n, 3) = 0 Then            IsPrime = False        Else            i = 5            Do While i * i <= n                If ModX(n, i) = 0 Or ModX(n, i + 2) = 0 Then                    IsPrime = False                    Exit Function                End If                i = i + 6            Loop            IsPrime = True        End If    End Function 'IsPrime    Function ModX(a As Currency, b As Currency) As Currency        ModX = a - Int(a / b) * b    End Function 'ModX        Function RightX(c, n)        RightX = Right(Space(n) & c, n)    End Function 'RightX`
Output:
```i= 1 :                   43
i= 2 :                   89
i= 3 :                  179
i= 4 :                  359
i= 5 :                  719
i= 6 :                1,439
i= 7 :                2,879
i= 8 :                5,779
i= 9 :               11,579
i=10 :               23,159
i=11 :               46,327
i=12 :               92,657
i=13 :              185,323
i=14 :              370,661
i=15 :              741,337
i=16 :            1,482,707
i=17 :            2,965,421
i=18 :            5,930,887
i=19 :           11,861,791
i=20 :           23,723,597
i=21 :           47,447,201
i=22 :           94,894,427
i=23 :          189,788,857
i=24 :          379,577,741
i=25 :          759,155,483
i=26 :        1,518,310,967
i=27 :        3,036,621,941
i=28 :        6,073,243,889
i=29 :       12,146,487,779
i=30 :       24,292,975,649
i=31 :       48,585,951,311
i=32 :       97,171,902,629
i=33 :      194,343,805,267
i=34 :      388,687,610,539
i=35 :      777,375,221,081
i=36 :    1,554,750,442,183
i=37 :    3,109,500,884,389
i=38 :    6,219,001,768,781
i=39 :   12,438,003,537,571
i=40 :   24,876,007,075,181
i=41 :   49,752,014,150,467
i=42 :   99,504,028,301,131```

## Visual Basic .NET

Visual Basic .Net allows to modify the index inside the loop.

Translation of: Visual Basic
Works with: Visual Basic .NET version 2013
`Module LoopsIliwlb     Sub Main()        'Loops Increment loop index within loop body - 17/07/2018        Dim imax, i As Int32        Dim n As Int64        imax = 42        i = 0 : n = 42        While i < imax            If IsPrime(n) Then                i = i + 1                Console.WriteLine("i=" & RightX(i, 2) & " : " & RightX(Format(n, "#,##0"), 20))                n = n + n - 1            End If            n = n + 1        End While    End Sub     Function IsPrime(n As Int64)        Dim i As Int64        If n = 2 Or n = 3 Then            IsPrime = True        ElseIf (n Mod 2) = 0 Or (n Mod 3) = 0 Then            IsPrime = False        Else            i = 5            While i * i <= n                If (n Mod i) = 0 Or (n Mod (i + 2)) = 0 Then                    IsPrime = False                    Exit Function                End If                i = i + 6            End While            IsPrime = True        End If    End Function 'IsPrime     Function RightX(c, n)        RightX = Right(Space(n) & c, n)    End Function End Module`
Output:
```i= 1 :                   43
i= 2 :                   89
i= 3 :                  179
i= 4 :                  359
i= 5 :                  719
i= 6 :                1,439
i= 7 :                2,879
i= 8 :                5,779
i= 9 :               11,579
i=10 :               23,159
i=11 :               46,327
i=12 :               92,657
i=13 :              185,323
i=14 :              370,661
i=15 :              741,337
i=16 :            1,482,707
i=17 :            2,965,421
i=18 :            5,930,887
i=19 :           11,861,791
i=20 :           23,723,597
i=21 :           47,447,201
i=22 :           94,894,427
i=23 :          189,788,857
i=24 :          379,577,741
i=25 :          759,155,483
i=26 :        1,518,310,967
i=27 :        3,036,621,941
i=28 :        6,073,243,889
i=29 :       12,146,487,779
i=30 :       24,292,975,649
i=31 :       48,585,951,311
i=32 :       97,171,902,629
i=33 :      194,343,805,267
i=34 :      388,687,610,539
i=35 :      777,375,221,081
i=36 :    1,554,750,442,183
i=37 :    3,109,500,884,389
i=38 :    6,219,001,768,781
i=39 :   12,438,003,537,571
i=40 :   24,876,007,075,181
i=41 :   49,752,014,150,467
i=42 :   99,504,028,301,131```

## Vlang

Translation of: go
`fn is_prime(n u64) bool {    if n % 2 == 0 {        return n == 2    }    if n % 3 == 0 {        return n == 3    }    mut d := u64(5)    for d * d <= n {        if n % d == 0 {            return false        }        d += 2        if n % d == 0 {            return false        }         d += 4    }    return true}const limit = 42fn main() {    for i, n := u64(limit), 0; n<limit; i++ {        if is_prime(i) {            n++            println("n = \${n:-2}  \${i:19}")            i += i - 1        }    }}`
Output:
```Same as Kotlin entry
```

## Wren

Library: Wren-fmt

Although it might appear as though one can change the index variable within a for loop, it does in fact change a local copy of the variable and the iteration is not affected at all. Consequently, the only way to complete this task in Wren is to use a while loop.

`import "/fmt" for Fmt var isPrime = Fn.new { |n|    if (n < 2 || !n.isInteger) return false    if (n%2 == 0) return n == 2    if (n%3 == 0) return n == 3    var d = 5    while (d*d <= n) {        if (n%d == 0) return false        d = d + 2        if (n%d == 0) return false        d = d + 4    }    return true} var count = 0var i = 42while (count < 42) {    if (isPrime.call(i)) {        count = count + 1        System.print("%(Fmt.d(2, count)): %(Fmt.dc(18, i))")        i = 2 * i - 1            }    i = i + 1}`
Output:
``` 1:                 43
2:                 89
3:                179
4:                359
5:                719
6:              1,439
7:              2,879
8:              5,779
9:             11,579
10:             23,159
11:             46,327
12:             92,657
13:            185,323
14:            370,661
15:            741,337
16:          1,482,707
17:          2,965,421
18:          5,930,887
19:         11,861,791
20:         23,723,597
21:         47,447,201
22:         94,894,427
23:        189,788,857
24:        379,577,741
25:        759,155,483
26:      1,518,310,967
27:      3,036,621,941
28:      6,073,243,889
29:     12,146,487,779
30:     24,292,975,649
31:     48,585,951,311
32:     97,171,902,629
33:    194,343,805,267
34:    388,687,610,539
35:    777,375,221,081
36:  1,554,750,442,183
37:  3,109,500,884,389
38:  6,219,001,768,781
39: 12,438,003,537,571
40: 24,876,007,075,181
41: 49,752,014,150,467
42: 99,504,028,301,131
```

## zkl

Uses libGMP (GNU MP Bignum Library) for easy prime detection rather than write that bit of code and pollute this solution.

`var [const] BN=Import("zklBigNum");  // libGMPn,p := 1,BN(42);do{   if(p.probablyPrime()){ println("n = %2d %,20d".fmt(n,p)); p.add(p); n+=1; }   p.add(1); }while(n<=42);`

zkl loop variables are iterators that don't allow direct manipulation of their underlying source. The compiler names these iterators __<index>Walker. However, by using the look ahead stack, we can keep the iterator from advancing through the source.

`p:=BN(42);foreach n in ([1..42]){   if(p.probablyPrime()){ println("n = %2d %,20d".fmt(n,p)); p.add(p); }   else{ p.add(1); __nWalker.push(n); }  // p not prime, don't advance n}`
Output:
```n =  1                   43
n =  2                   89
n =  3                  179
n =  4                  359
n =  5                  719
n =  6                1,439
n =  7                2,879
n =  8                5,779
n =  9               11,579
n = 10               23,159
n = 11               46,327
n = 12               92,657
n = 13              185,323
n = 14              370,661
n = 15              741,337
n = 16            1,482,707
n = 17            2,965,421
n = 18            5,930,887
n = 19           11,861,791
n = 20           23,723,597
n = 21           47,447,201
n = 22           94,894,427
n = 23          189,788,857
n = 24          379,577,741
n = 25          759,155,483
n = 26        1,518,310,967
n = 27        3,036,621,941
n = 28        6,073,243,889
n = 29       12,146,487,779
n = 30       24,292,975,649
n = 31       48,585,951,311
n = 32       97,171,902,629
n = 33      194,343,805,267
n = 34      388,687,610,539
n = 35      777,375,221,081
n = 36    1,554,750,442,183
n = 37    3,109,500,884,389
n = 38    6,219,001,768,781
n = 39   12,438,003,537,571
n = 40   24,876,007,075,181
n = 41   49,752,014,150,467
n = 42   99,504,028,301,131
```