Jump to content

Sort primes from list to a list

From Rosetta Code
Sort primes from list to a list 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


Let given list:
Primes = [2,43,81,122,63,13,7,95,103]
Show on this page the ascending ordered list of primes from given list.

-- Rosetta Code Task written in Ada
-- Sort primes from list to a list
-- https://rosettacode.org/wiki/Sort_primes_from_list_to_a_list
-- Sort procedure taken from Ada task: "Sorting algorithms/Insertion sort"
-- November 2025, R. B. E.

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

procedure Extract_and_Sort_Primes is

  type Data_Array is array(Natural range <>) of Integer;
 
  procedure Insertion_Sort(Item : in out Data_Array) is
    First : Natural := Item'First;
    Last  : Natural := Item'Last;
    Value : Integer;
    J     : Integer;
  begin
    for I in (First + 1)..Last loop
      Value := Item(I);
      J := I - 1;
      while J in Item'range and then Item(J) > Value loop
        Item(J + 1) := Item(J);
        J := J - 1;
      end loop;
      Item(J + 1) := Value;
    end loop;
  end Insertion_Sort;

  function Is_Prime (P : Positive) return Boolean is
    D : Positive := 5;
  begin
    if (P < 2) then
      return False;
    end if;
    if ((P mod 2) = 0) then
      return (P = 2);
    end if;
    if ((P mod 3) = 0) then
      return (P = 3);
    end if;
    while ((D * D) <= P) loop
      if ((P mod D) = 0) then
        return False;
      end if;
      D := D + 2;
    end loop;
    return True;
  end Is_Prime;

  Data : Data_Array := (2, 43, 81, 122, 63, 13, 7, 95, 103);

begin
  New_Line;
  Put_Line ("Task: Sort primes from list to a list");
  New_Line;
  Put_Line ("Data (as provided by task description) prior to sorting:");
  for Number of Data loop
    Put (Number, 4);
  end loop;
  New_Line (2);
  Insertion_Sort (Data);
  Put_Line ("Provided data after sorting:");
  for Number of Data loop
    Put (Number, 4);
  end loop;
  New_Line (2);
  Put_Line ("Prime numbers extracted from the provided data:");
  for Number of Data loop
    if Number > 0 and then Is_Prime (Number) then
      Put (Number, 4);
    end if;
  end loop;
  New_Line;
end Extract_and_Sort_Primes;
Output:
Task: Sort primes from list to a list

Data (as provided by task description) prior to sorting:
   2  43  81 122  63  13   7  95 103

Provided data after sorting:
   2   7  13  43  63  81  95 103 122

Prime numbers extracted from the provided data:
   2   7  13  43 103

Sorting after finding the primes

Library: ALGOL 68-rows
Library: ALGOL 68-sort
BEGIN # extract the elements of a list that are prime and sort them           #
    PR read "primes.incl.a68" PR                    # include prime utilities #
    PR read "rows.incl.a68"   PR              # include row (array) utilities #
    PR read "sort.incl.a68"   PR                  # include sorting utilities #
    # list of numbers required by the task #
    []INT list = (  2, 43, 81, 122, 63, 13, 7, 95, 103 );
    [ 1 : UPB list ]INT prime list;
    # count the nunber of primes in list and assign the primes to prime list  #
    INT p count := 0;
    FOR i TO UPB list DO
        IF is probably prime( list[ i ] ) THEN
            # have a prime #
            prime list[ p count +:= 1 ] := list[ i ]
        FI
    OD;
    print( ( "prime elements of: " ) );
    SHOW list;
    print( ( newline, "              are: " ) );
    SHOW ( prime list QUICKSORT ELEMENTS( 1, p count ) )[ 1 : p count ]
END
Output:
prime elements of:  2 43 81 122 63 13 7 95 103
              are:  2 7 13 43 103

Sorting whilst finding the primes

Translation of: EasyLang

Some of the other samples have interpreted the task to mean sort as the primes are discovered, this follows their approach.

