task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Factor
Factor
USING: combinators formatting io kernel math math.parser sequences ; IN: rosetta-code.middle-three-digits   CONSTANT: test-values { 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 }   : (middle-three) ( str -- str' ) [ midpoint@ [ 1 - ] [ 2 + ] bi ] [ subseq ] bi ;   : ...
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#Yabasic
Yabasic
print " X| 1 2 3 4 5 6 7 8 9 10 11 12" print "---+------------------------------------------------"   for i = 1 to 12 nums$ = right$(" " + str$(i), 3) + "|" for j = 1 to 12 if i <= j then if j >= 1 then nums$ = nums$ + left$(" ", (4 - len(str$(i * j)...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Kotlin
Kotlin
// version 1.1.2   import java.math.BigInteger import java.util.Random   val bigTwo = BigInteger.valueOf(2L)   fun isProbablyPrime(n: BigInteger, k: Int): Boolean { require (n > bigTwo && n % bigTwo == BigInteger.ONE) { "Must be odd and greater than 2" } var s = 0 val nn = n - BigInteger.ONE var d: BigI...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Modula-2
Modula-2
MODULE Mertens; FROM InOut IMPORT WriteString, WriteInt, WriteCard, WriteLn;   CONST Max = 1000; VAR n, k, x, y, zero, cross: CARDINAL; M: ARRAY [1..Max] OF INTEGER;   BEGIN M[1] := 1; FOR n := 2 TO Max DO M[n] := 1; FOR k := 2 TO n DO M[n] := M[n] - M[n DIV k]; END; ...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Fantom
Fantom
class Main { static Void displayList (Str[] items) { items.each |Str item, Int index| { echo ("$index: $item") } }   public static Str getChoice (Str[] items) { selection := -1 while (selection == -1) { displayList (items) Env.cur.out.print ("Select: ").flush in...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#J
J
NB. convert/misc/md5 NB. RSA Data Security, Inc. MD5 Message-Digest Algorithm NB. version: 1.0.2 NB. NB. See RFC 1321 for license details NB. J implementation -- (C) 2003 Oleg Kobchenko; NB. NB. 09/04/2003 Oleg Kobchenko NB. 03/31/2007 Oleg Kobchenko j601, JAL NB. 12/17/2015 G.Pruss 64-bit NB. ~60+ times slower than us...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#PL.2FI
PL/I
  mainproc: proc options(main) reorder;   subproc: proc; dcl subvar char init ('X');   put skip data(subvar); subvar = 'Q'; end subproc;   call subproc(); call subproc(); end mainproc;
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#PureBasic
PureBasic
*buffer=AllocateMemory(20)   *newBuffer = ReAllocateMemory(*buffer, 2000) ;increase size of buffer ;*buffer value is still valid if newBuffer wasn't able to be reallocated If *newBuffer <> 0 *buffer = *newBuffer : *newBuffer = 0 EndIf   FreeMemory(*buffer)     size=20 ; allocate an image for use with image functions...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Forth
Forth
: middle3 ( n1 -- a n2) abs s>d <# #s #> dup 2/ 0<> over 1 and 0<> and if 2/ 1- chars + 3 else drop 0 then ;
http://rosettacode.org/wiki/Multiplication_tables
Multiplication tables
Task Produce a formatted   12×12   multiplication table of the kind memorized by rote when in primary (or elementary) school. Only print the top half triangle of products.
#zkl
zkl
fcn multiplicationTable(n){ w,fmt := (n*n).numDigits, " %%%dd".fmt(w).fmt; // eg " %3".fmt header:=[1..n].apply(fmt).concat(); // 1 2 3 4 ... println(" x ", header, "\n ", "-"*header.len()); dash:=String(" "*w,"-"); // eg " -" foreach a in ([1..n]){ print("%2d|".fmt(a),dash*(a-1)); ...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Liberty_BASIC
Liberty BASIC
  DIM mersenne(11) mersenne(1)=7 mersenne(2)=31 mersenne(3)=127 mersenne(4)=8191 mersenne(5)=131071 mersenne(6)=524287 mersenne(7)=2147483647 mersenne(8)=2305843009213693951 mersenne(9)=618970019642690137449562111 mersenne(10)=162259276829213363391578010288127 mersenne(11)=170141183460469231731687303715884105727     di...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Nim
Nim
import sequtils, strformat   func mertensNumbers(max: int): seq[int] = result = repeat(1, max + 1) for n in 2..max: for k in 2..n: dec result[n], result[n div k]   const Max = 1000 let mertens = mertensNumbers(Max)   echo "First 199 Mertens numbers:" const Count = 200 var column = 0 for i in 0..<Count: ...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Forth
Forth
\ Rosetta Code Menu Idiomatic Forth   \ vector table compiler : CASE: ( -- ) CREATE ; : | ( -- <text>) ' ,  ; IMMEDIATE : ;CASE ( -- ) DOES> SWAP CELLS + @ EXECUTE ;   : NIL ( -- addr len) S" " ; : FEE ( -- addr len) S" fee fie" ; : HUFF ( -- addr len) S" huff and puff" ; : MIRROR ( -- addr l...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Java
Java
class MD5 {   private static final int INIT_A = 0x67452301; private static final int INIT_B = (int)0xEFCDAB89L; private static final int INIT_C = (int)0x98BADCFEL; private static final int INIT_D = 0x10325476;   private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23,...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Python
Python
>>> from array import array >>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'), ('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])] >>> for typecode, initializer in argslist: a = array(typecode, initializer) print a del a     array('l') array('c', 'hello world') array('u', u'hello \u2641') array('...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Fortran
Fortran
  !-*- mode: compilation; default-directory: "/tmp/" -*- !Compilation started at Sat Jun 1 14:48:41 ! !a=./f && make $a && OMP_NUM_THREADS=2 $a < unixdict.txt # some of the compilation options and redirection from unixdict.txt are vestigial. !gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-n...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Lua
Lua
function MRIsPrime(n, k) -- If n is prime, returns true (without fail). -- If n is not prime, then returns false with probability ≥ 4^(-k), true otherwise. -- First, deal with 1 and multiples of 2. if n == 1 then return false elseif n == 2 then return true elseif n%2 == 0 then return false en...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Pascal
Pascal
program Merten; {$IFDEF FPC} {$MODE DELPHI} {$Optimization ON,ALL} {$ELSE} {$APPTYPE CONSOLE} {$ENDIF} uses sysutils; const BigLimit = 10*1000*1000*1000;//1e10   type tSieveElement = Int8; tpSieve = pInt8; tMoebVal = array[-1..1] of Int64; var MertensValues : array[-40000..50500] of NativeInt; prim...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Fortran
Fortran
  !a=./f && make $a && OMP_NUM_THREADS=2 $a !gfortran -std=f2008 -Wall -fopenmp -ffree-form -fall-intrinsics -fimplicit-none f.f08 -o f   module menu public :: selector contains   function selector(title,options) result(choice) character(len=*),intent(in) :: title character(len=*),d...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Julia
Julia
# a rather literal translation of the pseudocode at https://en.wikipedia.org/wiki/MD5   const s = UInt32[7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, ...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#R
R
x=numeric(10) # allocate a numeric vector of size 10 to x rm(x) # remove x   x=vector("list",10) #allocate a list of length 10 x=vector("numeric",10) #same as x=numeric(10), space allocated to list vector above now freed rm(x) # remove x
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Racket
Racket
#lang racket (collect-garbage) ; This function forces a garbage collection   (current-memory-use) ;Gives an estimate on the memory use based on the last garbage collection   (custodian-require-memory <limit-custodian> <amount> <stop-custodian>) ; Registers a check on ...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Function middleThreeDigits (n As Integer) As String If n < 0 Then n = -n If n < 100 Then Return "" '' error code If n < 1000 Then Return Str(n) If n < 10000 Then Return "" Dim ns As String = Str(n) If Len(ns) Mod 2 = 0 Then Return "" '' need to have an odd number of digits for there t...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
MillerRabin[n_,k_]:=Module[{d=n-1,s=0,test=True},While[Mod[d,2]==0 ,d/=2 ;s++] Do[ a=RandomInteger[{2,n-1}]; x=PowerMod[a,d,n]; If[x!=1, For[ r = 0, r < s, r++, If[x==n-1, Continue[]]; x = Mod[x*x, n]; ]; If[ x != n-1, test=False ]; ]; ,{k}]; Print[test] ]
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Perl
Perl
use utf8; use strict; use warnings; use feature 'say'; use List::Util 'uniq';   sub prime_factors { my ($n, $d, @factors) = (shift, 1); while ($n > 1 and $d++) { $n /= $d, push @factors, $d until $n % $d; } @factors }   sub μ { my @p = prime_factors(shift); @p == uniq(@p) ? 0 == @p%2 ? 1...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#FreeBASIC
FreeBASIC
dim as string menu(1 to 4)={ "fee fie", "huff and puff", "mirror mirror", "tick tock" }   function menu_select( m() as string ) as string dim as integer i, vc = 0 dim as string c while vc<1 or vc > ubound(m) cls for i = 1 to ubound(m) print i;" ";m(i) next i prin...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Kotlin
Kotlin
// version 1.1.3   object MD5 {   private val INIT_A = 0x67452301 private val INIT_B = 0xEFCDAB89L.toInt() private val INIT_C = 0x98BADCFEL.toInt() private val INIT_D = 0x10325476   private val SHIFT_AMTS = intArrayOf( 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 1...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Raku
Raku
my $buffer = Buf.new(0 xx 1024);
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Retro
Retro
display total memory available   ~~~ EOM n:put ~~~   display unused memory   ~~~ EOM here - n:put ~~~   display next free address   ~~~ here n:put ~~~   allocate 1000 cells   ~~~ #1000 allot ~~~   free 500 cells   ~~~ #-500 allot ~~~
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Gambas
Gambas
Public Sub Main() Dim iList As Integer[] = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0] 'Array of integers to process Dim sTemp As String 'Temp string Dim siCount As Short ...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Maxima
Maxima
/* Miller-Rabin algorithm is builtin, see function primep. Here is another implementation */     /* find highest power of p, p^s, that divide n, and return s and n / p^s */   facpow(n, p) := block( [s: 0], while mod(n, p) = 0 do (s: s + 1, n: quotient(n, p)), [s, n] )$   /* check whether n is a strong pseudopr...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Phix
Phix
function Mertens(integer n) integer res = 1 for k=2 to n do res -= Mertens(floor(n/k)) end for return res end function sequence s = {" ."} for i=1 to 143 do s = append(s,sprintf("%3d",Mertens(i))) end for puts(1,join_by(s,1,12," ")) integer prev = 1, zeroes = 0, crosses = 0 for n=2 to 1000 do...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Gambas
Gambas
  Public Sub Main()   Dim asMenu As String[] = ["fee fie", "huff And puff", "mirror mirror", "tick tock"] Dim sValuePrompt As String = "Please select one of the above numbers> " Dim sChoice As String Dim sFeedbackFormat As String = "You have chosen '&1'\r\n"   sChoice = Menu(asMenu, sValuePrompt) ...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Liberty_BASIC
Liberty BASIC
---------------------------------------- -- Calculates MD5 hash of string or bytearray -- @param {bytearray|string} input -- @return {bytearray} (16 bytes) ---------------------------------------- on md5 (input) if stringP(input) then input = bytearray(input)   -- Convert string to list of little-endian words.....
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#REXX
REXX
Axtec_god.3='Quetzalcoatl ("feathered serpent"), god of learning, civilization, regeneration, wind and storms'
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Ring
Ring
  cVar = " " # create variable contains string of 5 bytes cVar = NULL # destroy the 5 bytes string !  
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Go
Go
package m3   import ( "errors" "strconv" )   var ( ErrorLT3 = errors.New("N of at least three digits required.") ErrorEven = errors.New("N with odd number of digits required.") )   func Digits(i int) (string, error) { if i < 0 { i = -i } if i < 100 { return "", ErrorLT3 ...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Mercury
Mercury
 :- func n2 = integer.integer.  :- pragma memo(n2/0). n2 = integer.integer(2).
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#PL.2FI
PL/I
mertens: procedure options(main);  %replace MAX by 1000;   declare M(1:MAX) fixed binary(5); declare (n, k) fixed binary(10); declare (isZero, crossZero) fixed binary(8);   M(1) = 1; do n = 2 to MAX; M(n) = 1; do k = 2 to n; M(n) = M(n) - M(divide(n,k,10)); end...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Go
Go
package main   import "fmt"   func menu(choices []string, prompt string) string { if len(choices) == 0 { return "" } var c int for { fmt.Println("") for i, s := range choices { fmt.Printf("%d.  %s\n", i+1, s) } fmt.Print(prompt) _, err := fmt.S...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Lingo
Lingo
---------------------------------------- -- Calculates MD5 hash of string or bytearray -- @param {bytearray|string} input -- @return {bytearray} (16 bytes) ---------------------------------------- on md5 (input) if stringP(input) then input = bytearray(input)   -- Convert string to list of little-endian words.....
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Ruby
Ruby
class Thingamajig def initialize fail 'not yet implemented' end end t = Thingamajig.allocate
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Rust
Rust
// we have to use `unsafe` here because // we will be dereferencing a raw pointer unsafe { use std::alloc::{Layout, alloc, dealloc}; // define a layout of a block of memory let int_layout = Layout::new::<i32>();   // memory is allocated here let ptr = alloc(int_layout);   // let us point to som...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Gosu
Gosu
var valid = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345} valid.each(\ num ->print(middleThree(num)))   var errant = {1, 2, -1, -10, 2002, -2002, 0} errant.each(\ num ->print(middleThree(num)))   function middleThree(x: int) : String { var s = Math.abs(x) as String if(s.length < 3) return...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Nim
Nim
  ## Nim currently doesn't have a BigInt standard library ## so we translate the version from Go which uses a ## deterministic approach, which is correct for all ## possible values in uint32.   proc isPrime*(n: uint32): bool = # bases of 2, 7, 61 are sufficient to cover 2^32 case n of 0, 1: return false of 2, 7...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Prolog
Prolog
:- dynamic mertens_number_cache/2.   mertens_number(1, 1):- !. mertens_number(N, M):- mertens_number_cache(N, M), !. mertens_number(N, M):- N >= 2, mertens_number(N, 2, M, 0), assertz(mertens_number_cache(N, M)).   mertens_number(N, N, M, M):- !. mertens_number(N, K, M, S):- N1 is N // K, me...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#GW-BASIC
GW-BASIC
  10 DATA "Fee fie", "Huff and Puff", "Mirror mirror", "Tick tock" 20 VC = 0 30 DIM M$(3) 40 FOR I = 0 TO 3 50 READ M$(I) 60 NEXT I 70 CLS 80 FOR I = 0 TO 3 90 PRINT I+1;" ";M$(I) 100 NEXT I 110 PRINT 120 INPUT "Choice? ", C$ 130 VC = VAL(C$) 140 IF VC<1 OR VC>4 THEN GOTO 70 150 PRINT "You picked ", M$(VC-1) 160 END ...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Lua
Lua
-- shift amounts local s = { 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21 }   -- constants local K = { 0xd76aa478, 0...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Scala
Scala
PRINT PEEK 16388+256*16389
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Sinclair_ZX81_BASIC
Sinclair ZX81 BASIC
PRINT PEEK 16388+256*16389
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Groovy
Groovy
def middleThree(Number number) { def text = Math.abs(number) as String assert text.size() >= 3 : "'$number' must be more than 3 numeric digits" assert text.size() % 2 == 1 : "'$number' must have an odd number of digits"   int start = text.size() / 2 - 1 text[start..(start+2)] }
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#OCaml
OCaml
  (* Translated from the wikipedia pseudo-code *) let miller_rabin n ~iter:k = (* return r and d where n = 2^r*d (from scheme implementation) *) let get_rd n = let rec loop r d = (* not even *) if Z.(equal (logand d one) one) then (r,d) else loop Z.(r + one) Z.(div d ~$2) i...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#PureBasic
PureBasic
Dim M.i(1000)   M(1)=1 For n=2 To 1000 psum=0 For k=2 To n : psum+M(Int(n/k)) : Next : M(n)=1-psum If M(n)=0 : z+1 : If M(n-1)<>0 : c+1 : EndIf : EndIf Next   OpenConsole("") PrintN("First 99 Mertens numbers:") : Print(Space(4)) For n=1 To 99 : Print(RSet(Str(M(n)),4)) : If n%10=9 : PrintN("") : EndIf : Next Prin...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Haskell
Haskell
module RosettaSelect where   import Data.Maybe (listToMaybe) import Control.Monad (guard)   select :: [String] -> IO String select [] = return "" select menu = do putStr $ showMenu menu putStr "Choose an item: " choice <- getLine maybe (select menu) return $ choose menu choice   showMenu :: [String] -> String...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
md5[string_String] := Module[{r = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}, k = Table[Floor[2^32*Abs...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Smalltalk
Smalltalk
handle := ExternalBytes new:size ... handle free
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#SNOBOL4
SNOBOL4
newstring = "This is creating and saving" " a new single string " "starting with three separate strings."
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Haskell
Haskell
mid3 :: Int -> Either String String mid3 n | m < 100 = Left "is too small" | even lng = Left "has an even number of digits" | otherwise = Right . take 3 $ drop ((lng - 3) `div` 2) s where m = abs n s = show m lng = length s   -- TEST -------------------------------------------------------- main :: I...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Oz
Oz
  %--------------------------------------------------------------------------% % module: Primality % file: Primality.oz % version: 17 DEC 2014 @ 6:50AM %--------------------------------------------------------------------------%   declare %--------------------------------------------------------------------------%   fu...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Python
Python
def mertens(count): """Generate Mertens numbers""" m = [None, 1] for n in range(2, count+1): m.append(1) for k in range(2, n+1): m[n] -= m[n//k] return m     ms = mertens(1000)   print("The first 99 Mertens numbers are:") print(" ", end=' ') col = 1 for n in ms[1:100]: p...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#HicEst
HicEst
CHARACTER list = "fee fie,huff and puff,mirror mirror,tick tock,", answer*20   POP(Menu=list, SelTxt=answer)   SUBROUTINE list ! callback procedure must have same name as menu argument ! Subroutine with no arguments: all objects are global ! The global variable $$ returns the selected list index WRITE(Messagebo...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#MATLAB_.2F_Octave
MATLAB / Octave
INTERFACE MD5;   IMPORT Word;   TYPE Digest = ARRAY [0..15] OF CHAR; TYPE Buffer = ARRAY [0..63] OF CHAR;   TYPE T = RECORD state: ARRAY [0..3] OF Word.T; count: ARRAY [0..1] OF Word.T; buffer: Buffer; END;   PROCEDURE Init(VAR md5ctx: T); PROCEDURE Update(VAR md5ctx: T; input: TEXT); PROCEDURE Final(VAR md5ctx: ...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Tcl
Tcl
#include <tcl.h>   /* A data structure used to enforce data safety */ struct block { int size; unsigned char data[4]; };   static int Memalloc( ClientData clientData, Tcl_Interp *interp, int objc, Tcl_Obj *const *objv) { Tcl_HashTable *nameMap = clientData; static int nameCounter = 0; ch...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Icon_and_Unicon
Icon and Unicon
procedure main(a) every n := !a do write(right(n,15)," -> ",midM(n)) end   procedure midM(n,m) /m := 3 n := abs(n) return n ? if (*n >= m) then if (((*n-m) % 2) = 0) then (move((*n - m)/2),move(m)) else "wrong number of digits" else "too short" end
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#PARI.2FGP
PARI/GP
MR(n,k)=ispseudoprime(n,k);
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Raku
Raku
use Prime::Factor;   sub μ (Int \n) { return 0 if n %% 4 or n %% 9 or n %% 25 or n %% 49 or n %% 121; my @p = prime-factors(n); +@p == +@p.unique ?? +@p %% 2 ?? 1 !! -1 !! 0 }   my @mertens = lazy [\+] flat '', 1, (2..*).hyper.map: -> \n { μ(n) };   put "Mertens sequence - First 199 terms:\n", @mertens[...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Icon_and_Unicon
Icon and Unicon
  ## menu.icn : rewrite of the faulty version on Rosetta Code site 24/4/2021   procedure main()   L := ["fee fie", "huff and puff", "mirror mirror", "tick tock"] K := ["hidie hi", "hidie ho", "mirror mirror on the Wall", "tick tock tick tok"] Z := []   choice := choose_from_menu(L) # call using menu L write("Ret...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Modula-3
Modula-3
INTERFACE MD5;   IMPORT Word;   TYPE Digest = ARRAY [0..15] OF CHAR; TYPE Buffer = ARRAY [0..63] OF CHAR;   TYPE T = RECORD state: ARRAY [0..3] OF Word.T; count: ARRAY [0..1] OF Word.T; buffer: Buffer; END;   PROCEDURE Init(VAR md5ctx: T); PROCEDURE Update(VAR md5ctx: T; input: TEXT); PROCEDURE Final(VAR md5ctx: ...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#Wren
Wren
// create a list with 10 elements all initialized to zero var squares = List.filled(10, 0) // give them different values and print them for (i in 0..9) squares[i] = i * i System.print(squares) // add another element to the list dynamically and print it again squares.add(10 * 10) System.print(squares) squares = null // ...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#X86_Assembly
X86 Assembly
  ; linux x86_64   struc block free: resb 1 ; whether or not this block is free size: resb 2 ; size of the chunk of memory next: resb 8 ; the next chunk after this one mem: endstruc   section .data hStart: dq 0 ; the beginning of our heap space break: dq 0 ; the current end of our heap space     section .text   Allocat...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#J
J
asString=: ":"0 NB. convert vals to strings getPfxSize=: [: -:@| 3 -~ # NB. get size of prefix to drop before the 3 middle digits getMid3=: (3 {. getPfxSize }. ,&'err') :: ('err'"_) NB. get 3 middle digits or return 'err' getMiddle3=: getMid3@asString@:|
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Perl
Perl
use bigint try => 'GMP';   sub is_prime { my ($n, $k) = @_; return 1 if $n == 2; return 0 if $n < 2 or $n % 2 == 0;   my $d = $n - 1; my $s = 0;   while (!($d % 2)) { $d /= 2; $s++; }   LOOP: for (1 .. $k) { my $a = 2 + int(rand($n - 2));   my $x = $a->bmodp...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#REXX
REXX
/*REXX pgm computes & shows a value grid of the Mertens function for a range of integers*/ parse arg LO HI grp eqZ xZ . /*obtain optional arguments from the CL*/ if LO=='' | LO=="," then LO= 0 /*Not specified? Then use the default.*/ if HI=='' | HI=="," then HI= 199 ...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#J
J
  CHOICES =: ];._2 'fee fie;huff and puff;mirror mirror;tick tock;' PROMPT =: 'Which is from the three pigs? '   showMenu =: smoutput@:(,"1~ (' ' ,.~ 3 ": i.@:(1 ,~ #))) read_stdin =: 1!:1@:1:   menu =: '? '&$: :(4 : 0) NB. use: [prompt] menu choice_array CHOICES =. y if. 0 = # CHOICES do. return. end. PROMPT =. x...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Nim
Nim
import sequtils   const ChunkSize = 512 div 8 SumSize = 128 div 8   proc extractChunk(msg : seq[uint8], chunk: var openarray[uint32], offset: int) = var srcIndex = offset   for dstIndex in 0 ..< 16: chunk[dstIndex] = 0 for ii in 0 ..< 4: chunk[dstIndex] = chunk[dstIndex] shr 8 chunk[dstI...
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#XPL0
XPL0
int Array(10); \allocates 10 integers (40 bytes) of heap space Array2:= Reserve(10*4); \another way to allocate 10 integers of heap space Array3:= MAlloc(4); \allocate 4 paragraphs (64 bytes) of conventional memory ... Release(Array3); \release this memory so it can be used elsewhere
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#zkl
zkl
Data(123); // this bit bucket expects hold 123 bytes List.createLong(123); // this list expects to hold 123 elements
http://rosettacode.org/wiki/Memory_allocation
Memory allocation
Task Show how to explicitly allocate and deallocate blocks of memory in your language. Show access to different types of memory (i.e., heap, stack, shared, foreign) if applicable.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 REM This code is written for a 48k spectrum 20 CLEAR 65535 - 8192: REM reserve 8192 bytes of memory 30 CLEAR 65535: REM unreserve the memory, moving the ramtop back to the top of the ram
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Java
Java
public class MiddleThreeDigits {   public static void main(String[] args) { final long[] passing = {123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, Long.MIN_VALUE, Long.MAX_VALUE};   final int[] failing = {1, 2, -1, -10, 2002, -2002, 0, Integer.MIN_VALUE, ...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Phix
Phix
with javascript_semantics function powermod(atom a, atom n, atom m) -- calculate a^n%mod atom p = a, res = 1 while n do if and_bits(n,1) then res = mod(res*p,m) end if p = mod(p*p,m) n = floor(n/2) end while return res end function function witness(atom n, a...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Ruby
Ruby
require 'prime'   def μ(n) return 1 if self == 1 pd = n.prime_division return 0 unless pd.map(&:last).all?(1) pd.size.even? ? 1 : -1 end   def M(n) (1..n).sum{|n| μ(n)} end   ([" "] + (1..199).map{|n|"%2s" % M(n)}).each_slice(20){|line| puts line.join(" ") }   ar = (1..1000).map{|n| M(n)} puts "\nThe Mertens...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Java
Java
public static String select(List<String> list, String prompt){ if(list.size() == 0) return ""; Scanner sc = new Scanner(System.in); String ret = null; do{ for(int i=0;i<list.size();i++){ System.out.println(i + ": "+list.get(i)); } System.out.print(prompt); int...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#ooRexx
ooRexx
  #!/usr/bin/rexx   /* Expected results: 0xd41d8cd98f00b204e9800998ecf8427e <== "" 0x0cc175b9c0f1b6a831c399e269772661 <== "a" 0x900150983cd24fb0d6963f7d28e17f72 <== "abc" 0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest" 0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz" 0xd17...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#JavaScript
JavaScript
function middleThree(x){ var n=''+Math.abs(x); var l=n.length-1; if(l<2||l%2) throw new Error(x+': Invalid length '+(l+1)); return n.slice(l/2-1,l/2+2); }   [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0].forEach(function(n){ try{console.log(n,middleThree(...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#PHP
PHP
<?php function is_prime($n, $k) { if ($n == 2) return true; if ($n < 2 || $n % 2 == 0) return false;   $d = $n - 1; $s = 0;   while ($d % 2 == 0) { $d /= 2; $s++; }   for ($i = 0; $i < $k; $i++) { $a = rand(2, $n-1);   $x = bcpowmod($a, $d, $n)...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Sidef
Sidef
say mertens(123456789) #=> 1170 say mertens(1234567890) #=> 9163
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Swift
Swift
import Foundation   func mertensNumbers(max: Int) -> [Int] { var mertens = Array(repeating: 1, count: max + 1) for n in 2...max { for k in 2...n { mertens[n] -= mertens[n / k] } } return mertens }   let max = 1000 let mertens = mertensNumbers(max: max)   let count = 200 let c...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#JavaScript
JavaScript
const readline = require('readline');   async function menuSelect(question, choices) { if (choices.length === 0) return '';   const prompt = choices.reduce((promptPart, choice, i) => { return promptPart += `${i + 1}. ${choice}\n`; }, '');   let inputChoice = -1; while (inputChoice < 1 || inputChoice > cho...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Perl
Perl
use strict; use warnings; use integer; use Test::More;   BEGIN { plan tests => 7 }   sub A() { 0x67_45_23_01 } sub B() { 0xef_cd_ab_89 } sub C() { 0x98_ba_dc_fe } sub D() { 0x10_32_54_76 } sub MAX() { 0xFFFFFFFF }   sub padding { my $l = length (my $msg = shift() . chr(128)); $msg .= "\0" x (($l%64<=56?...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#jq
jq
def middle3: if . < 0 then -. else . end | tostring as $s | ($s | length) as $n | if $n<3 or ($n % 2) == 0 then "invalid length: \($n)" else (($n - 1) / 2) as $n | $s[$n - 1 : $n + 2] end ;   (123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345, 1, 2, -1, -10, 2002, -2002, 0) | "\...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#PicoLisp
PicoLisp
(de longRand (N) (use (R D) (while (=0 (setq R (abs (rand))))) (until (> R N) (unless (=0 (setq D (abs (rand)))) (setq R (* R D)) ) ) (% R N) ) )   (de **Mod (X Y N) (let M 1 (loop (when (bit? 1 Y) (setq M (% (* M X) N)) ) (T (=0 (setq Y (...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Vlang
Vlang
fn mertens(t int) ([]int, int, int) { mut to:=t if to < 1 { to = 1 } mut merts := []int{len:to+1} mut primes := [2] mut sum := 0 mut zeros := 0 mut crosses := 0 for i := 1; i <= to; i++ { mut j := i mut cp := 0 // counts prime factors mut spf := f...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#Wren
Wren
import "/fmt" for Fmt import "/math" for Int   var isSquareFree = Fn.new { |n| var i = 2 while (i * i <= n) { if (n%(i*i) == 0) return false i = (i > 2) ? i + 2 : i + 1 } return true }   var mu = Fn.new { |n| if (n < 1) Fiber.abort("Argument must be a positive integer") if (n == ...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#jq
jq
def choice: def read(prompt; max): def __read__: prompt, ( input as $input | if ($input|type) == "number" and 0 < $input and $input <= max then $input else __read__ end); __read__;   if length == 0 then "" else . as $in | ("Enter your choice:\n" + (reduce ...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#Phix
Phix
-- demo\rosetta\md5.exw with javascript_semantics function uxor(atom data1,atom data2) atom result = xor_bits(data1,data2) if result<0 then result += #100000000 end if return result end function function uor(atom data1,atom data2) atom result = or_bits(data1,data2) if result<0 then result += #100000000 en...
http://rosettacode.org/wiki/Middle_three_digits
Middle three digits
Task Write a function/procedure/subroutine that is called with an integer value and returns the middle three digits of the integer if possible or a clear indication of an error if this is not possible. Note: The order of the middle digits should be preserved. Your function should be tested with the following values;...
#Julia
Julia
using Printf   function middle3(n::Integer) l = ndigits(n) iseven(l) && error("n must have an odd number of digits") l < 3 && error("n must have 3 digits or more") mid = (l + 1) ÷ 2 abs(n) ÷ 10^(mid-2) % 10^3 end   for n = [123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12...
http://rosettacode.org/wiki/Miller%E2%80%93Rabin_primality_test
Miller–Rabin primality test
This page uses content from Wikipedia. The original article was at Miller–Rabin primality test. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The Miller–Rabin primality test or Rabin–Miller prima...
#Pike
Pike
      int pow_mod(int m, int i,int mod){ int x=1,y=m%mod; while(i){ if(i&1) x = x*y%mod; y = y*y%mod; i>>=1; } return x; } bool mr_pass(int a, int s, int d, int n){ int a_to_power = pow_mod(a, d, n); if(a_to_power == 1) return true; for(int i = 0; i< s - 1; i++){ if(a_to_power == ...
http://rosettacode.org/wiki/Mertens_function
Mertens function
The Mertens function M(x) is the count of square-free integers up to x that have an even number of prime factors, minus the count of those that have an odd number. It is an extension of the Möbius function. Given the Möbius function μ(n), the Mertens function M(x) is the sum of the Möbius numbers from n == 1 through n...
#zkl
zkl
fcn mertensW(n){ [1..].tweak(fcn(n,pm){ pm.incN(mobius(n)); pm.value }.fp1(Ref(0))) } fcn mobius(n){ pf:=primeFactors(n); sq:=pf.filter1('wrap(f){ (n % (f*f))==0 }); // False if square free if(sq==False){ if(pf.len().isEven) 1 else -1 } else 0 } fcn primeFactors(n){ // Return a list of p...
http://rosettacode.org/wiki/Menu
Menu
Task Given a prompt and a list containing a number of strings of which one is to be selected, create a function that: prints a textual menu formatted as an index value followed by its corresponding string for each item in the list; prompts the user to enter a number; returns the string corresponding to the selecte...
#Julia
Julia
using Printf   function _menu(items) for (ind, item) in enumerate(items) @printf "  %2i) %s\n" ind item end end   _ok(::Any,::Any) = false function _ok(reply::AbstractString, itemcount) n = tryparse(Int, reply) return isnull(n) || 0 ≤ get(n) ≤ itemcount end   "Prompt to select an item from the i...
http://rosettacode.org/wiki/MD5/Implementation
MD5/Implementation
The purpose of this task to code and validate an implementation of the MD5 Message Digest Algorithm by coding the algorithm directly (not using a call to a built-in or external hashing library). For details of the algorithm refer to MD5 on Wikipedia or the MD5 definition in IETF RFC (1321). The implementation needs t...
#PicoLisp
PicoLisp
(scl 12) (load "@lib/math.l") # For 'sin'   (de *Md5-R 7 12 17 22 7 12 17 22 7 12 17 22 7 12 17 22 5 9 14 20 5 9 14 20 5 9 14 20 5 9 14 20 4 11 16 23 4 11 16 23 4 11 16 23 4 11 16 23 6 10 15 21 6 10 15 21 6 10 15 21 6 10 15 21 )   (de *Md5-K ~(make (for I 64 (link ...