Jump to content

10001th prime

From Rosetta Code
10001th prime is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Task


Find and show on this page the 10001st prime number.

11l

V k = 10001
V n = k * 17
V primes = [1B] * n
primes[0] = primes[1] = 0B

L(i) 2 .. Int(sqrt(n))
   I !primes[i]
      L.continue
   L(j) (i * i .< n).step(i)
      primes[j] = 0B

L(i) 0 .< n
   I primes[i]
      I k == 1
         print(i)
         L.break
      k--
Output:
104743

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
or android 64 bits with application Termux
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program prime1000164.s   */
/************************************/
/* Constantes                       */
/************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"

/************************************/
/* Macros                           */
/************************************/
//.include "../../ficmacros64.inc"        // use for developper debugging
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessStartPgm:          .asciz "Program 64 bits start \n"
szMessEndPgm:            .asciz "Program normal end.\n"
szMessErrorArea:         .asciz "\033[31mError : area divisors too small.\n"
szMessPrime:             .asciz "Prime N0 10001 : "
szMessOverflow:          .asciz "Overflow function isPrime.\n"
szCarriageReturn:        .asciz "\n"

.align 4
qGraine:                 .quad 123456
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss 
.align 4
sZoneConv:               .skip 24
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main 
main:                            // program start
    ldr x0,qAdrszMessStartPgm    // display start message
    bl affichageMess
    mov x4,#1                    // start number 
    mov x5,#1                    // prime counter 
    ldr x2,iLimit
    tst x4,#1
    cinc x4,x4,eq                // start with odd number
1:
    mov x0,x4
    bl isPrimeMiller             // test miller rabin
    cmp x0,#0
    cinc x4,x4,eq
    cinc x4,x4,eq
    beq 1b
    add x5,x5,#1
    cmp x5,x2                    // counter ok ?
    cinc x4,x4,ne
    cinc x4,x4,ne
    bne 1b

    ldr x0,qAdrszMessPrime
    bl affichageMess
    mov x0,x4
    ldr x1,qAdrsZoneConv
    bl conversion10              // decimal conversion
    ldr x0,qAdrsZoneConv
    bl affichageMess
    ldr x0,qAdrszCarriageReturn
    bl affichageMess

    ldr x0,qAdrszMessEndPgm         // display end message
    bl affichageMess

100:                                // standard end of the program
    mov x0, #0                      // return code
    mov x8,EXIT 
    svc 0                           // perform system call
qAdrszMessStartPgm:        .quad szMessStartPgm
qAdrszMessEndPgm:          .quad szMessEndPgm
qAdrszCarriageReturn:      .quad szCarriageReturn
qAdrsZoneConv:             .quad sZoneConv
qAdrszMessPrime:           .quad szMessPrime
iLimit:                    .quad 10001


/***************************************************/
/*   check if a number is prime  test miller rabin  */
/***************************************************/
/* r0 contains the number            */
/* r0 return 1 if prime  0 else */
//2147483647
//4294967297
//131071
isPrimeMiller:
    stp x1,lr,[sp,-16]!
    cmp x0,#1          // control 0 or 1
    csel x0,xzr,x0,ls
    bls 100f
    cmp x0,#2          // control = 2
    mov x1,1
    csel x0,x1,x0,eq
    beq 100f
    tst x0,#1
    csel x0,xzr,x0,eq  // even
    beq 100f
    mov x1,#5          // loop number
    bl testMiller
100:
    ldp x1,lr,[sp],16
    ret 
/***************************************************/
/*   test miller rabin  algorithme wikipedia       */
/*   unsigned                                      */
/***************************************************/
/* x0 contains number   */
/* x1 contains parameter   */
/* x0 return 1 if prime 0 if composite    */
testMiller:
    stp x1,lr,[sp,-16]!               // TODO: save à completer 
    stp x2,x3,[sp,-16]!  
    stp x4,x5,[sp,-16]! 
    stp x6,x7,[sp,-16]! 
    stp x8,x9,[sp,-16]! 
    stp x10,x11,[sp,-16]! 
    mov x4,x0          // N
    mov x7,x1          // loop maxi 
    sub x10,x0,#1       // D
    mov x2,#2
    mov x6,#0          // S
1:                     // compute D * 2 power S
    lsr x10,x10,#1     // D= D/2
    add x6,x6,#1       // increment S
    tst x10,#1          // D even ?
    beq 1b
2:
    mov x8,#0          // loop counter 
    sub x5,x0,#3
3:
    mov x0,x5
    bl genereraleas
    add x0,x0,#2       // alea (entre 2 et n-1)
    mov x1,x10          // exposant = D
    mov x2,x4          // modulo N
    bl moduloPur64
    cmp x0,#1
    beq 5f
    sub x1,x4,#1       // n -1
    cmp x0,x1
    beq 5f
    sub x9,x6,#1       // S - 1
4:
    mov x2,x0
    
    mul x0,x2,x2       // compute square lower
    umulh x1,x2,x2     // compute square upper    
    mov x2,x4          // and compute modulo N
    bl divisionReg128U
    mov x0,x3
    cmp x0,#1
    csel x0,xzr,x0,eq  // composite
    beq 100f
    sub x1,x4,#1       // n -1
    cmp x0,x1
    beq 5f
    subs x9,x9,#1
    bge 4b
    mov x0,#0          // composite
    b 100f
5:
    add x8,x8,#1
    cmp x8,x7
    blt 3b 
    mov x0,#1          // prime
100:
    ldp x10,x11,[sp],16
    ldp x8,x9,[sp],16
    ldp x6,x7,[sp],16
    ldp x4,x5,[sp],16
    ldp x2,x3,[sp],16
    ldp x1,lr,[sp],16                 // TODO: retaur à completer 
    ret 