BEGIN # sort primes from a list to a list - translation of EasyLang #

    PROC is prime = ( INT n )BOOL:
         IF   n < 2 THEN FALSE
         ELIF NOT ODD n THEN n = 2
         ELSE
            INT root n = ENTIER sqrt( n );
            BOOL result := TRUE;
            FOR i FROM 3 BY 2 TO root n WHILE result := n MOD i /= 0 DO SKIP OD;
            result
         FI # is prime # ;

    PROC insert = ( INT v, REF[]INT d, REF INT d pos )VOID:
         BEGIN
            INT i pos := d pos;
            d pos +:= 1;
            IF i pos > LWB d THEN
                WHILE i pos > LWB d AND d[ i pos ] > v DO
                    d[ i pos + 1 ] := d[ i pos ];
                    i pos -:= 1
                OD
            FI;
            d[ i pos + 1 ] := v
         END # insert # ;

    []INT list = ( 2, 43, 81, 122, 63, 13, 7, 95, 103 );
    [ LWB list : UPB list ]INT sorted primes;
    INT prime pos := LWB list - 1;
    FOR l pos FROM LWB list TO UPB list DO
        INT p = list[ l pos ];
        IF is prime( p ) THEN insert( p, sorted primes, prime pos ) FI
    OD;
    FOR l pos FROM LWB sorted primes TO prime pos DO
        print( ( " ", whole( sorted primes[ l pos ], 0 ) ) )
    OD;
    print( ( newline ) )

END
Output:
 2 7 13 43 103

The strangely worded title and task description suggest to this native English speaker that the task is to sort each prime into the primes list as it's identified, which is certainly a less pointless coding exercise than simply extracting all the primes and then sorting them. The implementation here allows for the primes list to be created from scratch or supplied with a few ordered numbers already in it. The sort process is part of an insertion sort.

on isPrime(n)
    if (n < 4) then return (n > 1)
    if ((n mod 2 is 0) or (n mod 3 is 0)) then return false
    repeat with i from 5 to (n ^ 0.5) div 1 by 6
        if ((n mod i is 0) or (n mod (i + 2) is 0)) then return false
    end repeat
    
    return true
end isPrime

-- primes list created from scratch.
on sortPrimesFromList:givenList
    return my sortPrimesFromList:givenList toList:{}
end sortPrimesFromList:

-- primes list supplied as a parameter, its current contents assumed to be already ordered ascending.
on sortPrimesFromList:givenList toList:primes
    set j to (count primes)
    repeat with this in givenList
        set this to this's contents
        if (isPrime(this)) then
            set end of primes to this
            set j to j + 1
            if (j > 1) then
                repeat with i from (j - 1) to 1 by -1
                    set v to primes's item i
                    if (v > this) then
                        set primes's item (i + 1) to v
                    else
                        set i to i + 1
                        exit repeat
                    end if
                end repeat
                set primes's item i to this
            end if
        end if
    end repeat
    
    return primes
end sortPrimesFromList:toList:

on demo()
    set primes to my sortPrimesFromList:{2, 43, 81, 22, 63, 13, 7, 95, 103}
    log primes
    my sortPrimesFromList:{8, 137, 19, 5, 44, 23} toList:primes
    log primes
end demo

demo()
Output:
Log:
(*2, 7, 13, 43, 103*)
(*2, 5, 7, 13, 19, 23, 43, 103, 137*)
lst: [2 43 81 122 63 13 7 95 103]

print sort select lst => prime?
Output:
2 7 13 43 103
Primes := [2,43,81,122,63,13,7,95,103]

t := [], result := []
for i, n in Primes
	if isPrime(n)
		t[n, i] := true
	
for n, obj in t
    for i, v in obj
        result.push(n)
	