/********************************************************/
/*   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 reste
1:
    tst x7,1
    beq 2f
    mul x4,x9,x6
    umulh x5,x9,x6
    mov x6,x4
    mov x0,x6
    mov x1,x5
    bl divisionReg128U
    mov x6,x3
2:
    mul x8,x9,x9
    umulh x5,x9,x9
    mov x0,x8
    mov x1,x5
    bl divisionReg128U
    mov x9,x3
    lsr x7,x7,1
    cbnz x7,1b
    mov x0,x6                  // result
    cmn x0,0                   // carry à zero pas d'erreur
    b 100f
99:
    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 x30
qAdrszMessOverflow:         .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 bit
1:    
    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 R
2:
    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 haute
3:
    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 à 1
4:
                               // 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,#1
5:
    orr x0,x0,x4               // position du dernier bit du quotient
    mov x3,x5
100:
    ldp x4,x5,[sp],16          // restaur des  2 registres
    ldp x6,lr,[sp],16          // restaur des  2 registres
    ret                        // retour adresse lr x30

/***************************************************/
/*   Generation random number                  */
/***************************************************/
/* x0 contains limit  */
genereraleas:
    stp x1,lr,[sp,-16]!            // save  registers
    stp x2,x3,[sp,-16]!            // save  registers
    ldr x1,qAdrqGraine
    ldr x2,[x1]
    ldr x3,qNbDep1
    mul x2,x3,x2
    ldr x3,qNbDep2
    add x2,x2,x3
    str x2,[x1]                    // maj de la graine pour l appel suivant 
    cmp x0,#0
    beq 100f
    udiv x3,x2,x0
    msub x0,x3,x0,x2               // résult = remainder
 
100:                               // end function
    ldp x2,x3,[sp],16              // restaur  2 registers
    ldp x1,lr,[sp],16              // restaur  2 registers
    ret                            // return to address lr x30
qAdrqGraine: .quad qGraine
qNbDep1:     .quad 0x0019660d
qNbDep2:     .quad 0x3c6ef35f
/***************************************************/
/*      ROUTINES INCLUDE                 */
/***************************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeARM64.inc"
Output:
Program 64 bits start
Prime N0 10001 : 104743
Program normal end.

Ada

-- Rosetta Code Task written in Ada
-- 10001th prime
-- https://rosettacode.org/wiki/10001th_prime
-- November 2024, R. B. E.

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Ten_Thousand_One_Prime is

  function Is_Prime (N : in Natural) return Boolean is
    Temp : Natural := 5;
  begin
    if N < 2 then
      return False;
    end if;
    if N mod 2 = 0 then
      return N = 2;
    end if;
    if N mod 3 = 00 then
      return N = 3;
    end if;
    while Temp * Temp <= N loop
      if N mod Temp = 0 then
        return False;
      end if;
      Temp := Temp + 2;
      if N mod Temp = 0 then
        return False;
      end if;
    end loop;
    return True;
  end Is_Prime;

  Nth_Prime : constant Positive := 10_001;
  Prime_Counter : Natural := 0;
  Prime_Candidate : Positive := 2;

begin
  loop
    if Is_Prime (Prime_Candidate) then
      Prime_Counter := Prime_Counter + 1;
    end if;
    exit when Prime_Counter = Nth_Prime;
    if Prime_Candidate = 2 then
      Prime_Candidate := Prime_Candidate + 1;
    else
      Prime_Candidate := Prime_Candidate + 2;
    end if;
  end loop;
  Put ("The ");
  Put (Nth_Prime, 0);
  Put ("th Prime is ");
  Put (Prime_Candidate, 0);
  New_Line;
end Ten_Thousand_One_Prime;
Output:
The 10001th Prime is 104743

ALGOL 68

Chebyshev showed that the limit of pi( n ) / ( n / ln(n) ) as n approaches infinity is 1 ( pi( n ) is the number of primes up to n ).
The APPROXIMATESIEVESIZEFOR operator uses this to find a rough value for size of sieve needed to contain the required number of primes.

BEGIN # find the 10001st prime #
    PR read "primes.incl.a68" PR
    # construct a sieve of primes that should be large enough to contain 10001 primes #
    INT required prime = 10 001;
    []BOOL prime = PRIMESIEVE APPROXIMATESIEVESIZEFOR required prime;
    INT p count := 1;
    FOR n FROM 3 BY 2 WHILE p count < required prime DO
        IF prime[ n ] THEN
            p count +:= 1;
            IF p count = required prime THEN
                print( ( "Prime ", whole( required prime, 0 ), " is ", whole( n, 0 ) ) )
            FI
        FI
    OD
END
Output:
Prime 10001 is 104743

ARM Assembly

Works with: as version Raspberry Pi
or android 32 bits with application Termux
/* ARM assembly Raspberry PI  */
/* program prime10001.s   */



/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes                       */
/************************************/
.include "../constantes.inc"

/************************************/
/* Macros                           */
/************************************/
//.include "../../ficmacros32.inc"        @ use for developper debugging
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessStartPgm:          .asciz "Program 32 bits start \n"
szMessEndPgm:            .asciz "Program normal end.\n"
szMessErrorArea:         .asciz "\033[31mError : area divisors too small.\n"
szMessPrime:             .asciz "Prime N0 10001 : "
szCarriageReturn:        .asciz "\n"

.align 4
iGraine:                 .int 123456
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss 
.align 4
sZoneConv:               .skip 24
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main 
main:                            @ program start
    ldr r0,iAdrszMessStartPgm    @ display start message
    bl affichageMess
    mov r4,#1                    @ start number 
    mov r5,#1                    @ prime counter 
    ldr r2,iLimit
    tst r4,#1
    addeq r4,#1                  @ start with odd number
1:
    mov r0,r4
    bl isPrimeMiller             @ test miller rabin
    cmp r0,#0
    addeq r4,r4,#2
    beq 1b
    add r5,r5,#1
    cmp r5,r2                    @ counter ok ?
    addne r4,r4,#2
    bne 1b

    ldr r0,iAdrszMessPrime
    bl affichageMess
    mov r0,r4
    ldr r1,iAdrsZoneConv
    bl conversion10              @ decimal conversion
    ldr r0,iAdrsZoneConv
    bl affichageMess
    ldr r0,iAdrszCarriageReturn
    bl affichageMess


    ldr r0,iAdrszMessEndPgm         @ display end message
    bl affichageMess

100:                                @ standard end of the program
    mov r0, #0                      @ return code
    mov r7, #EXIT                   @ request to exit program
    svc 0                           @ perform system call
iAdrszMessStartPgm:        .int szMessStartPgm
iAdrszMessEndPgm:          .int szMessEndPgm
iAdrszCarriageReturn:      .int szCarriageReturn
iAdrsZoneConv:             .int sZoneConv
iAdrszMessPrime:           .int szMessPrime
iLimit:                    .int 10001