isPrime(n){
	Loop, % floor(sqrt(n))
		v := A_Index = 1 ? n : mod(n,A_Index) ? v : v "," A_Index "," n//A_Index
	Return (v = n)
}
Output:
[2, 7, 13, 43, 103]
# syntax: GAWK -f SORT_PRIMES_FROM_LIST_TO_A_LIST.AWK
BEGIN {
    PROCINFO["sorted_in"] = "@val_num_asc"
    split("2,43,81,122,63,13,7,95,103",arr,",")
    for (i in arr) {
      if (is_prime(arr[i])) {
        printf("%d ",arr[i])
      }
    }
    printf("\n")
    exit(0)
}
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)
}
Output:
2 7 13 43 103


Translation of: FreeBASIC
arraybase 1
global temp

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

subroutine sort(array)
	for i = 1 to array[?]
		for j = i + 1 to array[?]
			if temp[i] > temp[j] then
				t = temp[i] : temp[i] = temp[j] : temp[j] = t
			end if
		next j
	next i
end subroutine

subroutine showArray(array)
	txt$ = ""
	print "[";
	for n = 1 to array[?]
		txt$ &= string(array[n]) & ","
	next n
	txt$ = left(txt$,length(txt$)-1)
	txt$ &= "]"
	print txt$
end subroutine

dim Primes(9)
Primes[1] = 2
Primes[2] = 43
Primes[3] = 81
Primes[4] = 122
Primes[5] = 63
Primes[6] = 13
Primes[7] = 7
Primes[8] = 95
Primes[9] = 103
c = 1

for n = 1 to Primes[?]
	if isprime(Primes[n]) then
		redim temp(c)
		temp[c] = Primes[n]
		c += 1
	end if
next n
call sort(temp)
call showArray(temp)
end
Output:
Igual que la entrada de FreeBASIC.
Dim Shared As Integer temp()

Function isPrime(Byval ValorEval As Integer) As Boolean
    If ValorEval <= 1 Then Return False
    For i As Integer = 2 To Int(Sqr(ValorEval))
        If ValorEval Mod i = 0 Then Return False
    Next i
    Return True
End Function

Sub sort(array() As Integer)
    For i As Integer = Lbound(array) To Ubound(array)
        For j As Integer = i + 1 To Ubound(array)
            If temp(i) > temp(j) Then Swap temp(i), temp(j)
        Next j
    Next i
End Sub

Sub showArray(array() As Integer)
    Dim As String txt = ""
    Print "[";
    For n As Integer = Lbound(array) To Ubound(array)
        txt &= Str(array(n)) & ","
    Next n
    txt = Left(txt,Len(txt)-1)
    txt &= "]"
    Print txt
End Sub

Dim As Integer Primes(1 To 9) = {2,43,81,122,63,13,7,95,103}
Dim As Integer c = 0

For n As Integer = Lbound(Primes) To Ubound(Primes)
    If isprime(Primes(n)) Then
        Redim Preserve temp(c)
        temp(c) = Primes(n)
        c += 1
    End If
Next n 
sort(temp())
showArray(temp())
Sleep
Output:
[2,7,13,43,103]
dim Primes(9)
Primes(1) = 2
Primes(2) = 43
Primes(3) = 81
Primes(4) = 122
Primes(5) = 63
Primes(6) = 13
Primes(7) = 7
Primes(8) = 95
Primes(9) = 103
c = 1

for n = 1 to arraysize(Primes(),1)
	if isPrime(Primes(n)) then
		redim temp(c)
		temp(c) = Primes(n)
		c = c + 1
	end if
next n
sort(temp)
showArray(temp)
end

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 sort(array)
	for i = 1 to arraysize(temp(),1)
		for j = i + 1 to arraysize(temp(),1)
			if temp(i) > temp(j) then
				t = temp(i) : temp(i) = temp(j) : temp(j) = t
			end if
		next j
	next i
end sub

sub showArray(array)
	local txt$ //= ""
	print "[";
	for n = 1 to arraysize(temp(),1)
		txt$ = txt$ + str$(temp(n)) + ","
	next n
	txt$ = left$(txt$,len(txt$)-1)
	txt$ = txt$ + "]"
	print txt$