/***************************************************/
/*   check if a number is prime  test miller rabin  */
/***************************************************/
/* r0 contains the number            */
/* r0 return 1 if prime  0 else */
@2147483647
@4294967297
@131071
isPrimeMiller:
    push {r1-r6,lr}   @ save registers 
    cmp r0,#1         @ control 0 or 1
    movls r0,#0
    bls 100f
    cmp r0,#2         @ control = 2
    moveq r0,#1
    beq 100f
    tst r0,#1
    moveq r0,#0       @ even
    beq 100f
    mov r1,#5         @ loop number
    bl testMiller
100:
    pop {r1-r6,pc}
/***************************************************/
/*   test miller rabin  algorithme wikipedia       */
/*   unsigned                                      */
/***************************************************/
/* r0 contains number   */
/* r1 contains parameter   */
/* r0 return 1 if prime 0 if composite    */
testMiller:
    push {r1-r9,lr}    @ save registers
    mov r4,r0          @ N
    mov r7,r1          @ loop maxi 
    sub r3,r0,#1       @ D
    mov r2,#2
    mov r6,#0          @ S
1:                     @ compute D * 2 power S
    lsr r3,#1          @ D= D/2
    add r6,r6,#1       @ increment S
    tst r3,#1          @ D even ?
    beq 1b
2:
    mov r8,#0          @ loop counter 
    sub r5,r0,#3
3:
    mov r0,r5
    bl genereraleas
    add r0,r0,#2       @ alea (entre 2 et n-1)
    mov r1,r3          @ exposant = D
    mov r2,r4          @ modulo N
    bl moduloPuR32
    cmp r0,#1
    beq 5f
    sub r1,r4,#1       @ n -1
    cmp r0,r1
    beq 5f
    sub r9,r6,#1       @ S - 1
4:
    mov r2,r0
    umull r0,r1,r2,r0  @ compute square
    mov r2,r4          @ and compute modulo N
    bl division32R2023
    mov r0,r2
    cmp r0,#1
    moveq r0,#0        @ composite
    beq 100f
    sub r1,r4,#1       @ n -1
    cmp r0,r1
    beq 5f
    subs r9,r9,#1
    bge 4b
    mov r0,#0          @ composite
    b 100f
5:
    add r8,r8,#1
    cmp r8,r7
    blt 3b 
    mov r0,#1          @ prime
100:
    pop {r1-r9,pc}
/********************************************************/
/*   Calcul modulo de b puissance e modulo m  */
/*    Exemple 4 puissance 13 modulo 497 = 445         */
/*                                             */
/********************************************************/
/* r0  nombre  */
/* r1 exposant */
/* r2 modulo   */
/* r0 return result  */
moduloPuR32:
    push {r1-r6,lr}    @ save registers  
    cmp r0,#0          @ control <> zero 
    beq 100f
    cmp r2,#0          @ control <> zero 
    beq 100f
1:
    mov r4,r2          @ save modulo
    mov r5,r1          @ save exposant 
    mov r6,r0          @ save base
    mov r3,#1          @ start result

    mov r1,#0          @ division r0,r1 by r2
    bl division32R2023
    mov r6,r2          @ base <- remainder
2:
    tst r5,#1          @  exposant even or odd
    beq 3f
    umull r0,r1,r6,r3  @ multiplication base
    mov r2,r4          @ and compute modulo N
    bl division32R2023
    mov r3,r2          @ result <- remainder
3:
    umull r0,r1,r6,r6  @ compute base square
    mov r2,r4          @ and compute modulo N
    bl division32R2023
    mov r6,r2          @ base <- remainder

    lsr r5,#1          @ left shift 1 bit
    cmp r5,#0          @ end ?
    bne 2b
    mov r0,r3
100:
    pop {r1-r6,pc}

/***************************************************/
/*   division number 64 bits in 2 registers by number 32 bits */
/*   unsigned */
/***************************************************/
/* r0 contains lower part dividende   */
/* r1 contains upper part dividende   */
/* r2 contains divisor   */
/* r0 return lower part quotient    */
/* r1 return upper part quotient    */
/* r2 return remainder               */
division32R2023:
    push {r3-r6,lr}    @ save registers
    mov r4,r2          @ save divisor
    mov r5,#0          @ init upper part divisor   
    mov r2,r0          @ save dividende
    mov r3,r1
    mov r0,#0          @ init result
    mov r1,#0
    mov r6,#0          @ init shift counter
1:                     @ loop shift divisor
    cmp r5,#0          @ upper divisor <0
    blt 2f
    cmp r5,r3
    cmpeq r4,r2
    bhs 2f             @ new divisor > dividende
    lsl r5,#1          @ shift left one bit upper divisor
    lsls r4,#1         @ shift left one bit lower divisor
    orrcs r5,r5,#1     @ move bit 31 lower on upper
    add r6,r6,#1       @ increment shift counter
    b 1b
2:                     @ loop 2
    lsl r1,#1          @ shift left one bit upper quotient
    lsls r0,#1         @ shift left one bit lower quotient
    orrcs r1,#1        @ move bit 31 lower on upper
    cmp r5,r3          @ compare divisor and dividende
    cmpeq r4,r2
    bhi 3f
    subs r2,r2,r4      @ <  sub divisor from dividende lower
    sbc r3,r3,r5       @ and upper
    orr r0,r0,#1       @ move 1 on quotient
3:
    lsr r4,r4,#1       @ shift right one bit upper divisor
    lsrs r5,#1         @ and lower
    orrcs r4,#0x80000000 @ move bit 0 upper to  31 bit lower
    subs r6,#1         @ decrement shift counter
    bge 2b             @ if > 0 loop 2
    
100:
    pop {r3-r6,pc}


/***************************************************/
/*   Generation random number                  */
/***************************************************/
/* r0 contains limit  */
genereraleas:
    push {r1-r4,lr}                   @ save registers 
    ldr r4,iAdriGraine
    ldr r2,[r4]
    ldr r3,iNbDep1
    mul r2,r3,r2
    ldr r3,iNbDep1
    add r2,r2,r3
    str r2,[r4]                       @ save seed for next call 
    cmp r0,#0
    beq 100f
    mov r1,r0                         @ divisor
    mov r0,r2                         @ dividende
    bl division
    mov r0,r3                         @ résult = remainder
  
100:                                  @ end function
    pop {r1-r4,pc}                    @ restaur registers
iAdriGraine: .int iGraine
iNbDep1:     .int 0x343FD
iNbDep2:     .int 0x269EC3  
/***************************************************/
/*      ROUTINES INCLUDE                 */
/***************************************************/
/* for this file see task include a file in arm assembly */
.include "../affichage.inc"
Output:
Program 32 bits start
Prime N0 10001 : 104743
Program normal end.

Arturo

primes: select 2..110000 => prime?
print primes\[10000]
Output:
104743

AWK

Converted from FreeBASIC

# syntax: GAWK -f 10001TH_PRIME.AWK

BEGIN {
    printf("%s\n",main(10001))
    exit(0)
}
function main(n,  p,pn) {
    if (n == 1) { return(2) }
    p = 3
    pn = 1
    while (pn < n) {
      if (is_prime(p)) {
        pn++
      }
      p += 2
    }
    return(p-2)
}
function is_prime(n,  d) {
    d = 5
    if (n < 2) { return(0) }
    if (n % 2 == 0) { return(n == 2) }
    if (n % 3 == 0) { return(n == 3) }
    while (d*d <= n) {
      if (n % d == 0) { return(0) }
      d += 2
      if (n % d == 0) { return(0) }
      d += 4
    }
    return(1)
}

Idiomatic

# awk -f 10001prime.awk

# n: odd number and n>8
function IsOddPrime(n,	i,limit) {
 limit = int(sqrt(n))
 for (i=3;i <= limit;i+=2)
  if (n%i==0) return 0
 return 1
}

# pos: positive
function PrimePosition(pos,	prime){
 pos -= ( (pos==1) ? prime=2 : prime=3 ) - 1
 while (pos)
  if (IsOddPrime(prime+=2)) pos--
 return prime
}

BEGIN { print PrimePosition(10001) }
Output:
104743

BASIC

BASIC256

function isPrime(v)
	if v < 2 then return False
	if v mod 2 = 0 then return v = 2
	if v mod 3 = 0 then return v = 3
	d = 5
	while d * d <= v
		if v mod d = 0 then return False else d += 2
	end while
	return True
end function

function prime(n)
	if n=1 then return 2
	p = 3
	pn = 1
	while pn < n
		if isPrime(p) then pn += 1
		p += 2
	end while
	return p-2
end function

print prime(10001)
end

Chipmunk Basic

Works with: Chipmunk Basic version 3.6.4

The GW-BASIC solution works without any changes.

FreeBASIC

#include "isprime.bas"
function prime( n as uinteger ) as ulongint
    if n=1 then return 2
    dim as integer p=3, pn=1
    while pn<n
        if isprime(p) then pn + = 1
        p += 2
    wend
    return p-2
end function

print prime(10001)
Output:
104743

Gambas

'Use "isprime.bas"

Public Sub Main()

  Print prime(10001)
  
End

Function prime(n As Integer) As Long 

  If n = 1 Then Return 2 
  Dim p As Integer = 3, pn As Integer = 1 
  While pn < n 
    If isPrime(p) Then pn += 1 
    p += 2 
  Wend 
  Return p - 2 
  
End Function
Output:
104743

GW-BASIC

Works with: BASICA
10 PN = 1
20 P = 3
30 WHILE PN < 10001
40 GOSUB 100
50 IF Q = 1 THEN PN = PN + 1
60 P = P + 2
70 WEND
80 PRINT P - 2
90 END
100 REM Tests if a number is prime
110 Q = 0
120 IF P = 2 THEN Q = 1: RETURN
130 IF P = 3 THEN Q = 1: RETURN
140 I = 1
150 I = I + 2
160 IF INT(P / I) * I = P THEN RETURN
170 IF I * I <= P THEN GOTO 150
180 Q = 1
190 RETURN
Output:
104743

PureBasic