end sub
Output:
Igual que la entrada de FreeBASIC.
#include <algorithm>
#include <cstdint>
#include <iostream>
#include <iterator>
#include <ranges>
#include <vector>

bool is_prime(const uint32_t& number) {
	if ( number % 2 == 0 ) {
		return number == 2;
	}

	uint32_t k = 3;
	while ( k * k <= number ) {
		if ( number % k == 0 ) {
			return false;
		}
		k += 2;
	}
	return true;
}


int main() {
	const std::vector<uint32_t> elements = { 2, 43, 81, 122, 63, 13, 7, 95, 103 };
	std::vector<uint32_t> primes;

	for ( const uint32_t& element : elements ) {
		if ( is_prime(element) ) {
			primes.emplace_back(element);
		}
	}

	std::sort(primes.begin(), primes.end());
	std::ranges::copy(primes, std::ostream_iterator<uint32_t>(std::cout, " "));
}
Output:
2 7 13 43 103
Works with: Delphi version 6.0

Uses Delphi TList object to hold and sort the data.

{Raw data to process}

var NumList: array [0..8] of integer = (2,43,81,122,63,13,7,95,103);

function Compare(P1,P2: pointer): integer;
{Compare for quick sort}
begin
Result:=Integer(P1)-Integer(P2);
end;

procedure GetSortedPrimes(Nums: Array of integer; var IA: TIntegerDynArray);
{Extract data from array "Nums" and return a sorted list of primes}
var I: integer;
var List: TList;
begin
List:=TList.Create;
try
{Put the primes in the TList object}
for I:=0 to High(Nums) do
 if IsPrime(Nums[I]) then List.Add(Pointer(Nums[I]));
{Sort the list}
List.Sort(Compare);
{Put the result in array}
SetLength(IA,List.Count);
for I:=0 to List.Count-1 do
 IA[I]:=Integer(List[I]);
finally List.Free; end;
end;


function ArrayToStr(Nums: array of integer): string;
{Convert array of integers to a string}
var I: integer;
begin
Result:='[';
for I:=0 to High(Nums) do
	begin
	if I<>0 then Result:=Result+',';
	Result:=Result+IntToStr(Nums[I]);
	end;
Result:=Result+']';
end;


procedure ShowSortedPrimes(Memo: TMemo);
var I: integer;
var IA: TIntegerDynArray;
var S: string;
begin
GetSortedPrimes(NumList,IA);
Memo.Lines.Add('Raw data:      '+ArrayToStr(NumList));
Memo.Lines.Add('Sorted Primes: '+ArrayToStr(IA));
end;
Output:
Raw data:      [2,43,81,122,63,13,7,95,103]
Sorted Primes: [2,7,13,43,103]
Elapsed Time: 2.910 ms.
fastfunc isprim num .
   i = 2
   while i <= sqrt num
      if num mod i = 0 : return 0
      i += 1
   .
   return 1
.
proc insert v &d[] .
   i = len d[]
   d[] &= 0
   while i > 0 and d[i] > v
      d[i + 1] = d[i]
      i -= 1
   .
   d[i + 1] = v
.
inp[] = [ 2 43 81 122 63 13 7 95 103 ]
for v in inp[]
   if isprim v = 1 : insert v d[]
.
print d[]
Output:
[ 2 7 13 43 103 ]

This task uses Extensible Prime Generator (F#)

// Primes from a list. Nigel Galloway: Januuary 23rd., 2022
[2;43;81;122;63;13;7;95;103]|>List.filter isPrime|>List.sort|>List.iter(printf "%d "); printfn ""
Output:
2 7 13 43 103 
Works with: Factor version 0.99 2021-06-02
USING: math.primes prettyprint sequences sorting ;

{ 2 43 81 122 63 13 7 95 103 } [ prime? ] filter natural-sort .
Output:
{ 2 7 13 43 103 }
Library: Go-rcu
package main

import (
    "fmt"
    "rcu"
    "sort"
)

func main() {
    list := []int{2, 43, 81, 122, 63, 13, 7, 95, 103}
    var primes []int
    for _, e := range list {
        if rcu.IsPrime(e) {
            primes = append(primes, e)
        }
    }
    sort.Ints(primes)
    fmt.Println(primes)
}
Output:
[2 7 13 43 103]
import Data.List ( sort ) 

isPrime :: Int -> Bool
isPrime n 
   |n == 1 = False
   |n == 2 = True
   |otherwise = all (\d -> mod n d /= 0 ) [2..limit]
   where
    limit = floor $ sqrt $ fromIntegral n

solution :: [Int]
solution = sort $ filter isPrime [2 , 43 , 122 , 63, 13 , 7 , 95 , 103]
Output:
[2,7,13,43,103]

J

This is a filter (on primality) and a sort (though we could first sort then filter if we preferred):

   /:~ (#~ 1&p:)2,43,81,122,63,13,7,95,103
2 7 13 43 103
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.IntStream;

public final class SortPrimesFromListToAList {

	public static void main(String[] args) {
		Predicate<Integer> isPrime = n -> IntStream.rangeClosed(2, (int) Math.sqrt(n)).allMatch( i -> n % i > 0 );
		 
		System.out.println(List.of( 2, 43, 81, 122, 63, 13, 7, 95, 103 )
			.stream().filter( i -> isPrime.test(i) ).sorted().toList());
	}

}
Output:
[2, 7, 13, 43, 103]
Works with: jq

Works with gojq, the Go implementation of jq

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

def lst: [2, 43, 81, 122, 63, 13, 7, 95, 103];

lst | map( select(is_prime) ) | sort
Output:
[2,7,13,43,103]

There is a prime function in numlib.joy and a qsort in seqlib.joy. Filter and sort.

2 43 81 122 63 13 7 95 103 stack dup.
[103 95 7 13 63 122 81 43 2 103 95 7 13 63 122 81 43 2 103 95 7 13 63 122 81 43 2]
[ prime  ] filter qsort.
[2 2 2 7 7 7 13 13 13 43 43 43 103 103 103]


julia> using Primes

julia> using Primes
julia> sort(filter(isprime, [2,43,81,122,63,13,7,95,103]))
5-element Vector{Int64}:
   2
   7
  13
  43
 103
Sort[Select[{2, 43, 81, 122, 63, 13, 7, 95, 103}, PrimeQ]]
Output:
{2, 7, 13, 43, 103}
sort(sublist([2, 43, 81, 122, 63, 13, 7, 95, 103], primep));
Output:
[2,7,13,43,103]
import algorithm, math, sequtils, strutils

proc isPrime(n: int): bool =
    if n < 2: return false
    if n == 2: return true
    if n mod 2 == 0: return false
    let limit = int(sqrt(n.float))
    for i in countup(3, limit, 2):  # Only odd numbers
        if n mod i == 0:
            return false
    return true

let numbers = [2, 43, 81, 122, 63, 13, 7, 95, 103]
echo sorted(filter(numbers, proc (x: int): bool = isPrime(x))).join(", ")
Output:
2, 7, 13, 43, 103
Translation of: ALGOL 68 – Sorting whilst finding the primes

...which is

Translation of: EasyLang
MODULE SortedPrimes; (* Sort primes from a list to a list - translation of EasyLang via Algol 68 *)
    IMPORT Out, Math;

    PROCEDURE isPrime( n : INTEGER ) : BOOLEAN;
        VAR   rootN, i   : INTEGER;
              result     : BOOLEAN;
        BEGIN
           IF    n < 2      THEN result := FALSE
           ELSIF ~ ODD( n ) THEN result := n = 2
           ELSE
              rootN  := FLOOR( Math.sqrt( FLT( n ) ) );
              result := TRUE;
              i      := 3;
              WHILE result & ( i < rootN ) DO
                 result := n MOD i # 0;
                 INC( i, 2 )
              END
           END
        RETURN result
        END isPrime;

     PROCEDURE insert( v : INTEGER; VAR d : ARRAY OF INTEGER; VAR dPos : INTEGER );
         VAR   iPos      : INTEGER;
         BEGIN
            iPos := dPos;
            INC( dPos );
            WHILE ( iPos > 0 ) & ( d[ iPos ] > v ) DO
               d[ iPos + 1 ] := d[ iPos ];
               DEC( iPos )
            END;
            d[ iPos + 1 ] := v
         END insert;

    PROCEDURE test;
        VAR   list, sortedPrimes    : ARRAY 9 OF INTEGER;
              primePos, lPos, p     : INTEGER;
        BEGIN
           list[0] :=  2; list[1] := 43; list[2] := 81; list[3] := 122;
           list[4] := 63; list[5] := 13; list[6] :=  7; list[7] :=  95; list[8] := 103;
           primePos := - 1;
           FOR lPos := 0 TO LEN( list ) - 1 DO
              p := list[ lPos ];
              IF isPrime( p ) THEN insert( p, sortedPrimes, primePos ) END
           END;
           FOR lPos := 0 TO primePos DO
              Out.String( " " );Out.Int( sortedPrimes[ lPos ], 0 )
           END;
           Out.Ln
        END test;

BEGIN
   test
END SortedPrimes.
Output:
 2 7 13 43 103
#!/usr/bin/perl

use strict; # https://rosettacode.org/wiki/Sort_primes_from_list_to_a_list
use warnings;
use ntheory qw( is_prime );
use List::AllUtils qw( nsort_by );

print "@{[ nsort_by {$_} grep is_prime($_), 2,43,81,122,63,13,7,95,103 ]}\n";
Output:
2 7 13 43 103

You could also use unique() instead of sort(), since that (by default) performs a sort() internally anyway. It wouldn't be any slower, might even be better, also it does not really make much difference here whether you filter() before or after the sort(), though of course some more expensive filtering operations might be faster given fewer items.

with javascript_semantics
pp(sort(filter({2,43,81,122,63,13,7,95,103},is_prime)))
Output:
{2,7,13,43,103}
Library: Pluto-int
Library: Pluto-fmt
local int = require "int"
local fmt = require "fmt"

local list   = {2, 43, 81, 122, 63, 13, 7, 95, 103}
local primes = list:filtered(|e| -> int.isprime(e)):reorder():sort()
fmt.lprint(primes)
Output:
{2, 7, 13, 43, 103}

Python: Procedural

print("working...")
print("Primes are:")

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

Primes = [2,43,81,122,63,13,7,95,103]
Temp = []

for n in range(len(Primes)):
	if isprime(Primes[n]):
		Temp.append(Primes[n])

Temp.sort()
print(Temp)
print("done...")
Output:
working...
Primes are:
[2, 7, 13, 43, 103]
done...

Python: Functional

'''Prime elements in rising order'''


# primeElementsSorted :: [Int] -> [Int]
def primeElementsSorted(xs):
    '''The prime elements of xs in rising order'''
    return sorted(x for x in xs if isPrime(x))


# ------------------------- TEST -------------------------
# main :: IO ()
def main():
    '''Filtered elements of given list in rising order'''

    print(
        primeElementsSorted([
            2, 43, 81, 122, 63, 13, 7, 95, 103
        ])
    )


# ----------------------- GENERIC ------------------------

# isPrime :: Int -> Bool
def 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)))