Procedure isPrime(v.i)
  If     v <= 1    : ProcedureReturn #False
  ElseIf v < 4     : ProcedureReturn #True
  ElseIf v % 2 = 0 : ProcedureReturn #False
  ElseIf v < 9     : ProcedureReturn #True
  ElseIf v % 3 = 0 : ProcedureReturn #False
  Else
    Protected r = Round(Sqr(v), #PB_Round_Down)
    Protected f = 5
    While f <= r
      If v % f = 0 Or v % (f + 2) = 0
        ProcedureReturn #False
      EndIf
      f + 6
    Wend
  EndIf
  ProcedureReturn #True
EndProcedure

Procedure prime(n.i)
  If n = 1 
    ProcedureReturn 2
  EndIf
  p.i = 3
  pn.i = 1
  While pn < n
    If isprime(p)
      pn + 1
    EndIf
    p + 2
  Wend
  ProcedureReturn p-2
EndProcedure

OpenConsole()
n = prime(10001)
PrintN(Str(n))
CloseConsole()

QB64

Trial Division Method

max=10001: n=1: p=0: t=Timer ' PRIMES.bas russian DANILIN
While n <= max ' 10001 104743 0.35 seconds
    f=0: j=2
    While f < 1
        If j >= p ^ 0.5 Then f=2
        If p Mod j = 0 Then f=1
        j=j+1
    Wend
    If f <> 1 Then n=n+1: ' Print n, p
    p=p+1
Wend
Print n-1, p-1, Timer-t
Output:
10001 104743 0.35 seconds

More Efficient TD Method

'JRace's results:
'Original version: 10001   104743  .21875
'This version:     10001   104743  .109375
max = 10001: n=1: p=0: t = Timer ' PRIMES.bas
While n <= max ' 10001 104743 0.35 seconds
    f = 0: j = 2
    pp = p^0.5 'NEW VAR: move exponentiation here, to outer loop
    While f < 1
        ' If j >= p ^ 0.5 Then f=2 'original line
        ' NOTE: p does not change in this loop,
        '      therefore p^0.5 doesn't change;
        '      moving p^0.5 to the outer loop will eliminate a lot of FP math)
        If j >= pp Then f=2 'new version with exponentiation relocated
        If p Mod j = 0 Then f=1
        j=j+1
    Wend
    If f <> 1 Then n=n+1: ' Print n, p
    p=p+1
Wend
Print n-1, p-1, Timer - t
Output:
10001 104743 0.11 seconds

True BASIC

Trial Division Method

Translation of: QB64
LET max = 10001
LET n = 1
LET p = 0
DO WHILE n <= max
   LET f = 0
   LET j = 2
   DO WHILE f < 1
      IF j >= p^0.5 THEN LET f = 2
      IF REMAINDER(p, j) = 0 THEN LET f = 1
      LET j = j+1
   LOOP
   IF f <> 1 THEN LET n = n+1
   LET p = p+1
LOOP
PRINT p-1
END
Output:
104743

Yabasic

sub isPrime(v)
    if v < 2 then return False : fi
    if mod(v, 2) = 0 then return v = 2 : fi
    if mod(v, 3) = 0 then return v = 3 : fi
    d = 5
    while d * d <= v
        if mod(v, d) = 0 then return False else d = d + 2 : fi
    wend
    return True
end sub

sub prime(n)
    if n = 1 then return 2 : fi
    p = 3 
	pn = 1
    while pn<n
        if isPrime(p) then pn = pn + 1 : fi
        p = p + 2
    wend
    return p-2
end sub

print prime(10001)
end

bc

a[0] = 2
a[o = 1] = 3
for (n = 5; o < 10000; n += 2) {
    for (i = 1; n % (p = a[i]) != 0; ++i) {
        if (p * p > n) {
            a[++o] = n
            break
        }
    }
}
a[o]
Output:
104743

C

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

int isprime( int p ) {
    int i;
    if(p==2) return 1;
    if(!(p%2)) return 0;
    for(i=3; i*i<=p; i+=2) {
       if(!(p%i)) return 0;
    }
    return 1;
}

int prime( int n ) {
    int p, pn=1;
    if(n==1) return 2;
    for(p=3;pn<n;p+=2) {
        if(isprime(p)) pn++;
    }
    return p-2;
}

int main(void) {
    printf( "%d\n", prime(10001) );
    return 0;
}
Output:
104743

C#

Sieve vs Trial Division

Comparing performance of the one-at-a-time trial division method vs the sieve of Eratosthenes method. About ten times faster for the sieve. It may appear that the sieve may be off by one, pr[10000] but since the array is zero based, it's the 10001st value.

using System; class Program {

  static bool isprime(uint p ) { if ((p & 1) == 0) return p == 2;
    if ((p % 3) == 0) return p == 3;
    for (uint i = 5, d = 4; i * i <= p; i += (d = 6 - d))
      if (p % i == 0) return false; return true; }
 
  static uint prime(uint n) { uint p, d, pn;
    for (p = 5, d = 4, pn = 2; pn < n; p += (d = 6 - d))
      if (isprime(p)) pn++; return p - d; }

  static void Main(string[] args) {
    Console.WriteLine("One-at-a-time trial division vs sieve of Eratosthenes");
    var sw = System.Diagnostics.Stopwatch.StartNew();
    var t = prime(10001); sw.Stop(); double e1, e2;
    Console.Write("{0:n0} {1} ms", prime(10001),
      e1 = sw.Elapsed.TotalMilliseconds);
    sw.Restart(); uint n = 105000, i, j; var pr = new uint[10100];
    pr[0] = 2; pr[1] = 3; uint pc = 2, r, d, ii;
    var pl = new bool[n + 1]; r = (uint)Math.Sqrt(n);
    for (i = 9; i < n; i += 6) pl[i] = true;
    for (i = 5, d = 4; i <= r; i += (d = 6 - d)) if (!pl[i]) {
      pr[pc++] = i; for (j = i * i, ii = i << 1; j <= n; j += ii)
        pl[j] = true; }
    for ( ;i <= n; i += (d = 6 - d)) if (!pl[i]) pr[pc++] = i;
    t = pr[10000]; sw.Stop();
    Console.Write("  {0:n0} {1} μs  {2:0.000} times faster", t,
      (e2 = sw.Elapsed.TotalMilliseconds) * 1000.0, e1 / e2); } }
Output @ Tio.run:
One-at-a-time trial division vs sieve of Eratosthenes
104,743 3.8943 ms  104,743 357.9 μs  10.881 times faster

Alternative Trial Division Method

using System; using System.Text; // PRIME_numb.cs russian DANILIN
namespace p10001 // 1 second  10001  104743 
{ class Program // rextester.com/ZBEPGE34760
    { static void Main(string[] args)
        { int max=10001; int n=1; int p=1; int f; int j; long s;
            while (n <= max) 
            { f=0; j=2; s=Convert.ToInt32(Math.Pow(p,0.5));
                while (f < 1) 
                { if (j >= s) 
                    { f=2; } 
                  if (p % j == 0) { f=1; }
                  j++;
                }
                if (f != 1) { n++; } // Console.WriteLine("{0} {1}", n, p);
                p++;
            }
Console.Write("{0} {1}", n-1, p-1);
Console.ReadKey(); 
}}}
Output:
104743

C++

Library: Primesieve
#include <iostream>
#include <locale>

#include <primesieve.hpp>

int main() {
    std::cout.imbue(std::locale(""));
    std::cout << "The 10,001st prime is " << primesieve::nth_prime(10001) << ".\n";
}
Output:
The 10,001st prime is 104,743.

COBOL

Limit based on the fact that the nth prime is guaranteed to be less than n * (ln n + ln(ln n)).

IDENTIFICATION DIVISION.
       PROGRAM-ID. 10001th_prime.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 n        PIC 9(3)    COMP.
       01 cnt      PIC 9(5)    COMP    VALUE 1.
       01 sieve.
           05 isp  PIC 9               VALUE 1 OCCURS 115000 TIMES 
                                       INDEXED BY i.
       01 out      PIC Z(10).

       PROCEDURE DIVISION.
           PERFORM VARYING n FROM 2 BY 1 UNTIL n * n > 115000
               SET i TO n

               IF isp(i) = 1
                   MULTIPLY n BY n GIVING i
                   PERFORM VARYING i FROM i BY n UNTIL i > 115000
                       SET isp(i) TO 0
                   END-PERFORM
           
           END-PERFORM

           SET i to 1
           
           PERFORM UNTIL cnt = 10001
               SET i UP BY 2
               ADD isp(i) TO cnt
           END-PERFORM

           MOVE i TO out
           DISPLAY FUNCTION TRIM (out)
           STOP RUN.
Output:
104743

Dart

import 'dart:math';

bool isPrime(int n) {
  if (n <= 1) return false;
  if (n == 2) return true;
  for (int i = 2; i <= sqrt(n); ++i) {
    if (n % i == 0) return false;
  }
  return true;
}

int prime(int n) {
  int p, pn = 1;
  if (n == 1) return 2;
  for (p = 3; pn < n; p += 2) {
    if (isPrime(p)) pn++;
  }
  return p - 2;
}

void main() {
  print(prime(10001));
}
Output:
104743

Delphi

Works with: Delphi version 6.0
Library: none
function IsPrime(N: integer): boolean;
{Fast, optimised prime test}
var I,Stop: integer;
begin
if (N = 2) or (N=3) then Result:=true
else if (n <= 1) or ((n mod 2) = 0) or ((n mod 3) = 0) then Result:= false
else
     begin
     I:=5;
     Stop:=Trunc(sqrt(N));
     Result:=False;
     while I<=Stop do
           begin
           if ((N mod I) = 0) or ((N mod (I + 2)) = 0) then exit;
           Inc(I,6);
           end;
     Result:=True;
     end;
end;


function Find10001thPrime: integer;
{Return the 10,001th prime number}
var Count: integer;
begin
Count:=1;
Result:= 3;
while true do
	begin
	if IsPrime(Result) then Count:= Count+1;
	if Count=10001 then exit;
	Inc(Result,2);
	end;
end;
Output:
10,001th Prime= 104,743

D

Translation of: C
import std.stdio;

int isprime( int p ) {
    int i;
	
    if(p==2) return 1;

    if(!(p%2)) return 0;
	
    for(i=3; i*i<=p; i+=2) {
       if(!(p%i)) return 0;
    }
	
    return 1;
}

int prime( int n ) {
	
    if(n==1) return 2;
	
    int p, pn=1;
	
    for(p=3;pn<n;p+=2) {
        if(isprime(p)) pn++;
    }
	
    return p-2;
}

void main()
{
	writeln(prime(10_001));
}
Output:
104743

DuckDB

Works with: DuckDB version V1.0
# Is nnumber prime?
create or replace function primep(nnumber) as (
  select
    case
    when nnumber < 2 then false
    when nnumber = 2 then true
    else NOT exists
         ( select * from 
           ( select (nnumber % anumber) as modNumber
             from (select unnest(range(2, 1 + sqrt(nnumber)::BIGINT)) as anumber)
           ) 
           where modNumber = 0 
         )
    end
);

create or replace function nth_prime(n) as (
  if (n <= 0, 0,
  if (n  = 1, 2,
  (with recursive cte as (
     select 2 as prime, 3 as candidate, true as pprime, 1 as nth
     union all
     select if(pprime, candidate, prime) as prime,
            candidate+2 as candidate,
            primep(candidate+2) as pprime,
            if(pprime,1,0)+nth as nth
     from cte
     where nth < n
  )
  select prime from cte where nth = n
  )))
);
  
select nth_prime(10001)
Output:
┌──────────────────┐
│ nth_prime(10001) │
│      int32       │
├──────────────────┤
│           104743 │
└──────────────────┘

Erlang

-module(task_10001th_prime).

-export([main/0]).

% 2 and 3 are both primes, so we start searching at 5
main() -> search(5, 2, 2).

search(N, Inc, Count) when Count < 10_001 ->
    case is_prime(N) of
        true -> search(N + Inc, 6 - Inc, Count + 1);
        false -> search(N + Inc, 6 - Inc, Count)
    end;
search(N, Inc, _) -> N - 6 + Inc.

is_prime(P) -> is_prime(P, 5, 2).

is_prime(N, P, _) when P * P > N -> true;
is_prime(N, P, _) when N rem P =:= 0 -> false;
is_prime(N, P, Inc) -> is_prime(N, P + Inc, 6 - Inc).
Output:
 timer:tc(task_10001th_prime, main, []).
{68615,104743}

EasyLang

fastfunc isprim num .
   i = 3
   while i <= sqrt num
      if num mod i = 0
         return 0
      .
      i += 2
   .
   return 1
.
nprim = 1
i = 3
repeat
   if isprim i = 1
      nprim += 1
   .
   until nprim = 10001
   i += 2
.
print i
Output:
104743

F#

This task uses Extensible Prime Generator (F#)

// 10001st prime. Nigel Galloway: November 22nd., 2021
printfn $"%d{Seq.item 10000 (primes32())}"
Output:
104743

Factor

USING: math math.primes prettyprint ;

2 10,000 [ next-prime ] times .
Output:
104743

Fermat

Prime(10001);
Output:
104743

Frink

nth1[primes[], 10001]
Output:
104743

FutureBasic

local fn IsPrime( n as NSUInteger ) as BOOL
  BOOL       isPrime = YES
  NSUInteger i
  
  if n < 2        then exit fn = NO
  if n = 2        then exit fn = YES
  if n mod 2 == 0 then exit fn = NO
  for i = 3 to int(n^.5) step 2
    if n mod i == 0 then exit fn = NO
  next
end fn = isPrime


local fn Prime( n as NSUInteger ) as long
  long p = 3, pn = 1
  
  if n = 1 then exit fn = 2
  while ( pn < n )
    if fn IsPrime( p ) then pn++
    p += 2
  wend
  p -= 2
end fn = p

print fn Prime(10001)

HandleEvents
Output:
104743

Go

package main

import "fmt"

func isPrime(n int) bool {
    if n == 1 {
        return false
    }
    i := 2
    for i*i <= n {
        if n%i == 0 {
            return false
        }
        i++
    }
    return true
}

func main() {
    var final, pNum int

    for i := 1; pNum < 10001; i++ {
        if isPrime(i) {
            pNum++
        }
        final = i
    }
    fmt.Println(final)
}
Output:
104743

Haskell

Relying upon the nontrivial fact that for every natural n >= 3 there exists a prime p with sqrt(n) < p < n to avoid looping infinitely:

primes :: [Int]
primes = (2 :) $ filter ( \n -> and $ map ((/= 0) . (rem n)) $ takeWhile ((<= n) . (^ 2)) $ primes ) $ [3,5..]

main = print $ primes !! 10000
Output:
104743

J

p:10000      NB. the index starts at 0; p:0 = 2
Output:
104743

Java

Uses the PrimeGenerator class from Extensible prime generator#Java.

public class NthPrime {
    public static void main(String[] args) {
        System.out.printf("The 10,001st prime is %,d.\n", nthPrime(10001));
    }

    private static int nthPrime(int n) {
        assert n > 0;
        PrimeGenerator primeGen = new PrimeGenerator(10000, 100000);
        int prime = primeGen.nextPrime();
        while (--n > 0)
            prime = primeGen.nextPrime();
        return prime;
    }
}
Output:
The 10,001st prime is 104,743.


JavaScript

Prime 10001 from Russia jdoodle.com/h/2V1

var max = 10001, n=1, p=1; var f,j,s  
while (n <= max) 
{ f=0; j=2; s = parseInt(Math.pow(p, 0.5))
   while (f < 1)
      { if (j >= s) f=2  
        if ( p % j == 0 ) f=1  
        j++
      }
   if (f != 1) n++ // { document.write(n +" "+ p +"<br>") }
   p++
}
document.write("<br>"+ (n-1) +" "+ (p-1) +"<br>" )
Output:
10001 104743

jq

Works with: jq

Works with gojq, the Go implementation of jq

A solution without any pre-determined numbers or guesses.

See Erdős-primes#jq for a suitable definition of `is_prime` as used here.

# Output: a stream of the primes
def primes: 2, (range(3; infinite; 2) | select(is_prime));

# The task
# jq uses an index-origin of 1 and so:
nth(10000; primes)
Output:
104743

Julia

julia> using Primes

julia> prime(10001)
104743

Mathematica / Wolfram Language

Prime[10001]
Output:

104743


Maxima

primes_first_n(n) := (
           if n<=1 then
               []
           else (
               L : [2],
               for i:2 thru n do (
                   L : append(L, [next_prime(last(L))])
               ),
               L
           )
       )$
last(primes_first_n(10001));
Output:

104743

MiniScript

isPrime = function(n)
	s = floor(n ^ 0.5)
	for i in range(2, s)
		if n % i == 0 then return false
	end for
	return true
end function

tt = time
c = 2
p = 2
lastPrime = 2
while c < 10001
	p += 1
	if isPrime(p) then 
		c += 1
	end if
end while
print p
Output:
104743

Nim

func isPrime(n: Positive): bool =
  ## Return true if "n" is prime.
  ## Assume n >= 5 and n not multiple of 2 and 3.
  var d = 5
  var step = 2
  while d * d <= n:
    if n mod d == 0:
      return false
    inc d, step
    step = 6 - step
  result = true

iterator primes(): tuple[rank, value: int] =
  ## Yield the primes preceded by their rank in the sequence.
  yield (1, 2)
  yield (2, 3)
  var idx = 2
  var n = 5
  var step = 2
  while true:
    if n.isPrime:
      inc idx
      yield (idx, n)
    inc n, step
    step = 6 - step

for (i, n) in primes():
  if i == 10001:
    echo "10001st prime: ", n
    break
Output:
10001st prime: 104743

OCaml

Using the function seq_primes from Extensible prime generator#OCaml:

let () =
  seq_primes |> Seq.drop 10000 |> Seq.take 1 |> Seq.iter (Printf.printf "%u\n")
Output:
104743

PARI/GP

prime(10001)
Output:
%1 = 104743

Pascal

Free Pascal

Program nth_prime;

Function nthprime(x : uint32): uint32;
Var primes : array Of uint32;
  i,pr,count : uint32;
  found : boolean;
Begin
  setlength(primes, x);
  primes[1] := 2;
  count := 1;
  i := 3;
  Repeat
    found := FALSE;
    pr := 0;
    Repeat
      inc(pr);
      found := i Mod primes[pr] = 0;
    Until (primes[pr]*primes[pr] > i) Or found;
    If Not found Then
      Begin
        inc(count);
        primes[count] := i;
      End;
    inc(i,2);
  Until count = x;
  nthprime := primes[x];
End;

Begin
  writeln(nthprime(10001));
End.
Output:
104743

Perl

Library: ntheory
use strict;
use warnings;
use feature 'say';

# the lengthy wait increases the delight in finally seeing the answer
my($n,$c) = (1,0);
while () {
    $c++ if (1 x ++$n) !~ /^(11+)\1+$/;
    $c == 10_001 and say $n and last;
}

# or if for some reason you want the answer quickly
use ntheory 'nth_prime';
say nth_prime(10_001);
Output:
104743
104743

Phix

with js ?get_prime(10001)
Output:
104743

Picat

go ?=>
  println(nth_prime(10001)),

  % faster but probably considered cheating
  nth(10001,primes(200000),P),
  println(P).

nth_prime(Choosen) = P =>
   nth_prime(1,0,Choosen, P).

nth_prime(Num, Choosen, Choosen, Num) :-
  prime(Num).
nth_prime(Num, Ix, Choosen, P) :-
   Ix < Choosen,
   next_prime(Num, P2),
   nth_prime(P2, Ix+1, Choosen, P).

next_prime(Num, P) :-
  next_prime2(Num+1, P).
next_prime2(Num, Num) :-
  prime(Num).
next_prime2(Num, P) :-
   next_prime2(Num+1,P).
Output:
104743
104743

Prolog

for swi-prolog

isPrime(2).                 % prime generator
isPrime(N):-
	between(3, inf, N),
	N /\ 1 > 0,             % odd
	M is floor(sqrt(N)) - 1, % reverse 2*I+1
	Max is M div 2,
	forall(between(1, Max, I), N mod (2*I+1) > 0).

do:- Index is 10001,
	findnsols(Index, N, isPrime(N), PrimeList),!,
	last(PrimeList, PrimeAtIndex),
	format('prime(~d) is ~d', [Index, PrimeAtIndex]), nl.
Output:
?- do.
prime(10001) is 104743
true.

Python

Trial Division Method

#!/usr/bin/python

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0:
            return False        
    return True

def prime(n: int) -> int:
    if n == 1:
        return 2
    p = 3
    pn = 1
    while pn < n:
        if isPrime(p):
            pn += 1
        p += 2
    return p-2

if __name__ == '__main__':
    print(prime(10001))
Output:
104743

Alternative Trial Division Method

import time; max=10001; n=1; p=1; # PRIME_numb.py russian DANILIN 
while n<=max: # 78081 994271 45 seconds
    f=0; j=2; s = int(p**0.5) # rextester.com/AAOHQ6342
    while f < 1:
        if j >= s:
            f=2
        if p % j == 0:
            f=1
        j+=1
    if f != 1:
        n+=1;
        #print(n,p);
    p+=1
print(n-1,p-1)
print(time.perf_counter())
Output:
10001 104743 7 seconds

Quackery

The 10001st prime number is the 10000th odd prime number.

prime is defined at Miller–Rabin primality test#Quackery.

  1 10000 times [ 2 + dup prime until ] echo
Output:
104743

R

library(primes)
nth_prime(10001)
Output:
104743

Racket

#lang racket
(require math/number-theory)
; Index starts at 0, (nth-prime 0) is 2
(nth-prime 10000)
Output:
104743

Raku

say (^∞).grep( &is-prime )[10000]
Output:
104743

REXX

The task has no stretch goal, nevertheless I will try one: showing primes higher in de sequence.

Trial division

/* REXX */
Parse Version v
Say v
Call Time 'R'
z=1
p.0=3
p.1=2
p.2=3
p.3=5
Do n=5 By 2 Until z=10001
  If right(n,1)=5 Then Iterate
  Do i=2 To p.0 Until b**2>n
    b=p.i
    If n//b=0 Then Leave
    End
  If b**2>n Then Do
    z=p.0+1
    p.z=n
    p.0=z
    End
  End
Say z n time('E')
Output:
H:\>rexx prime10001
REXX-ooRexx_5.0.0(MT)_64-bit 6.05 8 Sep 2020
10001 104743 0.219000

H:\>regina prime10001
REXX-Regina_3.9.4(MT) 5.00 25 Oct 2021
10001 104743 .615000

Finding the 100001th prime number:

REXX-ooRexx_5.0.0(MT)_64-bit 6.05 23 Dec 2022
100001 1299721 11.989000

REXX-Regina_3.9.6(MT) 5.00 29 Apr 2024
100001 1299721 19.117000

Sieve

Libraries: How to use
Libraries: Source code

As some other REXX entries suggest, using a sieve is fast, but requires memory to store the primes. Consider following program, based on the property 'nth prime < n*(ln(n)+ln(ln(n)))'.

include Settings

say version; say '10001th prime'; say
call Primes(-10001)
say prim.prime.10001
say Format(Time('e'),,3) 'seconds'
exit

include Functions
include Numbers
include Sequences
include Constants

include Abend
Output:
REXX-Regina_3.9.6(MT) 5.00 29 Apr 2024
10001th prime

104743
0.039 seconds

Ring

load "stdlib.ring"
see "working..." + nl
num = 0 pr = 0 limit = 10001

while true
      num++
      if isprime(num) pr++ ok
      if pr = limit exit ok
end

see "" + num + nl + "done..." + nl
Output:
working...
The 10001th prime is: 104743
done...

RPL

Works with: HP version 49
« 2
  1 10000 START NEXTPRIME NEXT
» 'TASK' STO
Output:
1: 104743

Ruby

require "prime"
puts  Prime.lazy.drop(10_000).next
Output:
104743

Rust

// [dependencies]
// primal = "0.3"

fn main() {
    let p = primal::StreamingSieve::nth_prime(10001);
    println!("The 10001st prime is {}.", p);
}
Output:
The 10001st prime is 104743.

Scala

Scala3 ready

object Prime10001 extends App {

  val oddPrimes: LazyList[Int] = 3 #:: LazyList.from(5, 2)
        .filter(p => oddPrimes.takeWhile(_ <= math.sqrt(p)).forall(p % _ > 0))
  val primes = 2 #:: oddPrimes
  
  val index = 10_001
  println(s"prime($index): " + primes.drop(index - 1).take(1).head)
}
Output:
prime(10001): 104743

Sidef

say 10001.prime
Output:
104743

Wren

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

var n = 10001
var limit = (n.log * n * 1.2).floor  // should be enough
var primes = Int.primeSieve(limit)
Fmt.print("The $,r prime is $,d.", n, primes[n-1])
Output:
The 10,001st prime is 104,743.

x86 Assembly

Using the Sieve of Eratosthenes and n * (ln n + ln(ln n)) as the upper limit for finding the nth prime.

section .data
    primes times 14375 db 255   ;N * (ln N + ln(ln N)) bits, rounded up

section .text
    global main

main:
    mov     ebx, 1          ;array index for outer loop
    xor     ecx, ecx        ;counter

sieve_outer:
    inc     ebx             ;increase index
    mov     eax, ebx        ;copy to eax for squaring
    mul     ebx             ;square
    cmp     eax, 115000     ;check if square is > limit    
    jg      find10001st     ;if it is, sieve is done
    bt      [primes], ebx   ;check if ebx is no prime
    jnc     sieve_outer     ;if no prime, try next number
    inc     ecx             ;else increase counter

sieve_inner:
    btr     [primes], eax   ;set multiple to not prime
    add     eax, ebx        ;next multiple
    cmp     eax, 115000     ;check if multiple is < limit
    jl      sieve_inner     ;if it is, continue with inner loop
    jmp     sieve_outer     ;if not, continue with outer loop

find10001st:
    inc     ebx             ;increase array index
    bt      [primes], ebx   ;is it prime?
    adc     ecx, 0          ;if yes, increase ecx
    cmp     ecx, 10001      ;check if counter arrived at 10001
    jl      find10001st     ;if not, continue
                            ;done, result in ebx
Output:
104743

XPL0

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

int C, N;
[C:= 1;         \count 2 as first prime
N:= 3;
loop    [if IsPrime(N) then
            [C:= C+1;
            if C = 10001 then quit;
            ];
        N:= N+2;
        ];
IntOut(0, N);
]
Output:
104743


Zig

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

const limit = 10001;

fn isPrime(x: usize) bool {
    if (x % 2 == 0) return false;

    var i: usize = 3;
    while (i * i <= x) : (i += 2) {
        if (x % i == 0) return false;
    }
    return true;
}

pub fn main() !void {
    var cnt: usize = 0;
    var last: usize = 0;
    var n: usize = 1;

    while (cnt < limit) : (n += 1) {
        if (isPrime(n)) {
            cnt += 1;
            last = n;
        }
    }
    try stdout.print("{d}st prime number is: {d}\n", .{ limit, last });
}
Output:
10001st prime number is: 104743
Cookies help us deliver our services. By using our services, you agree to our use of cookies.