# MAIN ---
if __name__ == '__main__':
    main()
Output:
[2, 7, 13, 43, 103]

eratosthenes and isprime are defined at Sieve of Eratosthenes#Quackery.

  ' [ 2 43 81 122 63 13 7 95 103 ]
  sort 
  dup -1 peek eratosthenes
  [] swap witheach
    [ dup isprime iff join else drop ]
  echo
Output:
[ 2 7 13 43 103 ]

R

This solution follows the AppleScript entry in sorting each prime into the list as it's identified. It also displays an animation of the current status of the sorted list to show what the code is actually doing as it runs (otherwise, there wouldn't be much point in implementing it that way).

maybe_primes <- c(2, 43, 81, 122, 63, 13, 7, 95, 103)
test_divisors <- c(2, 3, 5, 7, 11)
primetest <- function(n) `|`(!(0 %in% (n%%test_divisors)),
                             n %in% test_divisors)
primes <- numeric(0)
for(i in maybe_primes){
  if(primetest(i)){
    primes <- c(primes, i)
    cat(sort(primes), "\r")
    Sys.sleep(1)
  }
}
Output:
2 7 13 43 103
put <2 43 81 122 63 13 7 95 103>.grep( &is-prime ).sort
Output:
2 7 13 43 103

Of course "ascending" is a little ambiguous. That ^^^ is numerically. This vvv is lexicographically.

put <2 43 81 122 63 13 7 95 103>.grep( &is-prime ).sort: ~*
Output:
103 13 2 43 7
load "stdlibcore.ring"
? "working"

Primes = [2,43,81,122,63,13,7,95,103]
Temp = []

for n = 1 to len(Primes)
     if isprime(Primes[n])
        add(Temp,Primes[n])
     ok
next

Temp = sort(Temp)
showarray(Temp)
? "done..."

func showArray(array)
     txt = ""
     see "["
     for n = 1 to len(array)
         txt = txt + array[n] + ","
     next
     txt = left(txt,len(txt)-1)
     txt = txt + "]"
     ? txt
Output:
working
Primes are:
[2,7,13,43,103]
done...
Works with: HP version 49

With control flow structure

« SORT { }
  1 PICK3 SIZE FOR j
     OVER j GET
     IF DUP ISPRIME? THEN + ELSE DROP END
  NEXT NIP
» 'TASK' STO 

Direct computation

« DUP ISPRIME? SWAP IFT SORT
» 'TASK' STO 
{2,43,81,122,63,13,7,95,103} TASK
Output:
1: { 2 7 13 43 103 }
require 'prime'

p [2,43,81,122,63,13,7,95,103].select(&:prime?).sort
Output:
[2, 7, 13, 43, 103]
fn is_prime( number : u32 ) -> bool {
   let result : bool = match number {
      0 => false ,
      1 => false ,
      2 => true ,
      _ => {
         let limit : u32 = (number as f32).sqrt( ).floor( ) as u32 ;
         (2..=limit).filter( | &d | number % d == 0 ).count( ) == 0 
      }
   } ;
   result 
}

fn main() {
    let numbers : Vec<u32> = vec![2 , 43 , 81 , 122 , 63 , 7 , 95 , 103] ;
    let mut primes : Vec<u32> = numbers.into_iter( ).filter( | &d | is_prime( d ) ).
       collect( ) ;
    primes.sort( ) ;
    println!("{:?}" , primes )
}
Output:
[2, 7, 43, 103]
var arr = [2,43,81,122,63,13,7,95,103]
say arr.grep{.is_prime}.sort
Output:
[2, 7, 13, 43, 103]
Library: Wren-math
import "./math" for Int

var lst = [2, 43, 81, 122, 63, 13, 7, 95, 103]
System.print(lst.where { |e| Int.isPrime(e) }.toList.sort())
Output:
[2, 7, 13, 43, 103]
include xpllib;
int Primes, Smallest, I, SI;
def Len=9, Inf=1000;
[Primes:= [2,43,81,122,63,13,7,95,103];
repeat  Smallest:= Inf;
        for I:= 0 to Len-1 do
            if Primes(I) < Smallest then
                [Smallest:= Primes(I);  SI:= I];
        Primes(SI):= Inf;       \cross off
        if IsPrime(Smallest) then
            [IntOut(0, Smallest);  ChOut(0, ^ )];
until   Smallest = Inf;
]
Output:
2 7 13 43 103 
Cookies help us deliver our services. By using our services, you agree to our use of cookies.