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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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 ;
: too-short ( -- )
"Number must have at least three digits." print ;
: number-even ( -- )
"Number must have an odd number of digits." print ;
: middle-three ( n -- )
abs number>string {
{ [ dup length 3 < ] [ drop too-short ] }
{ [ dup length even? ] [ drop number-even ] }
[ (middle-three) print ]
} cond ;
: main ( -- )
test-values [ dup "%9d : " printf middle-three ] each ;
MAIN: main |
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))))
end if
nums$ = nums$ + str$(i * j)
else
nums$ = nums$ + " "
end if
next j
print nums$
next 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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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: BigInteger
do {
s++
d = nn.shiftRight(s)
}
while (d % bigTwo == BigInteger.ZERO)
val rand = Random()
loop@ for (i in 1..k) {
var a: BigInteger
do {
a = BigInteger(n.bitLength(), rand)
}
while(a < bigTwo || a > nn) // make sure it's in the interval [2, n - 1]
var x = a.modPow(d, n)
if (x == BigInteger.ONE || x == nn) continue
for (r in 1 until s) {
x = (x * x) % n
if (x == BigInteger.ONE) return false
if (x == nn) break@loop
}
return false
}
return true
}
fun main(args: Array<String>) {
val k = 20 // say
// obtain all primes up to 100
println("The following numbers less than 100 are prime:")
for (i in 3..99 step 2)
if (isProbablyPrime(BigInteger.valueOf(i.toLong()), k)) print("$i ")
println("\n")
// check if some big numbers are probably prime
val bia = arrayOf(
BigInteger("4547337172376300111955330758342147474062293202868155909489"),
BigInteger("4547337172376300111955330758342147474062293202868155909393")
)
for (bi in bia)
println("$bi is ${if (isProbablyPrime(bi, k)) "probably prime" else "composite"}")
} |
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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;
END;
WriteString("The first 99 Mertens numbers are:");
WriteLn();
FOR y := 0 TO 90 BY 10 DO
FOR x := 0 TO 9 DO
IF x+y=0 THEN WriteString(" ");
ELSE WriteInt(M[x+y], 3);
END;
END;
WriteLn();
END;
zero := 0;
cross := 0;
FOR n := 2 TO Max DO
IF M[n] = 0 THEN
zero := zero + 1;
IF M[n-1] # 0 THEN
cross := cross + 1;
END;
END;
END;
WriteString("M(n) is zero ");
WriteCard(zero,0);
WriteString(" times.");
WriteLn();
WriteString("M(n) crosses zero ");
WriteCard(cross,0);
WriteString(" times.");
WriteLn();
END 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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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
input := Int.fromStr(Env.cur.in.readLine, 10, false)
if (input != null)
{
if (input >= 0 && input < items.size)
{
selection = input
}
}
echo ("Try again")
}
return items[selection]
}
public static Void main ()
{
choice := getChoice (["fee fie", "huff and puff", "mirror mirror", "tick tock"])
echo ("You chose: $choice")
}
} |
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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 using the jqt library
require 'convert'
coclass 'pcrypt'
NB. lt= (*. -.)~ gt= *. -. ge= +. -. xor= ~:
'`lt gt ge xor'=: (20 b.)`(18 b.)`(27 b.)`(22 b.)
'`and or sh'=: (17 b.)`(23 b.)`(33 b.)
3 : 0 ''
if. IF64 do.
rot=: (16bffffffff and sh or ] sh~ 32 -~ [) NB. (y << x) | (y >>> (32 - x))
add=: ((16bffffffff&and)@+)"0
else.
rot=: (32 b.)
add=: (+&(_16&sh) (16&sh@(+ _16&sh) or and&65535@]) +&(and&65535))"0
end.
EMPTY
)
hexlist=: tolower@:,@:hfd@:,@:(|."1)@(256 256 256 256&#:)
cmn=: 4 : 0
'x s t'=. x [ 'q a b'=. y
b add s rot (a add q) add (x add t)
)
ff=: cmn (((1&{ and 2&{) or 1&{ lt 3&{) , 2&{.)
gg=: cmn (((1&{ and 3&{) or 2&{ gt 3&{) , 2&{.)
hh=: cmn (((1&{ xor 2&{)xor 3&{ ) , 2&{.)
ii=: cmn (( 2&{ xor 1&{ ge 3&{ ) , 2&{.)
op=: ff`gg`hh`ii
I=: ".;._2(0 : 0)
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 6 11 0 5 10 15 4 9 14 3 8 13 2 7 12
5 8 11 14 1 4 7 10 13 0 3 6 9 12 15 2
0 7 14 5 12 3 10 1 8 15 6 13 4 11 2 9
)
S=: 4 4$7 12 17 22 5 9 14 20 4 11 16 23 6 10 15 21
T=: |:".;._2(0 : 0)
_680876936 _165796510 _378558 _198630844
_389564586 _1069501632 _2022574463 1126891415
606105819 643717713 1839030562 _1416354905
_1044525330 _373897302 _35309556 _57434055
_176418897 _701558691 _1530992060 1700485571
1200080426 38016083 1272893353 _1894986606
_1473231341 _660478335 _155497632 _1051523
_45705983 _405537848 _1094730640 _2054922799
1770035416 568446438 681279174 1873313359
_1958414417 _1019803690 _358537222 _30611744
_42063 _187363961 _722521979 _1560198380
_1990404162 1163531501 76029189 1309151649
1804603682 _1444681467 _640364487 _145523070
_40341101 _51403784 _421815835 _1120210379
_1502002290 1735328473 530742520 718787259
1236535329 _1926607734 _995338651 _343485551
)
norm=: 3 : 0
n=. 16 * 1 + _6 sh 8 + #y
b=. n#0 [ y=. a.i.y
for_i. i. #y do.
b=. ((j { b) or (8*4|i) sh i{y) (j=. _2 sh i) } b
end.
b=. ((j { b) or (8*4|i) sh 128) (j=._2 sh i=.#y) } b
_16]\ (8 * #y) (n-2) } b
)
NB.*md5 v MD5 Message-Digest Algorithm
NB. diagest=. md5 message
md5=: 3 : 0
X=. norm y
q=. r=. 1732584193 _271733879 _1732584194 271733878
for_x. X do.
for_j. i.4 do.
l=. ((j{I){x) ,. (16$j{S) ,. j{T
for_i. i.16 do.
r=. _1|.((i{l) (op@.j) r),}.r
end.
end.
q=. r=. r add q
end.
hexlist r
)
md5_z_=: md5_pcrypt_ |
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
CreateImage(1,size,size)
FreeImage(1) |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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));
[a..n].pump(String,'*(a),fmt).println();
}
}(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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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
dim SmallPrimes(1000)
data 2, 3, 5, 7, 11, 13, 17, 19, 23, 29
data 31, 37, 41, 43, 47, 53, 59, 61, 67, 71
data 73, 79, 83, 89, 97, 101, 103, 107, 109, 113
data 127, 131, 137, 139, 149, 151, 157, 163, 167, 173
data 179, 181, 191, 193, 197, 199, 211, 223, 227, 229
data 233, 239, 241, 251, 257, 263, 269, 271, 277, 281
data 283, 293, 307, 311, 313, 317, 331, 337, 347, 349
data 353, 359, 367, 373, 379, 383, 389, 397, 401, 409
data 419, 421, 431, 433, 439, 443, 449, 457, 461, 463
data 467, 479, 487, 491, 499, 503, 509, 521, 523, 541
data 547, 557, 563, 569, 571, 577, 587, 593, 599, 601
data 607, 613, 617, 619, 631, 641, 643, 647, 653, 659
data 661, 673, 677, 683, 691, 701, 709, 719, 727, 733
data 739, 743, 751, 757, 761, 769, 773, 787, 797, 809
data 811, 821, 823, 827, 829, 839, 853, 857, 859, 863
data 877, 881, 883, 887, 907, 911, 919, 929, 937, 941
data 947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013
data 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069
data 1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151
data 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223
data 1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291
data 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373
data 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451
data 1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511
data 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583
data 1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657
data 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733
data 1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811
data 1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889
data 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987
data 1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053
data 2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129
data 2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213
data 2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287
data 2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357
data 2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423
data 2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531
data 2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617
data 2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687
data 2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741
data 2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819
data 2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903
data 2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999
data 3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079
data 3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181
data 3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257
data 3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331
data 3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413
data 3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511
data 3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571
data 3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643
data 3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727
data 3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821
data 3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907
data 3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989
data 4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057
data 4073, 4079, 4091, 4093, 4099, 4111, 4127, 4129, 4133, 4139
data 4153, 4157, 4159, 4177, 4201, 4211, 4217, 4219, 4229, 4231
data 4241, 4243, 4253, 4259, 4261, 4271, 4273, 4283, 4289, 4297
data 4327, 4337, 4339, 4349, 4357, 4363, 4373, 4391, 4397, 4409
data 4421, 4423, 4441, 4447, 4451, 4457, 4463, 4481, 4483, 4493
data 4507, 4513, 4517, 4519, 4523, 4547, 4549, 4561, 4567, 4583
data 4591, 4597, 4603, 4621, 4637, 4639, 4643, 4649, 4651, 4657
data 4663, 4673, 4679, 4691, 4703, 4721, 4723, 4729, 4733, 4751
data 4759, 4783, 4787, 4789, 4793, 4799, 4801, 4813, 4817, 4831
data 4861, 4871, 4877, 4889, 4903, 4909, 4919, 4931, 4933, 4937
data 4943, 4951, 4957, 4967, 4969, 4973, 4987, 4993, 4999, 5003
data 5009, 5011, 5021, 5023, 5039, 5051, 5059, 5077, 5081, 5087
data 5099, 5101, 5107, 5113, 5119, 5147, 5153, 5167, 5171, 5179
data 5189, 5197, 5209, 5227, 5231, 5233, 5237, 5261, 5273, 5279
data 5281, 5297, 5303, 5309, 5323, 5333, 5347, 5351, 5381, 5387
data 5393, 5399, 5407, 5413, 5417, 5419, 5431, 5437, 5441, 5443
data 5449, 5471, 5477, 5479, 5483, 5501, 5503, 5507, 5519, 5521
data 5527, 5531, 5557, 5563, 5569, 5573, 5581, 5591, 5623, 5639
data 5641, 5647, 5651, 5653, 5657, 5659, 5669, 5683, 5689, 5693
data 5701, 5711, 5717, 5737, 5741, 5743, 5749, 5779, 5783, 5791
data 5801, 5807, 5813, 5821, 5827, 5839, 5843, 5849, 5851, 5857
data 5861, 5867, 5869, 5879, 5881, 5897, 5903, 5923, 5927, 5939
data 5953, 5981, 5987, 6007, 6011, 6029, 6037, 6043, 6047, 6053
data 6067, 6073, 6079, 6089, 6091, 6101, 6113, 6121, 6131, 6133
data 6143, 6151, 6163, 6173, 6197, 6199, 6203, 6211, 6217, 6221
data 6229, 6247, 6257, 6263, 6269, 6271, 6277, 6287, 6299, 6301
data 6311, 6317, 6323, 6329, 6337, 6343, 6353, 6359, 6361, 6367
data 6373, 6379, 6389, 6397, 6421, 6427, 6449, 6451, 6469, 6473
data 6481, 6491, 6521, 6529, 6547, 6551, 6553, 6563, 6569, 6571
data 6577, 6581, 6599, 6607, 6619, 6637, 6653, 6659, 6661, 6673
data 6679, 6689, 6691, 6701, 6703, 6709, 6719, 6733, 6737, 6761
data 6763, 6779, 6781, 6791, 6793, 6803, 6823, 6827, 6829, 6833
data 6841, 6857, 6863, 6869, 6871, 6883, 6899, 6907, 6911, 6917
data 6947, 6949, 6959, 6961, 6967, 6971, 6977, 6983, 6991, 6997
data 7001, 7013, 7019, 7027, 7039, 7043, 7057, 7069, 7079, 7103
data 7109, 7121, 7127, 7129, 7151, 7159, 7177, 7187, 7193, 7207
data 7211, 7213, 7219, 7229, 7237, 7243, 7247, 7253, 7283, 7297
data 7307, 7309, 7321, 7331, 7333, 7349, 7351, 7369, 7393, 7411
data 7417, 7433, 7451, 7457, 7459, 7477, 7481, 7487, 7489, 7499
data 7507, 7517, 7523, 7529, 7537, 7541, 7547, 7549, 7559, 7561
data 7573, 7577, 7583, 7589, 7591, 7603, 7607, 7621, 7639, 7643
data 7649, 7669, 7673, 7681, 7687, 7691, 7699, 7703, 7717, 7723
data 7727, 7741, 7753, 7757, 7759, 7789, 7793, 7817, 7823, 7829
data 7841, 7853, 7867, 7873, 7877, 7879, 7883, 7901, 7907, 7919
print "Liberty Miller Rabin Demonstration"
print "Loading Small Primes"
for i=1 to 1000: read x : SmallPrimes(i)=x :next :NoOfSmallPrimes=1000
print NoOfSmallPrimes;" Primes Loaded"
'Prompt "Enter number to test:";resp$
'x=val(resp$)
'goto [Jump]
For i=1 to 11
x=mersenne(i)
t1=time$("ms")
[TryAnother]
print
iterations=0
[Loop]
iterations=iterations+1
if MillerRabin(x,7)=1 then
t2=time$("ms")
print "Composite, found in ";t2-t1;" milliseconds"
else
t2=time$("ms")
print x;" Probably Prime. Tested in ";t2-t1;" milliseconds"
playwave "tada.wav", async
end if
print
next
END
Function GCD( m,n )
' Find greatest common divisor with Extend Euclidian Algorithm
' Knuth Vol 1 P.13 Algorithm E
ap =1 :b =1 :a =0 :bp =0: c =m :d =n
[StepE2]
q = int(c/d) :r = c-q*d
if r<>0 then
c=d :d=r :t=ap :ap=a :a=t-q*a :t=bp :bp=b :b=t-q*b
'print ap;" ";b;" ";a;" ";bp;" ";c;" ";d;" ";t;" ";q
goto [StepE2]
end if
GCD=a*m+b*n
'print ap;" ";b;" ";a;" ";bp;" ";c;" ";d;" ";t;" ";q
End Function 'Extended Euclidian GCD
function IsEven( x )
if ( x MOD 2 )=0 then
IsEven=1
else
IsEven=0
end if
end function
function IsOdd( x )
if ( x MOD 2 )=0 then
IsOdd=0
else
IsOdd=1
end if
end function
Function FastExp(x, y, N)
if (y=1) then 'MOD(x,N)
FastExp=x-int(x/N)*N
goto [ExitFunction]
end if
if ( y and 1) = 0 then
dum1=y/2
dum2=y-int(y/2)*2 'MOD(y,2)
temp=FastExp(x,dum1,N)
z=temp*temp
FastExp=z-int(z/N)*N 'MOD(temp*temp,N)
goto [ExitFunction]
else
dum1=y-1
dum1=dum1/2
temp=FastExp(x,dum1,N)
dum2=temp*temp
temp=dum2-int(dum2/N)*N 'MOD(dum2,N)
z=temp*x
FastExp=z-int(z/N)*N 'MOD(temp*x,N)
goto [ExitFunction]
end if
[ExitFunction]
end function
Function MillerRabin(n,b)
'print "Miller Rabin"
't1=time$("ms")
if IsEven(n) then
MillerRabin=1
goto [ExtFn]
end if
i=0
[Loop]
i=i+1
if i>1000 then goto [Continue]
if ( n MOD SmallPrimes(i) )=0 then
MillerRabin=0
goto [ExtFn]
end if
goto [Loop]
[Continue]
if GCD(n,b)>1 then
MillerRabin=1
goto [ExtFn]
end if
q=n-1
t=0
while (int(q) AND 1 )=0
t=t+1
q=int(q/2)
wend
r=FastExp(b, q, n)
if ( r <> 1 ) then
e=0
while ( e < (t-1) )
if ( r <> (n-1) ) then
r=FastExp(r, r, n)
else
Exit While
end if
e=e+1
wend
[ExitLoop]
end if
if ( (r=1) OR (r=(n-1)) ) then
MillerRabin=0
else
MillerRabin=1
end if
[ExtFn]
End Function
|
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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:
if column > 0: stdout.write ' '
stdout.write if i == 0: " " else: &"{mertens[i]:>2}"
inc column
if column == 20:
stdout.write '\n'
column = 0
var zero, cross, previous = 0
for i in 1..Max:
let m = mertens[i]
if m == 0:
inc zero
if previous != 0:
inc cross
previous = m
echo ""
echo &"M(n) is zero {zero} times for 1 ⩽ n ⩽ {Max}."
echo &"M(n) crosses zero {cross} times for 1 ⩽ n ⩽ {Max}." |
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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 len) S" mirror mirror" ;
: TICKTOCK ( -- addr len) S" tick tock" ;
CASE: SELECT ( n -- addr len)
| NIL | FEE | HUFF | MIRROR | TICKTOCK
;CASE
CHAR 1 CONSTANT '1'
CHAR 4 CONSTANT '4'
: BETWEEN ( n low hi -- ?) 1+ WITHIN ;
: MENU ( addr len -- addr len )
DUP 0=
IF
2DROP NIL EXIT
ELSE
BEGIN
CR
CR 2DUP 3 SPACES TYPE
CR ." 1 " 1 SELECT TYPE
CR ." 2 " 2 SELECT TYPE
CR ." 3 " 3 SELECT TYPE
CR ." 4 " 4 SELECT TYPE
CR ." Choice: " KEY DUP EMIT
DUP '1' '4' BETWEEN 0=
WHILE
DROP
REPEAT
-ROT 2DROP \ drop input string
CR [CHAR] 0 - SELECT
THEN
; |
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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,
6, 10, 15, 21
};
private static final int[] TABLE_T = new int[64];
static
{
for (int i = 0; i < 64; i++)
TABLE_T[i] = (int)(long)((1L << 32) * Math.abs(Math.sin(i + 1)));
}
public static byte[] computeMD5(byte[] message)
{
int messageLenBytes = message.length;
int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;
int totalLen = numBlocks << 6;
byte[] paddingBytes = new byte[totalLen - messageLenBytes];
paddingBytes[0] = (byte)0x80;
long messageLenBits = (long)messageLenBytes << 3;
for (int i = 0; i < 8; i++)
{
paddingBytes[paddingBytes.length - 8 + i] = (byte)messageLenBits;
messageLenBits >>>= 8;
}
int a = INIT_A;
int b = INIT_B;
int c = INIT_C;
int d = INIT_D;
int[] buffer = new int[16];
for (int i = 0; i < numBlocks; i ++)
{
int index = i << 6;
for (int j = 0; j < 64; j++, index++)
buffer[j >>> 2] = ((int)((index < messageLenBytes) ? message[index] : paddingBytes[index - messageLenBytes]) << 24) | (buffer[j >>> 2] >>> 8);
int originalA = a;
int originalB = b;
int originalC = c;
int originalD = d;
for (int j = 0; j < 64; j++)
{
int div16 = j >>> 4;
int f = 0;
int bufferIndex = j;
switch (div16)
{
case 0:
f = (b & c) | (~b & d);
break;
case 1:
f = (b & d) | (c & ~d);
bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
break;
case 2:
f = b ^ c ^ d;
bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
break;
case 3:
f = c ^ (b | ~d);
bufferIndex = (bufferIndex * 7) & 0x0F;
break;
}
int temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] + TABLE_T[j], SHIFT_AMTS[(div16 << 2) | (j & 3)]);
a = d;
d = c;
c = b;
b = temp;
}
a += originalA;
b += originalB;
c += originalC;
d += originalD;
}
byte[] md5 = new byte[16];
int count = 0;
for (int i = 0; i < 4; i++)
{
int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));
for (int j = 0; j < 4; j++)
{
md5[count++] = (byte)n;
n >>>= 8;
}
}
return md5;
}
public static String toHexString(byte[] b)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < b.length; i++)
{
sb.append(String.format("%02X", b[i] & 0xFF));
}
return sb.toString();
}
public static void main(String[] args)
{
String[] testStrings = { "", "a", "abc", "message digest", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "12345678901234567890123456789012345678901234567890123456789012345678901234567890" };
for (String s : testStrings)
System.out.println("0x" + toHexString(computeMD5(s.getBytes())) + " <== \"" + s + "\"");
return;
}
} |
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('l', [1, 2, 3, 4, 5])
array('d', [1.0, 2.0, 3.1400000000000001])
>>> |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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-none f.f08 -o f
! 123 123
! 12345 234
! 1234567 345
! 987654321 654
! 10001 000
! -10001 000
! -123 123
! -100 100
! 100 100
! -12345 234
! 1 Too short
! 2 Too short
! -1 Too short
! -10 Too short
! 2002 Digit count too even
! -2002 Digit count too even
! 0 Too short
!
!Compilation finished at Sat Jun 1 14:48:41
program MiddleMuddle
integer, dimension(17) :: itest, idigits
integer :: i, n
data itest/123,12345,1234567,987654321,10001,-10001,-123,-100,100,-12345,1,2,-1,-10,2002,-2002,0/
do i = 1, size(itest)
call antibase(10, abs(itest(i)), idigits, n)
write(6,'(i20,2x,a20)') itest(i), classifym3(idigits, n)
if (0 .eq. itest(i)) exit
end do
contains
logical function even(n)
integer, intent(in) :: n
even = 0 .eq. iand(n,1)
end function even
function classifym3(iarray, n) result(s)
integer, dimension(:), intent(in) :: iarray
integer, intent(in) :: n
character(len=20) :: s
integer :: i,m
if (n < 3) then
s = 'Too short'
else if (even(n)) then
s = 'Digit count too even'
else
m = (n+1)/2
write(s,'(3i1)')(iarray(i), i=m+1,m-1,-1)
end if
end function classifym3
subroutine antibase(base, m, digits, n) ! digits ordered by increasing significance
integer, intent(in) :: base, m
integer, intent(out) :: n ! the number of digits
integer, dimension(:), intent(out) :: digits
integer :: em
em = m
do n=1, size(digits)
digits(n) = mod(em, base)
em = em / base
if (0 .eq. em) return
end do
stop 'antibase ran out of space to store result'
end subroutine antibase
end program MiddleMuddle
|
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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
end
-- Now n is odd and greater than 1.
-- Find the unique expression n = 1 + t*2^h for n, where t is odd and h≥1.
t = (n-1)/2
h = 1
while t%2 == 0 do
t = t/2
h = h + 1
end
for i = 1, k do
-- Generate a random integer between 1 and n-1 inclusive.
a = math.random(n-1)
-- Test whether a is an element of the set L, and return false if not.
if not IsInL(n, a, t, h) then
return false
end
end
-- All generated a were in the set L; thus with high probability, n is prime.
return true
end
function IsInL(n, a, t, h)
local b = PowerMod(a, t, n)
if b == 1 then
return true
end
for j = 0, h-1 do
if b == n-1 then
return true
elseif b == 1 then
return false
end
b = (b^2)%n
end
return false
end
function PowerMod(x, y, m)
-- Computes x^y mod m.
local z = 1
while y > 0 do
if y%2 == 0 then
x, y, z = (x^2)%m, y//2, z
else
x, y, z = (x^2)%m, y//2, (x*z)%m
end
end
return z
end |
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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;
primes : array of byte;
sieve : array of tSieveElement;
procedure CompactPrimes;
//searching for needed primes
//last primes are marked with -1
var
pSieve : tpSieve;
i,lmt,dp:NativeInt;
Begin
setlength(Primes,74500);//suffices for primes to calc square upto 1e12
//extract difference of primes
i := 2;
lmt := 0;
dp := 2;
pSieve :=@sieve[0];
repeat
IF pSieve[i]= 0 then
Begin
//mark for Moebius
pSieve[i]:= -1;
primes[lmt] := dp;
dp := 0;
inc(lmt);
end;
inc(dp);
inc(i);
until i*i >BigLimit;
setlength(Primes,lmt+1);
repeat
IF pSieve[i]= 0 then
//mark for Moebius
pSieve[i]:= -1;
inc(i);
until i >BigLimit;
end;
procedure SieveSquares;
//mark all powers >=2 of prime => all powers = 2 is sufficient
var
pSieve : tpSieve;
i,sq,k,prime : NativeInt;
Begin
pSieve := @sieve[0];
prime := 0;
For i := 0 to High(primes) do
Begin
prime := prime+primes[i];
sq := prime*prime;
k := sq;
if sq > BigLimit then
break;
repeat
pSieve[k] := 0;
inc(k,sq);
until k> BigLimit;
end;
end;
procedure initPrimes;
var
pSieve : tpSieve;
fakt,
sieveprime : NativeUint;
begin
pSieve := @sieve[0];
sieveprime := 2;
repeat
if pSieve[sieveprime]=0 then
begin
fakt := sieveprime+sieveprime;
while fakt <=BigLimit do
Begin
//count divisors
inc(pSieve[fakt]);
inc(fakt,sieveprime);
end;
end;
inc(sieveprime);
until sieveprime>BigLimit DIV 2;
//Möbius of 1
pSieve[1] := 1;
//convert to Moebius
For fakt := 2 to BigLimit do
Begin
sieveprime := pSieve[fakt];
IF sieveprime<>0 then
pSieve[fakt] := 1-(2*(sieveprime AND 1)) ;
end;
CompactPrimes;
SieveSquares;
end;
procedure OutMerten10(Lmt,ZeroCross:NativeInt;Const MoebVal:tMoebVal);
var
i,j: NativeInt;
Begin
Writeln(lmt:11,MoebVal[-1]:11,MoebVal[1]:11,MoebVal[-1]+MoebVal[1]:11,
MoebVal[-1]-MoebVal[1]:7,MoebVal[0]:11);
i:= low(MertensValues);
while MertensValues[i] = 0 do
inc(i);
j:= High(MertensValues);
while MertensValues[j] = 0 do
dec(j);
write('Merten min ',i:6,' max ',j:6,' zero''s ',MertensValues[0]:8);
writeln(' zeroCross ',ZeroCross);
writeln;
end;
procedure Count_x10;
var
MoebCount: tMoebVal;
pSieve : tpSieve;
i,lmt,Merten,Moebius,LastMert,ZeroCross: NativeInt;
begin
writeln('[1 to limit]');
Writeln('Limit Moeb. odd Moeb.even sqr-free Merten Zero''s');
pSieve := @sieve[0];
For i := -1 to 1 do
MoebCount[i]:=0;
ZeroCross := 0;
LastMert :=1;
Merten :=0;
lmt := 10;
i := 1;
repeat
while i <= lmt do
Begin
Moebius := pSieve[i];
inc(MoebCount[Moebius]);
inc(Merten,Moebius);
inc(MertensValues[Merten]);//MoebCount[1]-MoebCount[-1]]);
inc(ZeroCross,ORD( (Merten = 0) AND (LastMert <> 0)));
LastMert := Merten;
inc(i);
end;
OutMerten10(Lmt,ZeroCross,MoebCount);
IF lmt >= BigLimit then
BREAK;
lmt := lmt*10;
IF lmt >BigLimit then
lmt := BigLimit;
until false;
writeln;
end;
procedure OutMerten(lmt:NativeInt);
var
i,k,m : NativeInt;
Begin
iF lmt> BigLimit then
lmt := BigLimit;
writeln('Mertens numbers from 1 to ',lmt);
k := 9;
write('':3);
m := 0;
For i := 1 to lmt do
Begin
inc(m,sieve[i]);
write(m:3);
dec(k);
IF k = 0 then
Begin
writeln;
k := 10;
end;
end;
writeln;
end;
procedure OutMoebius(lmt:NativeInt);
var
i,k : NativeInt;
Begin
iF lmt> BigLimit then
lmt := BigLimit;
writeln('Möbius numbers from 1 to ',lmt);
k := 19;
write('':3);
For i := 1 to lmt do
Begin
write(sieve[i]:3);
dec(k);
IF k = 0 then
Begin
writeln;
k := 20;
end;
end;
writeln;
end;
Begin
setlength(sieve,BigLimit+1);
InitPrimes;
SieveSquares;
Count_x10;
OutMoebius(199);
OutMerten(99);
setlength(primes,0);
setlength(sieve,0);
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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=*),dimension(:),intent(in) :: options
character(len=len(options)) :: choice
integer :: i,ichoose,ios,n
choice = ""
n = size(options)
if (n > 0) then
do
print "(a)",title
print "(i8,"", "",a)",(i,options(i),i=1,n)
read (*,fmt="(i8)",iostat=ios) ichoose
if (ios == -1) exit ! EOF error
if (ios /= 0) cycle ! other error
if (ichoose < 1) cycle
if (ichoose > n) cycle ! out-of-bounds
choice = options(ichoose)
exit
end do
end if
end function selector
end module menu
program menu_demo
use menu
character(len=14),dimension(:),allocatable :: zero_items,fairytale
character(len=len(zero_items)) :: s
!! empty list demo
allocate(zero_items(0))
print "(a)","input items:",zero_items
s = selector('Choose from the empty list',zero_items)
print "(a)","returned:",s
if (s == "") print "(a)","(an empty string)"
!! Fairy tale demo
allocate(fairytale(4))
fairytale = (/'fee fie ','huff and puff ', &
'mirror mirror ','tick tock '/)
print "(a)","input items:",fairytale
s = selector('Choose a fairy tale',fairytale)
print "(a)","returned: ",s
if (s == "") print "(a)","(an empty string)"
end program menu_demo
|
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]
const K = UInt32[0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf,
0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1,
0x895cd7be, 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562,
0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681,
0xe7d3fbc8, 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905,
0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122,
0xfde5380c, 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6,
0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8,
0xc4ac5665, 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3,
0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314,
0x4e0811a1, 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391]
function md5(msgbytes)
a0::UInt32 = 0x67452301 # A
b0::UInt32 = 0xefcdab89 # B
c0::UInt32 = 0x98badcfe # C
d0::UInt32 = 0x10325476 # D
oldlen = length(msgbytes)
umsg = push!([UInt8(b) for b in msgbytes], UInt8(0x80))
while length(umsg) % 64 != 56
push!(umsg, UInt8(0))
end
append!(umsg, reinterpret(UInt8, [htol(UInt64(oldlen) * 8)]))
for j in 1:64:length(umsg)-1
arr = view(umsg, j:j+63)
M = [reinterpret(UInt32, arr[k:k+3])[1] for k in 1:4:62]
A = a0
B = b0
C = c0
D = d0
for i in 0:63
if 0 ≤ i ≤ 15
F = D ⊻ (B & (C ⊻ D))
g = i
elseif 16 ≤ i ≤ 31
F = C ⊻ (D & (B ⊻ C))
g = (5 * i + 1) % 16
elseif 32 ≤ i ≤ 47
F = B ⊻ C ⊻ D
g = (3 * i + 5) % 16
elseif 48 ≤ i ≤ 63
F = C ⊻ (B | (~D))
g = (7 * i) % 16
end
F += A + K[i+1] + M[g+1]
A = D
D = C
C = B
B += ((F) << s[i+1]) | (F >> (32 - s[i+1]))
end
a0 += A
b0 += B
c0 += C
d0 += D
end
digest = join(map(x -> lpad(string(x, base=16), 2, '0'), reinterpret(UInt8, [a0, b0, c0, d0])), "") # Output is in little-endian
end
for pair in [0xd41d8cd98f00b204e9800998ecf8427e => "", 0x0cc175b9c0f1b6a831c399e269772661 => "a",
0x900150983cd24fb0d6963f7d28e17f72 => "abc", 0xf96b697d7cb7938d525a2f31aaf161d0 => "message digest",
0xc3fcd3d76192e4007dfb496cca67e13b => "abcdefghijklmnopqrstuvwxyz",
0xd174ab98d277d9f5a5611c2c9f419d9f => "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
0x57edf4a22be3c955ac49da2e2107b67a => "12345678901234567890123456789012345678901234567890123456789012345678901234567890"]
println("MD5 of $(pair[2]) is $(md5(pair[2])), which checks with $(string(pair[1], base=16)).")
end
|
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 required memory for the <limit-custodian>
; If amount of bytes can't be reached, <stop-custodian> is shutdown
(custodian-limit-memory <custodian> <amount>) ; Register a limit on memory for the <custodian> |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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 to be 3 middle
Return Mid(ns, Len(ns) \ 2, 3)
End Function
Dim a(1 To 16) As Integer => _
{123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -123451, 2, -1, -10, 2002, -2002, 0}
Dim As Integer i
Dim As String result
Print "The 3 middle digits of the following numbers are : "
Print
For i = 1 To 16
result = middleThreeDigits(a(i))
Print a(i), " => ";
If result <> "" Then
Print result
Else
Print "Error: does not have 3 middle digits"
End If
Next
Print
Print "Press any key to quit"
Sleep |
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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 : -1 : 0
}
sub progressive_sum {
my @sum = shift @_;
push @sum, $sum[-1] + $_ for @_;
@sum
}
my($upto, $show, @möebius) = (1000, 199, ());
push @möebius, μ($_) for 1..$upto;
my @mertens = progressive_sum @möebius;
say "Mertens sequence - First $show terms:\n" .
(' 'x4 . sprintf "@{['%4d' x $show]}", @mertens[0..$show-1]) =~ s/((.){80})/$1\n/gr .
sprintf("\nEquals zero %3d times between 1 and $upto", scalar grep { ! $_ } @mertens) .
sprintf "\nCrosses zero%3d times between 1 and $upto", scalar grep { ! $mertens[$_-1] and $mertens[$_] } 1 .. @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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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
print
input "Choice? ", c
vc = val(c)
wend
return m(vc)
end function
print menu_select( menu() ) |
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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, 10, 15, 21
)
private val TABLE_T = IntArray(64) {
((1L shl 32) * Math.abs(Math.sin(it + 1.0))).toLong().toInt()
}
fun compute(message: ByteArray): ByteArray {
val messageLenBytes = message.size
val numBlocks = ((messageLenBytes + 8) ushr 6) + 1
val totalLen = numBlocks shl 6
val paddingBytes = ByteArray(totalLen - messageLenBytes)
paddingBytes[0] = 0x80.toByte()
var messageLenBits = (messageLenBytes shl 3).toLong()
for (i in 0..7) {
paddingBytes[paddingBytes.size - 8 + i] = messageLenBits.toByte()
messageLenBits = messageLenBits ushr 8
}
var a = INIT_A
var b = INIT_B
var c = INIT_C
var d = INIT_D
val buffer = IntArray(16)
for (i in 0 until numBlocks) {
var index = i shl 6
for (j in 0..63) {
val temp = if (index < messageLenBytes) message[index] else
paddingBytes[index - messageLenBytes]
buffer[j ushr 2] = (temp.toInt() shl 24) or (buffer[j ushr 2] ushr 8)
index++
}
val originalA = a
val originalB = b
val originalC = c
val originalD = d
for (j in 0..63) {
val div16 = j ushr 4
var f = 0
var bufferIndex = j
when (div16) {
0 -> {
f = (b and c) or (b.inv() and d)
}
1 -> {
f = (b and d) or (c and d.inv())
bufferIndex = (bufferIndex * 5 + 1) and 0x0F
}
2 -> {
f = b xor c xor d;
bufferIndex = (bufferIndex * 3 + 5) and 0x0F
}
3 -> {
f = c xor (b or d.inv());
bufferIndex = (bufferIndex * 7) and 0x0F
}
}
val temp = b + Integer.rotateLeft(a + f + buffer[bufferIndex] +
TABLE_T[j], SHIFT_AMTS[(div16 shl 2) or (j and 3)])
a = d
d = c
c = b
b = temp
}
a += originalA
b += originalB
c += originalC
d += originalD
}
val md5 = ByteArray(16)
var count = 0
for (i in 0..3) {
var n = if (i == 0) a else (if (i == 1) b else (if (i == 2) c else d))
for (j in 0..3) {
md5[count++] = n.toByte()
n = n ushr 8
}
}
return md5
}
}
fun ByteArray.toHexString(): String {
val sb = StringBuilder()
for (b in this) sb.append(String.format("%02x", b.toInt() and 0xFF))
return sb.toString()
}
fun main(args: Array<String>) {
val testStrings = arrayOf(
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890"
)
println("${"hash code".padStart(34)} <== string")
for (s in testStrings) {
println("0x${MD5.compute(s.toByteArray()).toHexString()} <== \"$s\"")
}
} |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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 'Counter
Dim sAnswer As New String[] 'Array, resons for failure or 'middle three digits'
For siCount = 0 To iList.Max 'Loop through the integers
sTemp = Str(Abs(iList[siCount])) 'Convert integer to positive and place in sTemp as a string
If Len(sTemp) < 3 Then 'If sTemp has less than 3 characters then..
sAnswer.Add("This integer has less than 3 characters") 'Place text in sAnswers
Else If Even(Len(sTemp)) Then 'Else If sTemp is of even length then
sAnswer.Add("This integer has an even length") 'Place text in sAnswers
Else 'Else..
sAnswer.Add(Mid(sTemp, Int(Len(sTemp) / 2), 3)) 'Place the middle 3 digits in sAnswer
Endif
Next
For siCount = 0 To iList.Max 'Loop through the integers
Print Space$(10 - Len(Str(iList[siCount]))) &
iList[siCount] & " : " & sAnswer[siCount] 'Print out results
Next
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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 pseudoprime to base a; s and d are given by facpow(n - 1, 2) */
sppp(n, a, s, d) := block(
[x: power_mod(a, d, n), q: false],
if x = 1 or x = n - 1 then true else (
from 2 thru s do (
x: mod(x * x, n),
if x = 1 then return(q: false) elseif x = n - 1 then return(q: true)
),
q
)
)$
/* Miller-Rabin primality test. For n < 341550071728321, the test is deterministic;
for larger n, the number of bases tested is given by the option variable
primep_number_of_tests, which is used by Maxima in primep. The bound for deterministic
test is also the same as in primep. */
miller_rabin(n) := block(
[v: [2, 3, 5, 7, 11, 13, 17], s, d, q: true, a],
if n < 19 then member(n, v) else (
[s, d]: facpow(n - 1, 2),
if n < 341550071728321 then ( /* see http://oeis.org/A014233 */
for a in v do (
if not sppp(n, a, s, d) then return(q: false)
),
q
) else (
thru primep_number_of_tests do (
a: 2 + random(n - 3),
if not sppp(n, a, s, d) then return(q: false)
),
q
)
)
)$ |
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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
integer m = Mertens(n)
if m=0 then
zeroes += 1
crosses += prev!=0
end if
prev = m
end for
printf(1,"\nMertens[1..1000] equals zero %d times and crosses zero %d times\n",{zeroes,crosses})
|
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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)
If sChoice = "" Then
Print "menu returned an empty string"
Else
Print Subst(sFeedbackFormat, sChoice)
Endif
End
Private Function Menu(asChoices As String[], sPrompt As String) As String
Dim sReturnValue As String = ""
Dim sMenuLineFormat As String = "&1) &2"
Dim sAnswer As String
Dim iAnswer As Integer
Dim iIndex As Integer = 0
Dim sMenuItem As String
If Not IsNull(asChoices) Then
If asChoices.Count > 0 Then
Do
For iIndex = 0 To asChoices.Max
sMenuItem = asChoices[iIndex]
Print Subst(sMenuLineFormat, iIndex, sMenuItem)
Next
Print sPrompt
Input sAnswer
If IsNumber(sAnswer) Then
iAnswer = sAnswer
If (0 <= iAnswer) And (iAnswer <= asChoices.Max) Then
sReturnValue = asChoices[iAnswer]
Break
Endif
Endif
Loop
Endif
Endif
Return sReturnValue
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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...
t_iLen = input.length * 8
t_iCnt = (t_iLen + 64) / 512 * 16 + 16
-- Create list, fill with zeros...
x = []
x[t_iCnt] = 0
t_fArr = [1, 256, 65536, 16777216]
i = 0
j = 0
repeat while i < t_iLen
j = j + 1
t_iNext = i / 32 + 1
t_iTemp = bitAnd(input[i/8+1], 255) * t_fArr[j]
x[t_iNext] = bitOr(x[t_iNext], t_iTemp)
i = i + 8
j = j mod 4
end repeat
-- Append padding...
t_iNext = t_iLen / 32 + 1
x[t_iNext] = bitOr(x[t_iNext], 128 * t_fArr[j + 1])
x[(t_iLen + 64) / 512 * 16 + 15] = t_iLen
-- Actual algorithm starts here...
a = 1732584193
b = -271733879
c = -1732584194
d = 271733878
i = 1
t_iWrap = the maxInteger + 1
t_iCount = x.count + 1
repeat while i < t_iCount
olda = a
oldb = b
oldc = c
oldd = d
-- Round(1) --
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i] - 680876936
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 1] - 389564586
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 2] + 606105819
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 3] - 1044525330
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 4] - 176418897
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 5] + 1200080426
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 6] - 1473231341
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 7] - 45705983
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 8] + 1770035416
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 9] - 1958414417
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 10] - 42063
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 11] - 1990404162
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 12] + 1804603682
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 13] - 40341101
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 14] - 1502002290
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 15] + 1236535329
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
-- Round(2) --
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 1] - 165796510
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 6] - 1069501632
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 11] + 643717713
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i] - 373897302
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 5] - 701558691
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 10] + 38016083
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 15] - 660478335
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 4] - 405537848
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 9] + 568446438
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 14] - 1019803690
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 3] - 187363961
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 8] + 1163531501
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 13] - 1444681467
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 2] - 51403784
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 7] + 1735328473
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 12] - 1926607734
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
-- Round(3) --
n = bitXor(bitXor(b, c), d) + a + x[i + 5] - 378558
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 8] - 2022574463
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 11] + 1839030562
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 14] - 35309556
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 1] - 1530992060
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 4] + 1272893353
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 7] - 155497632
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 10] - 1094730640
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 13] + 681279174
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i] - 358537222
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 3] - 722521979
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 6] + 76029189
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 9] - 640364487
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 12] - 421815835
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 15] + 530742520
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 2] - 995338651
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
-- Round(4) --
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i] - 198630844
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 7] + 1126891415
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 14] - 1416354905
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 5] - 57434055
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 12] + 1700485571
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 3] - 1894986606
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 10] - 1051523
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 1] - 2054922799
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 8] + 1873313359
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 15] - 30611744
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 6] - 1560198380
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 13] + 1309151649
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 4] - 145523070
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 11] - 1120210379
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 2] + 718787259
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 9] - 343485551
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
a = a + olda
b = b + oldb
c = c + oldc
d = d + oldd
i = i + 16
end repeat
t_iArr = [a, b, c, d]
ba = bytearray()
p = 1
repeat with i in t_iArr
if(i > 0) then
repeat with n = 1 to 4
ba[p] = (i mod 256)
i = i / 256
p = p+1
end repeat
else
i = bitNot(i)
repeat with n = 1 to 4
ba[p] = 255-(i mod 256)
i = i / 256
p = p+1
end repeat
end if
end repeat
ba.position = 1
return ba
end |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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
}
s := strconv.Itoa(i)
if len(s)%2 == 0 {
return "", ErrorEven
}
m := len(s) / 2
return s[m-1 : m+2], nil
} |
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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;
end;
put skip list('The first 99 Mertens numbers are:');
put skip list(' ');
do n = 1 to 99;
put edit(M(n)) (F(3));
if mod(n,10) = 9 then put skip;
end;
isZero = 0;
crossZero = 0;
do n = 2 to MAX;
if M(n) = 0 then do;
isZero = isZero + 1;
if M(n-1) ^= 0 then
crossZero = crossZero + 1;
end;
end;
put skip list('Zeroes: ',isZero);
put skip list('Crossings:',crossZero);
end 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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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.Scanln(&c)
if err == nil && c > 0 && c <= len(choices) {
break
}
}
return choices[c-1]
}
func main() {
pick := menu(nil, "No prompt")
fmt.Printf("No choices, result = %q\n", pick)
choices := []string{
"fee fie",
"huff and puff",
"mirror mirror",
"tick tock",
}
pick = menu(choices, "Enter number: ")
fmt.Printf("You picked %q\n", pick)
} |
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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...
t_iLen = input.length * 8
t_iCnt = (t_iLen + 64) / 512 * 16 + 16
-- Create list, fill with zeros...
x = []
x[t_iCnt] = 0
t_fArr = [1, 256, 65536, 16777216]
i = 0
j = 0
repeat while i < t_iLen
j = j + 1
t_iNext = i / 32 + 1
t_iTemp = bitAnd(input[i/8+1], 255) * t_fArr[j]
x[t_iNext] = bitOr(x[t_iNext], t_iTemp)
i = i + 8
j = j mod 4
end repeat
-- Append padding...
t_iNext = t_iLen / 32 + 1
x[t_iNext] = bitOr(x[t_iNext], 128 * t_fArr[j + 1])
x[(t_iLen + 64) / 512 * 16 + 15] = t_iLen
-- Actual algorithm starts here...
a = 1732584193
b = -271733879
c = -1732584194
d = 271733878
i = 1
t_iWrap = the maxInteger + 1
t_iCount = x.count + 1
repeat while i < t_iCount
olda = a
oldb = b
oldc = c
oldd = d
-- Round(1) --
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i] - 680876936
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 1] - 389564586
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 2] + 606105819
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 3] - 1044525330
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 4] - 176418897
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 5] + 1200080426
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 6] - 1473231341
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 7] - 45705983
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 8] + 1770035416
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 9] - 1958414417
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 10] - 42063
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 11] - 1990404162
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
n = bitOr(bitAnd(b, c), bitAnd(bitNot(b), d)) + a + x[i + 12] + 1804603682
if(n < 0) then a = bitOr(n * 128, bitOr((n + t_iWrap) / 33554432, 64)) + b
else a = bitOr(n * 128, n / 33554432) + b
n = bitOr(bitAnd(a, b), bitAnd(bitNot(a), c)) + d + x[i + 13] - 40341101
if(n < 0) then d = bitOr(n * 4096, bitOr((n + t_iWrap) / 1048576, 2048)) + a
else d = bitOr(n * 4096, n / 1048576) + a
n = bitOr(bitAnd(d, a), bitAnd(bitNot(d), b)) + c + x[i + 14] - 1502002290
if(n < 0) then c = bitOr(n * 131072, bitOr((n + t_iWrap) / 32768, 65536)) + d
else c = bitOr(n * 131072, n / 32768) + d
n = bitOr(bitAnd(c, d), bitAnd(bitNot(c), a)) + b + x[i + 15] + 1236535329
if(n < 0) then b = bitOr(n * 4194304, bitOr((n + t_iWrap) / 1024, 2097152)) + c
else b = bitOr(n * 4194304, n / 1024) + c
-- Round(2) --
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 1] - 165796510
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 6] - 1069501632
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 11] + 643717713
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i] - 373897302
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 5] - 701558691
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 10] + 38016083
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 15] - 660478335
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 4] - 405537848
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 9] + 568446438
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 14] - 1019803690
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 3] - 187363961
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 8] + 1163531501
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
n = bitOr(bitAnd(b, d), bitAnd(c, bitNot(d))) + a + x[i + 13] - 1444681467
if(n < 0) then a = bitOr(n * 32, bitOr((n + t_iWrap) / 134217728, 16)) + b
else a = bitOr(n * 32, n / 134217728) + b
n = bitOr(bitAnd(a, c), bitAnd(b, bitNot(c))) + d + x[i + 2] - 51403784
if(n < 0) then d = bitOr(n * 512, bitOr((n + t_iWrap) / 8388608, 256)) + a
else d = bitOr(n * 512, n / 8388608) + a
n = bitOr(bitAnd(d, b), bitAnd(a, bitNot(b))) + c + x[i + 7] + 1735328473
if(n < 0) then c = bitOr(n * 16384, bitOr((n + t_iWrap) / 262144, 8192)) + d
else c = bitOr(n * 16384, n / 262144) + d
n = bitOr(bitAnd(c, a), bitAnd(d, bitNot(a))) + b + x[i + 12] - 1926607734
if(n < 0) then b = bitOr(n * 1048576, bitOr((n + t_iWrap) / 4096, 524288)) + c
else b = bitOr(n * 1048576, n / 4096) + c
-- Round(3) --
n = bitXor(bitXor(b, c), d) + a + x[i + 5] - 378558
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 8] - 2022574463
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 11] + 1839030562
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 14] - 35309556
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 1] - 1530992060
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 4] + 1272893353
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 7] - 155497632
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 10] - 1094730640
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 13] + 681279174
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i] - 358537222
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 3] - 722521979
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 6] + 76029189
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
n = bitXor(bitXor(b, c), d) + a + x[i + 9] - 640364487
if(n < 0) then a = bitOr(n * 16, bitOr((n + t_iWrap) / 268435456, 8)) + b
else a = bitOr(n * 16, n / 268435456) + b
n = bitXor(bitXor(a, b), c) + d + x[i + 12] - 421815835
if(n < 0) then d = bitOr(n * 2048, bitOr((n + t_iWrap) / 2097152, 1024)) + a
else d = bitOr(n * 2048, n / 2097152) + a
n = bitXor(bitXor(d, a), b) + c + x[i + 15] + 530742520
if(n < 0) then c = bitOr(n * 65536, bitOr((n + t_iWrap) / 65536, 32768)) + d
else c = bitOr(n * 65536, n / 65536) + d
n = bitXor(bitXor(c, d), a) + b + x[i + 2] - 995338651
if(n < 0) then b = bitOr(n * 8388608, bitOr((n + t_iWrap) / 512, 4194304)) + c
else b = bitOr(n * 8388608, n / 512) + c
-- Round(4) --
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i] - 198630844
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 7] + 1126891415
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 14] - 1416354905
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 5] - 57434055
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 12] + 1700485571
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 3] - 1894986606
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 10] - 1051523
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 1] - 2054922799
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 8] + 1873313359
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 15] - 30611744
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 6] - 1560198380
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 13] + 1309151649
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
n = bitXor(c, bitOr(b, bitNot(d))) + a + x[i + 4] - 145523070
if(n < 0) then a = bitOr(n * 64, bitOr((n + t_iWrap) / 67108864, 32)) + b
else a = bitOr(n * 64, n / 67108864) + b
n = bitXor(b, bitOr(a, bitNot(c))) + d + x[i + 11] - 1120210379
if(n < 0) then d = bitOr(n * 1024, bitOr((n + t_iWrap) / 4194304, 512)) + a
else d = bitOr(n * 1024, n / 4194304) + a
n = bitXor(a, bitOr(d, bitNot(b))) + c + x[i + 2] + 718787259
if(n < 0) then c = bitOr(n * 32768, bitOr((n + t_iWrap) / 131072, 16384)) + d
else c = bitOr(n * 32768, n / 131072) + d
n = bitXor(d, bitOr(c, bitNot(a))) + b + x[i + 9] - 343485551
if(n < 0) then b = bitOr(n * 2097152, bitOr((n + t_iWrap) / 2048, 1048576)) + c
else b = bitOr(n * 2097152, n / 2048) + c
a = a + olda
b = b + oldb
c = c + oldc
d = d + oldd
i = i + 16
end repeat
t_iArr = [a, b, c, d]
ba = bytearray()
p = 1
repeat with i in t_iArr
if(i > 0) then
repeat with n = 1 to 4
ba[p] = (i mod 256)
i = i / 256
p = p+1
end repeat
else
i = bitNot(i)
repeat with n = 1 to 4
ba[p] = 255-(i mod 256)
i = i / 256
p = p+1
end repeat
end if
end repeat
ba.position = 1
return ba
end |
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 some data
*ptr = 123;
assert_eq!(*ptr, 123);
// deallocate `ptr` with associated layout `int_layout`
dealloc(ptr, int_layout);
} |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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 "Error: ${x} has less than 3 digits"
if(s.length % 2 == 0) return "Error: ${x} has an even number of digits"
var start = (s.length / 2) - 1
return s.substring(start, start + 3)
} |
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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, 61: return true
else: discard
var
nm1 = n-1
d = nm1.int
s = 0
n = n.uint64
while d mod 2 == 0:
d = d shr 1
s += 1
for a in [2, 7, 61]:
var
x = 1.uint64
p = a.uint64
dr = d
while dr > 0:
if dr mod 2 == 1:
x = x * p mod n
p = p * p mod n
dr = dr shr 1
if x == 1 or x.uint32 == nm1:
continue
var r = 1
while true:
if r >= s:
return false
x = x * x mod n
if x == 1:
return false
if x.uint32 == nm1:
break
r += 1
return true
proc isPrime*(n: int32): bool =
## Overload for int32
n >= 0 and n.uint32.isPrime
when isMainModule:
const primeNumber1000 = 7919 # source: https://en.wikipedia.org/wiki/List_of_prime_numbers
var
i = 0u32
numberPrimes = 0
while true:
if isPrime(i):
if numberPrimes == 999:
break
numberPrimes += 1
i += 1
assert i == primeNumber1000
assert isPrime(2u32)
assert isPrime(31u32)
assert isPrime(37u32)
assert isPrime(1123u32)
assert isPrime(492366587u32)
assert isPrime(1645333507u32)
|
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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,
mertens_number(N1, M1),
K1 is K + 1,
S1 is S - M1,
mertens_number(N, K1, M, S1).
print_mertens_numbers(Count):-
print_mertens_numbers(Count, 0).
print_mertens_numbers(Count, Count):-!.
print_mertens_numbers(Count, N):-
(N == 0 ->
write(' ')
;
mertens_number(N, M),
writef('%3r', [M])
),
N1 is N + 1,
Column is N1 mod 20,
(N > 0, Column == 0 ->
nl
;
true
),
print_mertens_numbers(Count, N1).
count_zeros(From, To, Z, C):-
count_zeros(From, To, Z, C, 0, 0, 0).
count_zeros(From, To, Z, C, Z, C, _):-
From > To,
!.
count_zeros(From, To, Z, C, Z1, C1, P):-
mertens_number(From, M),
(M == 0 -> Z2 is Z1 + 1 ; Z2 = Z1),
(M == 0, P \= 0 -> C2 is C1 + 1 ; C2 = C1),
Next is From + 1,
count_zeros(Next, To, Z, C, Z2, C2, M).
main:-
writeln('First 199 Mertens numbers:'),
print_mertens_numbers(200),
count_zeros(1, 1000, Z, C),
writef('M(n) is zero %t times for 1 <= n <= 1000.\n', [Z]),
writef('M(n) crosses zero %t times for 1 <= n <= 1000.\n', [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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
}
local function leftRotate(x, c)
return (x << c) | (x >> (32-c))
end
local function getInt(byteArray, n)
return (byteArray[n+3]<<24) + (byteArray[n+2]<<16) + (byteArray[n+1]<<8) + byteArray[n]
end
--- converts 32bit integer n to a little endian hex representation
-- @tparam integer n
local function lE(n)
local s = ''
for i = 0, 3 do
s = ('%s%02x'):format(s, (n>>(i*8))&0xff)
end
return s
end
--- md5
-- @tparam string message
local function md5(message)
local a0, b0, c0, d0 = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476
local bytes = {message:byte(1, -1)}
-- insert 1 bit (and the rest of the byte)
table.insert(bytes, 0x80)
-- pad with zeros until we have *just enough*
local p = #bytes%64
if p > 56 then
p = p - 64
end
for _ = p+1, 56 do
table.insert(bytes, 0)
end
-- insert the initial message length, in little-endian
local len = ((#message)<<3)&0xffffffffffffffff -- length in bits
for i = 0, 7 do
table.insert(bytes, (len>>(i*8))&0xff)
end
for i = 0, #bytes//64-1 do
local a, b, c, d = a0, b0, c0, d0
for j = 0, 63 do
local F, g
-- permutate
if j <= 15 then
F = (b & c) | (~b & d)
g = j
elseif j <= 31 then
F = (d & b) | (~d & c)
g = (5*j + 1) & 15
elseif j <= 47 then
F = b ~ c ~ d
g = (3*j + 5) & 15
else
F = c ~ (b | ~d)
g = (7*j) & 15
end
F = (F + a + K[j+1] + getInt(bytes, i*64+g*4+1))&0xffffffff
-- shuffle
a = d
d = c
c = b
b = (b + leftRotate(F, s[j+1]))&0xffffffff
end
-- update internal state
a0 = (a0 + a)&0xffffffff
b0 = (b0 + b)&0xffffffff
c0 = (c0 + c)&0xffffffff
d0 = (d0 + d)&0xffffffff
end
-- lua doesn't support any other byte strings. Could convert to a wacky string but this is more printable.
return lE(a0)..lE(b0)..lE(c0)..lE(d0)
end
local demo = {
[""] = "d41d8cd98f00b204e9800998ecf8427e",
["a"] = "0cc175b9c0f1b6a831c399e269772661",
["abc"] = "900150983cd24fb0d6963f7d28e17f72",
["message digest"] = "f96b697d7cb7938d525a2f31aaf161d0",
["abcdefghijklmnopqrstuvwxyz"] = "c3fcd3d76192e4007dfb496cca67e13b",
["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"] = "d174ab98d277d9f5a5611c2c9f419d9f",
["12345678901234567890123456789012345678901234567890123456789012345678901234567890"] = "57edf4a22be3c955ac49da2e2107b67a",
}
for k, v in pairs(demo) do
local m = md5(k)
print(("%s [%2s] <== \"%s\""):format(m, m==v and 'OK' or '', k))
end |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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)
in
loop Z.zero n
in
let single_miller n r d =
(* (random (n - 4)) + 2 *)
let a = Bigint.to_zarith_bigint
Bigint.((random ((of_zarith_bigint n) - (of_int 4))) + (of_int 2))
in
let x = Z.(powm a d n) in
if Z.(equal x ~$1) || Z.(equal x (n - ~$1)) then true
else
let rec loop i x =
if Z.(equal ~$i (r - ~$1)) then false
else
let x = Z.(powm x ~$2 n) in
if Z.(equal x (n - ~$1)) then true
else loop (i + 1) x
in
loop 0 x
in
let n = Z.abs n in
if Z.(equal n one) then false
else if Z.(equal (logand n one) zero) then false
else if Z.(equal (n mod ~$3) zero) then false
else
let r, d = get_rd Z.(n - one) in
let rec loop i bool =
if i = k then bool
else loop (i + 1) (bool && single_miller n r d)
in
loop 0 true
|
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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
PrintN("M(N) is zero "+Str(z)+" times.") : PrintN("M(N) crosses zero "+Str(c)+" times.")
Input() |
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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
showMenu menu = unlines [show n ++ ") " ++ item | (n, item) <- zip [1..] menu]
choose :: [String] -> String -> Maybe String
choose menu choice = do
n <- maybeRead choice
guard $ n > 0
listToMaybe $ drop (n-1) menu
maybeRead :: Read a => String -> Maybe a
maybeRead = fmap fst . listToMaybe . filter (null . snd) . reads |
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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@Sin@i], {i, 1, 64}], h0 = 16^^67452301,
h1 = 16^^efcdab89, h2 = 16^^98badcfe, h3 = 16^^10325476,
data = Partition[
Join[FromDigits[Reverse@#, 256] & /@
Partition[
PadRight[Append[#, 128], Mod[56, 64, Length@# + 1]], 4],
Reverse@IntegerDigits[8 Length@#, 2^32, 2]] &@
ImportString[string, "Binary"], 16], a, b, c, d, f, g},
Do[{a, b, c, d} = {h0, h1, h2, h3};
Do[Which[1 <= i <= 16,
f = BitOr[BitAnd[b, c], BitAnd[BitNot[b], d]]; g = i - 1,
17 <= i <= 32, f = BitOr[BitAnd[d, b], BitAnd[BitNot[d], c]];
g = Mod[5 i - 4, 16], 33 <= i <= 48, f = BitXor[b, c, d];
g = Mod[3 i + 2, 16], 49 <= i <= 64,
f = BitXor[c, BitOr[b, BitNot[d] + 2^32]];
g = Mod[7 i - 7, 16]]; {a, b, c, d} = {d,
BitOr[BitShiftLeft[#1, #2], BitShiftRight[#1, 32 - #2]] &[
Mod[a + f + k[[i]] + w[[g + 1]], 2^32], r[[i]]] + b, b,
c}, {i, 1, 64}]; {h0, h1, h2, h3} =
Mod[{h0, h1, h2, h3} + {a, b, c, d}, 2^32], {w, data}];
"0x" ~~ IntegerString[
FromDigits[
Flatten[Reverse@IntegerDigits[#, 256, 4] & /@ {h0, h1, h2, h3}],
256], 16, 32]] |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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 :: IO ()
main = do
let xs =
[ 123
, 12345
, 1234567
, 987654321
, 10001
, -10001
, -123
, -100
, 100
, -12345
, 1
, 2
, -1
, -10
, 2002
, -2002
, 0
]
w = maximum $ (length . show) <$> xs
(putStrLn . unlines) $
(\n ->
justifyRight w ' ' (show n) ++
" -> " ++ either ((>>= id) . ("(" :) . (: [")"])) id (mid3 n)) <$>
xs
where
justifyRight :: Int -> Char -> String -> String
justifyRight n c s = drop (length s) (replicate n c ++ s) |
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #Oz | Oz |
%--------------------------------------------------------------------------%
% module: Primality
% file: Primality.oz
% version: 17 DEC 2014 @ 6:50AM
%--------------------------------------------------------------------------%
declare
%--------------------------------------------------------------------------%
fun {IsPrime N} % main interface of module
if N < 2 then false
elseif N < 4 then true
elseif (N mod 2) == 0 then false
elseif N < 341330071728321 then {IsMRprime N {DetWit N}}
else {IsMRprime N {ProbWit N 20}}
end
end
%--------------------------------------------------------------------------%
fun {DetWit N} % deterministic witnesses
if N < 1373653 then [2 3]
elseif N < 9080191 then [31 73]
elseif N < 25326001 then [2 3 5]
elseif N < 3215031751 then [2 3 5 7]
elseif N < 4759123141 then [2 7 61]
elseif N < 1122004669633 then [2 13 23 1662803]
elseif N < 2152302898747 then [2 3 5 7 11]
elseif N < 3474749660383 then [2 3 5 7 11 13]
elseif N < 341550071728321 then [2 3 5 7 11 13 17]
else nil
end
end
%--------------------------------------------------------------------------%
fun {ProbWit N K} % probabilistic witnesses
local A B C in
A = 6364136223846793005
B = 1442695040888963407
C = N - 2
{RWloop N A B C K nil}
end
end
fun {RWloop N A B C K L}
local N1 in
N1 = (((N * A) + B) mod C) + 1
if K == 0 then L
else {RWloop N1 A B C (K - 1) N1|L}
end
end
end
%--------------------------------------------------------------------------%
fun {IsMRprime N As} % the Miller-Rabin algorithm
local D S T Ts in
{FindDS N} = D|S
{OuterLoop N As D S}
end
end
fun {OuterLoop N As D S}
local A At Base C in
As = A|At
Base = {Powm A D N}
C = {InnerLoop Base N 0 S}
if {Not C} then false
elseif {And C (At == nil)} then true
else {OuterLoop N At D S}
end
end
end
fun {InnerLoop Base N Loop S}
local NextBase NextLoop in
NextBase = (Base * Base) mod N
NextLoop = Loop + 1
if {And (Loop == 0) (Base == 1)} then true
elseif Base == (N - 1) then true
elseif NextLoop == S then false
else {InnerLoop NextBase N NextLoop S}
end
end
end
%--------------------------------------------------------------------------%
fun {FindDS N}
{FindDS1 (N - 1) 0}
end
fun {FindDS1 D S}
if (D mod 2 == 0) then {FindDS1 (D div 2) (S + 1)}
else D|S
end
end
%--------------------------------------------------------------------------%
fun {Powm A D N} % returns (A ^ D) mod N
if D == 0 then 1
elseif (D mod 2) == 0 then {Pow {Powm A (D div 2) N} 2} mod N
else (A * {Powm A (D - 1) N}) mod N
end
end
%--------------------------------------------------------------------------%
% end_module Primality
|
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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]:
print("{:2d}".format(n), end=' ')
col += 1
if col == 10:
print()
col = 0
zeroes = sum(x==0 for x in ms)
crosses = sum(a!=0 and b==0 for a,b in zip(ms, ms[1:]))
print("M(N) equals zero {} times.".format(zeroes))
print("M(N) crosses zero {} times.".format(crosses)) |
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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(Messagebox, Name) answer, $$
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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: T): Digest;
PROCEDURE ToText(hash: Digest): TEXT;
END MD5. |
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;
char nameBuf[30];
Tcl_HashEntry *hPtr;
int size, dummy;
struct block *blockPtr;
/* Parse arguments */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "size");
return TCL_ERROR;
}
if (Tcl_GetIntFromObj(interp, objv[1], &size) != TCL_OK) {
return TCL_ERROR;
}
if (size < 1) {
Tcl_AppendResult(interp, "size must be positive", NULL);
return TCL_ERROR;
}
/* The ckalloc() function will panic on failure to allocate. */
blockPtr = (struct block *)
ckalloc(sizeof(struct block) + (unsigned) (size<4 ? 0 : size-4));
/* Set up block */
blockPtr->size = size;
memset(blockPtr->data, 0, blockPtr->size);
/* Give it a name and return the name */
sprintf(nameBuf, "block%d", nameCounter++);
hPtr = Tcl_CreateHashEntry(nameMap, nameBuf, &dummy);
Tcl_SetHashValue(hPtr, blockPtr);
Tcl_SetObjResult(interp, Tcl_NewStringObj(nameBuf, -1));
return TCL_OK;
}
static int
Memfree(
ClientData clientData,
Tcl_Interp *interp,
int objc, Tcl_Obj *const *objv)
{
Tcl_HashTable *nameMap = clientData;
Tcl_HashEntry *hPtr;
struct block *blockPtr;
/* Parse the arguments */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "handle");
return TCL_ERROR;
}
hPtr = Tcl_FindHashEntry(nameMap, Tcl_GetString(objv[1]));
if (hPtr == NULL) {
Tcl_AppendResult(interp, "unknown handle", NULL);
return TCL_ERROR;
}
blockPtr = Tcl_GetHashValue(hPtr);
/* Squelch the memory */
Tcl_DeleteHashEntry(hPtr);
ckfree((char *) blockPtr);
return TCL_OK;
}
static int
Memset(
ClientData clientData,
Tcl_Interp *interp,
int objc, Tcl_Obj *const *objv)
{
Tcl_HashTable *nameMap = clientData;
Tcl_HashEntry *hPtr;
struct block *blockPtr;
int index, byte;
/* Parse the arguments */
if (objc != 4) {
Tcl_WrongNumArgs(interp, 1, objv, "handle index byte");
return TCL_ERROR;
}
hPtr = Tcl_FindHashEntry(nameMap, Tcl_GetString(objv[1]));
if (hPtr == NULL) {
Tcl_AppendResult(interp, "unknown handle", NULL);
return TCL_ERROR;
}
blockPtr = Tcl_GetHashValue(hPtr);
if (Tcl_GetIntFromObj(interp, objv[2], &index) != TCL_OK
|| Tcl_GetIntFromObj(interp, objv[3], &byte) != TCL_OK) {
return TCL_ERROR;
}
if (index < 0 || index >= blockPtr->size) {
Tcl_AppendResult(interp, "index out of range", NULL);
return TCL_ERROR;
}
/* Update the byte of the data block */
blockPtr->data[index] = (unsigned char) byte;
return TCL_OK;
}
static int
Memget(
ClientData clientData,
Tcl_Interp *interp,
int objc, Tcl_Obj *const *objv)
{
Tcl_HashTable *nameMap = clientData;
Tcl_HashEntry *hPtr;
struct block *blockPtr;
int index, byte;
/* Parse the arguments */
if (objc != 3) {
Tcl_WrongNumArgs(interp, 1, objv, "handle index");
return TCL_ERROR;
}
hPtr = Tcl_FindHashEntry(nameMap, Tcl_GetString(objv[1]));
if (hPtr == NULL) {
Tcl_AppendResult(interp, "unknown handle", NULL);
return TCL_ERROR;
}
blockPtr = Tcl_GetHashValue(hPtr);
if (Tcl_GetIntFromObj(interp, objv[2], &index) != TCL_OK) {
return TCL_ERROR;
}
if (index < 0 || index >= blockPtr->size) {
Tcl_AppendResult(interp, "index out of range", NULL);
return TCL_ERROR;
}
/* Read the byte from the data block and return it */
Tcl_SetObjResult(interp, Tcl_NewIntObj(blockPtr->data[index]));
return TCL_OK;
}
static int
Memaddr(
ClientData clientData,
Tcl_Interp *interp,
int objc, Tcl_Obj *const *objv)
{
Tcl_HashTable *nameMap = clientData;
Tcl_HashEntry *hPtr;
struct block *blockPtr;
int addr;
/* Parse the arguments */
if (objc != 2) {
Tcl_WrongNumArgs(interp, 1, objv, "handle");
return TCL_ERROR;
}
hPtr = Tcl_FindHashEntry(nameMap, Tcl_GetString(objv[1]));
if (hPtr == NULL) {
Tcl_AppendResult(interp, "unknown handle", NULL);
return TCL_ERROR;
}
blockPtr = Tcl_GetHashValue(hPtr);
/* This next line is non-portable */
addr = (int) blockPtr->data;
Tcl_SetObjResult(interp, Tcl_NewIntObj(addr));
return TCL_OK;
}
int
Memalloc_Init(Tcl_Interp *interp)
{
/* Make the hash table */
Tcl_HashTable *hashPtr = (Tcl_HashTable *) ckalloc(sizeof(Tcl_HashTable));
Tcl_InitHashTable(hashPtr, TCL_STRING_KEYS);
/* Register the commands */
Tcl_CreateObjCommand(interp, "memalloc", Memalloc, hashPtr, NULL);
Tcl_CreateObjCommand(interp, "memfree", Memfree, hashPtr, NULL);
Tcl_CreateObjCommand(interp, "memset", Memset, hashPtr, NULL);
Tcl_CreateObjCommand(interp, "memget", Memget, hashPtr, NULL);
Tcl_CreateObjCommand(interp, "memaddr", Memaddr, hashPtr, NULL);
/* Register the package */
return Tcl_PkgProvide(interp, "memalloc", "1.0");
} |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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[^200]».fmt('%3s').batch(20).join("\n"),
"\n\nEquals zero ", +@mertens[1..1000].grep( !* ),
' times between 1 and 1000', "\n\nCrosses zero ",
+@mertens[1..1000].kv.grep( {!$^v and @mertens[$^k]} ),
" times between 1 and 1000\n\nFirst Mertens equal to:";
for 10, 20, 30 … 100 -> $threshold {
printf "%4d: M(%d)\n", -$threshold, @mertens.first: * == -$threshold, :k;
printf "%4d: M(%d)\n", $threshold, @mertens.first: * == $threshold, :k;
} |
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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("Returned value =", choice)
choice := choose_from_menu(K) # call using menu K
write("Returned value =", choice)
choice := choose_from_menu(Z) # call using empty list
write("Returned value =", choice)
end ## of main
# --------- subroutines below ---------------------------------
procedure choose_from_menu(X)
displaymenu(X)
repeat {
writes("Choose a number from the menu above: ")
a := read()
if a == "" then return(a) ## no selection
write("You selected ",a)
if numeric(a) then {
if integer(a) <= 0 | integer(a) > *X then displaymenu(X) else
{ ## check entered option in range
write(a, " ==> ",X[a])
return ( string(a))
}
}
else displaymenu(X)
}
end ## choose_from_menu(X)
procedure displaymenu(X)
every i := 1 to *X do
write(i,") ",X[i]) ## dispay menu options
end ## displaymenu(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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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: T): Digest;
PROCEDURE ToText(hash: Digest): TEXT;
END MD5. |
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 // make eligible for GC |
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
Allocate:
push rdi ; save the size argument
cmp qword [break], 0 ; if breakpoint is zero this
je firstAlloc ; is the first call to allocate
mov rdi, qword [hStart] ; else address of heap start
findBlock: ; look for a suitable block of memory
cmp byte [rdi + free], 2
je newBlock ; end of heap reached, create new block
cmp byte [rdi + free], 0
je skipBlock ; this block taken
; this block is free, make
; sure it's big enough
mov bx, word [rdi + size]
mov rcx, qword [rsp] ; compare against our size arg
cmp cx, bx
jg skipBlock ; keep looking if not big enough
mov byte [rdi + free], 0 ; else mark as taken
add rdi, mem
add rsp, 8 ; discard size arg, we didn't need it
mov rax, rdi ; return pointer to this block
ret
skipBlock:
mov rsi, qword [rdi + next] ; load next
mov rdi, rsi ' block address
jmp findBlock
newBlock:
mov rax, rdi
add rdi, 1024
cmp rdi, qword [break]
jl initAndAllocate
push rax
mov rdi, qword [break] ; if we are getting low on
add rdi, 4096 ; heap space, we ask OS for
mov rax, 12 ; more memory with brk syscall
syscall
cmp rax, qword [break] ; if breakpoint has not increased,
je allocFail ; then memory could not be allocated
mov qword [break], rax
pop rax
jmp initAndAllocate
firstAlloc: ; extra work has to be done on first
mov rax, 12 ; call to this subroutine
mov rdi, 0
syscall
mov qword [hStart], rax ; init heap start
add rax, 4096
mov rdi, rax
mov rax, 12 ; get heap memory with sys brk
syscall
cmp rax, qword [hStart]
je allocFail
mov qword [break], rax
mov rax, qword [hStart]
initAndAllocate:
mov byte [rax + free], 0 ; mark block free
pop rdi ; pop size arg off stack
mov word [rax + size], di ; mark it's size
lea rsi, [rax + mem + rdi]
mov byte [rsi + free], 2 ; mark heap end block
mov qword [rax + next], rsi ; mark next block
add rax, mem ; return pointer to block's memory space
ret
allocFail: ; exit(1) when allocation fails
mov rax, 60
mov rdi, 1
syscall
ret
; free this block so it can be
; reused in a subsequent call to allocate
Release:
sub rdi, mem
mov byte [rdi + free], 1
ret
|
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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->bmodpow($d, $n);
next if $x == 1 or $x == $n - 1;
for (1 .. $s - 1) {
$x = ($x * $x) % $n;
return 0 if $x == 1;
next LOOP if $x == $n - 1;
}
return 0;
}
return 1;
}
print join ", ", grep { is_prime $_, 10 } (1 .. 1000); |
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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 /* " " " " " " */
if grp=='' | grp=="," then grp= 20 /* " " " " " " */
if eqZ=='' | eqZ=="," then eqZ= 1000 /* " " " " " " */
if xZ=='' | xZ=="," then xZ= 1000 /* " " " " " " */
call genP /*generate primes up to max √ HIHI */
call Franz LO, HI
if eqZ>0 then call Franz 1, -eqZ
if xZ>0 then call Franz -1, xZ
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
Franz: parse arg a 1 oa,b 1 ob; @Mertens= ' The Mertens sequence from '
a= abs(a); b= abs(b); grid= oa>=0 & ob>=0 /*semaphore used to show a grid title. */
if grid then say center(@Mertens LO " ──► " HI" ", max(50, grp*3), '═') /*show title*/
else say
zeros= 0 /*# of 0's found for Mertens function.*/
Xzero= 0 /*number of times that zero was crossed*/
$=; prev= /*$ holds output grid of GRP numbers. */
do j=a to b; _= Mertens(j) /*process some numbers from LO ──► HI.*/
if _==0 then zeros= zeros + 1 /*Is Zero? Then bump the zeros counter*/
if _==0 then if prev\==0 then Xzero= Xzero+1 /*prev ¬=0? " " " Xzero " */
prev= _
if grid then $= $ right(_, 2) /*build grid if A & B are non─negative.*/
if words($)==grp then do; say substr($, 2); $= /*show grid if fully populated, */
end /* and nullify it for more #s. */
end /*j*/ /*for small grids, using wordCnt is OK.*/
if $\=='' then say substr($, 2) /*handle any residual numbers not shown*/
if oa<0 then say @Mertens a " to " b ' has crossed zero ' Xzero " times."
if ob<0 then say @Mertens a " to " b ' has ' zeros " zeros."
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Mertens: procedure expose @. !!. M.; parse arg n; if M.n\==. then return M.n
if n<1 then return '∙'; m= 0 /*handle special cases of non─positive#*/
do k=1 for n; m= m + mobius(k) /*sum the MU's up to N. */
end /*k*/ /* [↑] mobius function uses memoization*/
M.n= m; return m /*return the sum of all the MU's. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
mobius: procedure expose @. !!.; parse arg x 1 ox /*get integer to be tested for mu */
if !!.x\==. then return !!.x /*X computed before? Return that value*/
if x<1 then return '∙'; mu= 0 /*handle special case of non-positive #*/
do k=1; p= @.k; if p>x then leave /* (P) > X? Then we're done.*/
if p*p>x then do; mu= mu+1; leave; end /* (P**2) > X? Bump # and leave*/
if x//p==0 then do; mu= mu+1 /*X divisible by P? Bump mu number.*/
x= x % p /* Divide by prime. */
if x//p==0 then return 0 /*X÷by P? Then return zero*/
end
end /*k*/ /*MU (below) is almost always small, <9*/
!!.ox= -1 ** mu; return !!.ox /*raise -1 to the mu power, memoize it.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
genP: @.1=2; @.2=3; @.3=5; @.4=7; @.5=11; @.6=13 /*initialize some low primes; # primes.*/
!!.=.; M.=!!.; #= 6; sq.#= @.6**2 /* " 2 arrays for memoization. */
do j=@.#+4 by 2 to max(HI, eqZ, xZ); parse var j '' -1 _ /*odd Ps from now on*/
if _==5 then iterate; if j//3==0 then iterate; if j//7==0 then iterate /*÷ 5 3 7*/
do k=7 while sq.k<=j /*divide by some generated odd primes. */
if j//@.k==0 then iterate j /*Is J divisible by P? Then not prime*/
end /*k*/ /* [↓] a prime (J) has been found. */
#= #+1; @.#=j; sq.j= j*j /*bump P count; P──►@.; compute J**2*/
end /*j*/; return /*calculate the squares of some primes.*/ |
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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
whilst. RESULT -.@:e. i. # CHOICES do.
showMenu CHOICES
smoutput PROMPT
RESULT =. _1 ". read_stdin''
end.
RESULT {:: CHOICES
)
|
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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[dstIndex] = chunk[dstIndex] or (msg[srcIndex].uint32 shl 24)
srcIndex.inc
proc leftRotate(val: uint32, shift: int) : uint32 =
result = (val shl shift) or (val shr (32 - shift))
proc md5Sum(msg : seq[uint8]) : array[SumSize, uint8] =
const
s : array[ChunkSize, int] =
[ 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 : array[ChunkSize, uint32] =
[ 0xd76aa478'u32, 0xe8c7b756'u32, 0x242070db'u32, 0xc1bdceee'u32,
0xf57c0faf'u32, 0x4787c62a'u32, 0xa8304613'u32, 0xfd469501'u32,
0x698098d8'u32, 0x8b44f7af'u32, 0xffff5bb1'u32, 0x895cd7be'u32,
0x6b901122'u32, 0xfd987193'u32, 0xa679438e'u32, 0x49b40821'u32,
0xf61e2562'u32, 0xc040b340'u32, 0x265e5a51'u32, 0xe9b6c7aa'u32,
0xd62f105d'u32, 0x02441453'u32, 0xd8a1e681'u32, 0xe7d3fbc8'u32,
0x21e1cde6'u32, 0xc33707d6'u32, 0xf4d50d87'u32, 0x455a14ed'u32,
0xa9e3e905'u32, 0xfcefa3f8'u32, 0x676f02d9'u32, 0x8d2a4c8a'u32,
0xfffa3942'u32, 0x8771f681'u32, 0x6d9d6122'u32, 0xfde5380c'u32,
0xa4beea44'u32, 0x4bdecfa9'u32, 0xf6bb4b60'u32, 0xbebfbc70'u32,
0x289b7ec6'u32, 0xeaa127fa'u32, 0xd4ef3085'u32, 0x04881d05'u32,
0xd9d4d039'u32, 0xe6db99e5'u32, 0x1fa27cf8'u32, 0xc4ac5665'u32,
0xf4292244'u32, 0x432aff97'u32, 0xab9423a7'u32, 0xfc93a039'u32,
0x655b59c3'u32, 0x8f0ccc92'u32, 0xffeff47d'u32, 0x85845dd1'u32,
0x6fa87e4f'u32, 0xfe2ce6e0'u32, 0xa3014314'u32, 0x4e0811a1'u32,
0xf7537e82'u32, 0xbd3af235'u32, 0x2ad7d2bb'u32, 0xeb86d391'u32 ]
# Pad with 1-bit, and fill with 0's up to 448 bits mod 512
var paddedMsgSize = msg.len + 1
var remain = (msg.len + 1) mod ChunkSize
if remain > (448 div 8):
paddedMsgSize += ChunkSize - remain + (448 div 8)
else:
paddedMsgSize += (448 div 8) - remain
var paddingSize = paddedMsgSize - msg.len
var padding = newSeq[uint8](paddingSize)
padding[0] = 0x80
# Pad with number of *bits* in original message, little-endian
var sizePadding = newSeq[uint8](8)
var size = msg.len * 8
for ii in 0 ..< 4:
sizePadding[ii] = uint8(size and 0xff)
size = size shr 8
var paddedMsg = concat(msg, padding, sizePadding)
var accum = [ 0x67452301'u32, 0xefcdab89'u32, 0x98badcfe'u32, 0x10325476'u32 ]
for offset in countup(0, paddedMsg.len - 1, ChunkSize):
var A = accum[0]
var B = accum[1]
var C = accum[2]
var D = accum[3]
var F : uint32
var g : int
var M : array[16, uint32]
var dTemp : uint32
extractChunk(paddedMsg, M, offset)
# This is pretty much the same as Wikipedia's MD5 entry
for ii in 0 .. 63:
if ii <= 15:
F = (B and C) or ((not B) and D)
g = ii
elif ii <= 31:
F = (D and B) or ((not D) and C)
g = (5 * ii + 1) mod 16
elif ii <= 47:
F = B xor C xor D
g = (3 * ii + 5) mod 16
else:
F = C xor (B or (not D))
g = (7 * ii) mod 16
dTemp = D
D = C
C = B
B = B + leftRotate((A + F + K[ii] + M[g]), s[ii])
A = dTemp
accum[0] += A
accum[1] += B
accum[2] += C
accum[3] += D
# Convert four 32-bit accumulators to 16 byte array, little-endian
var dstIdx : int
for acc in accum:
var tmp = acc
for ii in 0 ..< 4:
result[dstIdx] = uint8(tmp and 0xff)
tmp = tmp shr 8
dstIdx.inc
# Only needed to convert from string to uint8 sequence
iterator items * (str : string) : uint8 =
for ii in 0 ..< len(str):
yield str[ii].uint8
proc main =
var msg = ""
var sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0xD4'u8, 0x1D, 0x8C, 0xD9, 0x8F, 0x00, 0xB2, 0x04,
0xE9, 0x80, 0x09, 0x98, 0xEC, 0xF8, 0x42, 0x7E ] )
msg = "The quick brown fox jumps over the lazy dog"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x9E'u8, 0x10, 0x7D, 0x9D, 0x37, 0x2B, 0xB6, 0x82,
0x6B, 0xD8, 0x1D, 0x35, 0x42, 0xA4, 0x19, 0xD6 ] )
msg = "The quick brown fox jumps over the lazy dog."
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0xE4'u8, 0xD9, 0x09, 0xC2, 0x90, 0xD0, 0xFB, 0x1C,
0xA0, 0x68, 0xFF, 0xAD, 0xDF, 0x22, 0xCB, 0xD0 ])
# Message size around magic 512 bits
msg = "01234567890123456789012345678901234567890123456789012345678901234"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0xBE'u8, 0xB9, 0xF4, 0x8B, 0xC8, 0x02, 0xCA, 0x5C,
0xA0, 0x43, 0xBC, 0xC1, 0x5E, 0x21, 0x9A, 0x5A ])
msg = "0123456789012345678901234567890123456789012345678901234567890123"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x7F'u8, 0x7B, 0xFD, 0x34, 0x87, 0x09, 0xDE, 0xEA,
0xAC, 0xE1, 0x9E, 0x3F, 0x53, 0x5F, 0x8C, 0x54 ])
msg = "012345678901234567890123456789012345678901234567890123456789012"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0xC5'u8, 0xE2, 0x56, 0x43, 0x7E, 0x75, 0x80, 0x92,
0xDB, 0xFE, 0x06, 0x28, 0x3E, 0x48, 0x90, 0x19 ])
# Message size around magic 448 bits
msg = "01234567890123456789012345678901234567890123456789012345"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x8A'u8, 0xF2, 0x70, 0xB2, 0x84, 0x76, 0x10, 0xE7,
0x42, 0xB0, 0x79, 0x1B, 0x53, 0x64, 0x8C, 0x09 ])
msg = "0123456789012345678901234567890123456789012345678901234"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x6E'u8, 0x7A, 0x4F, 0xC9, 0x2E, 0xB1, 0xC3, 0xF6,
0xE6, 0x52, 0x42, 0x5B, 0xCC, 0x8D, 0x44, 0xB5 ])
msg = "012345678901234567890123456789012345678901234567890123"
sum = md5Sum(toSeq(msg.items()))
assert(sum == [ 0x3D'u8, 0xFF, 0x83, 0xC8, 0xFA, 0xDD, 0x26, 0x37,
0x0D, 0x5B, 0x09, 0x84, 0x09, 0x64, 0x44, 0x57 ])
main() |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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,
Integer.MAX_VALUE};
for (long n : passing)
System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
for (int n : failing)
System.out.printf("middleThreeDigits(%s): %s\n", n, middleThreeDigits(n));
}
public static <T> String middleThreeDigits(T n) {
String s = String.valueOf(n);
if (s.charAt(0) == '-')
s = s.substring(1);
int len = s.length();
if (len < 3 || len % 2 == 0)
return "Need odd and >= 3 digits";
int mid = len / 2;
return s.substring(mid - 1, mid + 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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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, atom s, atom d, sequence a)
-- n-1 = 2^s * d with d odd by factoring powers of 2 from n-1
for i=1 to length(a) do
atom x = powermod(a[i], d, n), y, w=s
while w do
y = mod(x*x,n)
if y == 1 and x != 1 and x != n-1 then
return false
end if
x = y
w -= 1
end while
if y != 1 then
return false
end if
end for
return true;
end function
function is_prime_mr(atom n)
if (mod(n,2)==0 and n!=2)
or (n<2)
or (mod(n,3)==0 and n!=3) then
return false
elsif n<=3 then
return true
end if
atom d = floor(n/2)
atom s = 1;
while and_bits(d,1)=0 do
d /= 2
s += 1
end while
sequence a
if n < 1373653 then
a = {2, 3}
elsif n < 9080191 then
a = {31, 73}
elsif (machine_bits()=32 and n < 94910107)
or (machine_bits()=64 and n < 4295041217) then
a = {2, 7, 61}
else
puts(1,"limits exceeded\n")
return 0
end if
return witness(n, s, d, a)
end function
sequence tests = {999983,999809,999727,52633,60787,999999,999995,999991}
for i=1 to length(tests) do
printf(1,"%d is %s\n",{tests[i],{"composite","prime"}[is_prime_mr(tests[i])+1]})
end for
|
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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 function is zero #{ar.count(0)} times in the range (1..1000);"
puts "it crosses zero #{ar.each_cons(2).count{|m1, m2| m1 != 0 && m2 == 0}} times."
|
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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 index = sc.nextInt();
if(index >= 0 && index < list.size()){
ret = list.get(index);
}
}while(ret == null);
return 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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #ooRexx | ooRexx |
#!/usr/bin/rexx
/* Expected results:
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
*/
md5 = .md5~new; md5~update(""); say md5~digest
md5 = .md5~new; md5~update("a"); say md5~digest
md5 = .md5~new; md5~update("abc"); say md5~digest
md5 = .md5~new; md5~update("message digest"); say md5~digest
md5 = .md5~new("abcdefghijklmnopqrstuvwxyz"); say md5~digest
md5 = .md5~new("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); md5~update("abcdefghijklmnopqrstuvwxyz0123456789"); say md5~digest
md5 = .md5~new; md5~update("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); say md5~digest
-- requires OORexx 4.2.0 or later
-- standard numeric digits of 9 is not enough in this case
::options digits 20
-- Implementation mainly based on pseudocode in https://en.wikipedia.org/wiki/MD5
::class md5 public
::method init
expose a0 b0 c0 d0 count buffer index K. s -- instance variables
use strict arg chunk=""
-- Initialize message digest
a0 = .int32~new('67452301'x,"C") -- A
b0 = .int32~new('efcdab89'x,"C") -- B
c0 = .int32~new('98badcfe'x,"C") -- C
d0 = .int32~new('10325476'x,"C") -- D
-- The 512 bit chunk buffer
buffer = .mutablebuffer~new('00'x~copies(64),64)
-- The position in the buffer to insert new input
index = 1
-- message bytecount
count = 0
-- initialize leftrotate amounts
nrs = .array~of(7,12,17,22)
s = nrs~union(nrs)~union(nrs)~union(nrs)
nrs = .array~of(5,9,14,20)
s = s~union(nrs)~union(nrs)~union(nrs)~union(nrs)
nrs = .array~of(4,11,16,23)
s = s~union(nrs)~union(nrs)~union(nrs)~union(nrs)
nrs = .array~of(6,10,15,21)
s = s~union(nrs)~union(nrs)~union(nrs)~union(nrs)
-- initialize sinus derived constants.
-- sin function from RXMath Library shipped with OORexx
-- see ::routine directive at the end of the code
do i=0 to 63
K.i = .int32~new(((2**32)*(sin(i+1,16,R)~abs))~floor)
end
-- process initial string if any
self~update(chunk)
exit
::method update
expose a0 b0 c0 d0 count buffer index K. s -- instance variables
use strict arg chunk
count += chunk~length
if chunk~length<65-index then do
buffer~overlay(chunk,index)
index += chunk~length
end
else do
split = 65-index+1
parse var chunk part =(split) chunk
buffer~overlay(part,index)
index = 65
end
-- Only proces completely filled buffer
do while index=65
A = a0
B = b0
C = c0
D = d0
do i=0 to 63
select
when i<16 then do
F = D~xor(B~and(C~xor(D)))
g = i
end
when i<32 then do
F = C~xor(D~and(B~xor(C)))
g = (5*i+1)//16
end
when i<48 then do
F = B~xor(C)~xor(D)
g = (3*i+5)//16
end
otherwise do
F = C~xor(B~or(D~xor(.int32~new('ffffffff'x,"C"))))
g = (7*i)//16
end
end
M = .int32~new(buffer~substr(g*4+1,4)~reverse,"C") -- 32bit word in little-endian
dTemp = D
D = C
C = B
B = (B + (A+F+K.i+M)~bitrotate(s[i+1]))
A = dTemp
end
a0 = a0+A
b0 = b0+B
c0 = c0+C
d0 = d0+D
parse var chunk part 65 chunk
index = part~length+1
buffer~overlay(part,1,part~length)
end
exit
::method digest
expose a0 b0 c0 d0 count buffer index K s -- instance variables
padlen = 64
if index<57 then padlen = 57-index
if index>57 then padlen = 121-index
padding = '00'x~copies(padlen)~bitor('80'x)
bitcount = count*8//2**64
lowword = bitcount//2**32
hiword = bitcount%2**32
lowcount = lowword~d2c(4)~reverse -- make it little-endian
hicount = hiword~d2c(4)~reverse -- make it little-endian
self~update(padding || lowcount || hicount)
return a0~string || b0~string || c0~string || d0~string
-- A convenience class to encapsulate operations on non OORexx-like
-- things as little-endian 32-bit words
::class int32 public
::attribute arch class
::method init class
self~arch = "little-endian" -- can be adapted for multiple architectures
-- Method to create an int32 like object
-- Input can be a OORexx whole number (type="I") or
-- a character string of 4 bytes (type="C")
-- input truncated or padded to 32-bit word/string
::method init
expose char4 int32
use strict arg input, type="Integer"
-- type must be one of "I"nteger or "C"haracter
t = type~subchar(1)~upper
select
when t=='I' then do
char4 = input~d2c(4)
int32 = char4~c2d
end
when t=='C' then do
char4 = input~right(4,'00'x)
int32 = char4~c2d
end
otherwise do
raise syntax 93.915 array("IC",type)
end
end
exit
::method xor -- wrapper for OORexx bitxor method
expose char4
use strict arg other
return .int32~new(char4~bitxor(other~char),"C")
::method and -- wrapper for OORexx bitand method
expose char4
use strict arg other
return .int32~new(char4~bitand(other~char),"C")
::method or -- wrapper for OORexx bitor method
expose char4
use strict arg other
return .int32~new(char4~bitor(other~char),"C")
::method bitleft -- OORexx shift (<<) implementation
expose char4
use strict arg bits
bstring = char4~c2x~x2b
bstring = bstring~substr(bits+1)~left(bstring~length,'0')
return .int32~new(bstring~b2x~x2d)
::method bitright -- OORexx shift (>>) implementation
expose char4
use strict arg bits, signed=.false
bstring = char4~c2x~x2b
fill = '0'
if signed then fill = bstring~subchar(1)
bstring = bstring~left(bstring~length-bits)~right(bstring~length,fill)
return .int32~new(bstring~b2x~x2d)
::method bitnot -- OORexx not implementation
expose char4
return .int32~new(char4~bitxor('ffffffff'x)~c2d,"C")
::method bitrotate -- OORexx (left) rotate method
expose char4
use strict arg bits, direction='left'
d = direction~subchar(1)~upper
if d=='L' then do
leftpart = self~bitleft(bits)
rightpart = self~bitright(32-bits)
end
else do
leftpart = self~bitleft(32-bits)
rightpart = self~bitright(bits)
end
return rightpart~or(leftpart)
::method int -- retrieve integer as number
expose int32
return int32
::method char -- retrieve integer as characters
expose char4
return char4
::method '+' -- OORexx method to add 2 .int32 instances
expose int32
use strict arg other
return .int32~new(int32+other~int)
::method string -- retrieve integer as hexadecimal string
expose char4
return char4~reverse~c2x~lower
-- Simplify function names for the necessary 'RxMath' functions
::routine sin EXTERNAL "LIBRARY rxmath RxCalcSin"
|
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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(n))}catch(e){console.error(e.message)}
}); |
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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);
if ($x == 1 || $x == $n-1)
continue;
for ($j = 1; $j < $s; $j++) {
$x = bcmod(bcmul($x, $x), $n);
if ($x == 1)
return false;
if ($x == $n-1)
continue 2;
}
return false;
}
return true;
}
for ($i = 1; $i <= 1000; $i++)
if (is_prime($i, 10))
echo "$i, ";
echo "\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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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 columns = 20
print("First \(count - 1) Mertens numbers:")
for i in 0..<count {
if i % columns > 0 {
print(" ", terminator: "")
}
print(i == 0 ? " " : String(format: "%2d", mertens[i]), terminator: "")
if (i + 1) % columns == 0 {
print()
}
}
var zero = 0, cross = 0, previous = 0
for i in 1...max {
let m = mertens[i]
if m == 0 {
zero += 1
if previous != 0 {
cross += 1
}
}
previous = m
}
print("M(n) is zero \(zero) times for 1 <= n <= \(max).")
print("M(n) crosses zero \(cross) times for 1 <= n <= \(max).") |
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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 > choices.length) {
inputChoice = await getSelection(`\n${prompt}${question}: `);
}
return choices[inputChoice - 1];
}
function getSelection(prompt) {
return new Promise((resolve) => {
const lr = readline.createInterface({
input: process.stdin,
output: process.stdout
});
lr.question(prompt, (response) => {
lr.close();
resolve(parseInt(response) || -1);
});
});
}
const choices = ['fee fie', 'huff and puff', 'mirror mirror', 'tick tock'];
const question = 'Which is from the three pigs?';
menuSelect(question, choices).then((answer) => {
console.log(`\nYou chose ${answer}`);
}); |
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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?56:120)-$l%64);
$l = ($l-1)*8;
$msg .= pack 'VV', $l & MAX , ($l >> 16 >> 16);
}
sub rotate_left($$) {
($_[0] << $_[1]) | (( $_[0] >> (32 - $_[1]) ) & ((1 << $_[1]) - 1));
}
sub gen_code {
# Discard upper 32 bits on 64 bit archs.
my $MSK = ((1 << 16) << 16) ? ' & ' . MAX : '';
my %f = (
FF => "X0=rotate_left((X3^(X1&(X2^X3)))+X0+X4+X6$MSK,X5)+X1$MSK;",
GG => "X0=rotate_left((X2^(X3&(X1^X2)))+X0+X4+X6$MSK,X5)+X1$MSK;",
HH => "X0=rotate_left((X1^X2^X3)+X0+X4+X6$MSK,X5)+X1$MSK;",
II => "X0=rotate_left((X2^(X1|(~X3)))+X0+X4+X6$MSK,X5)+X1$MSK;",
);
my %s = ( # shift lengths
S11 => 7, S12 => 12, S13 => 17, S14 => 22, S21 => 5, S22 => 9, S23 => 14,
S24 => 20, S31 => 4, S32 => 11, S33 => 16, S34 => 23, S41 => 6, S42 => 10,
S43 => 15, S44 => 21
);
my $insert = "\n";
while(defined( my $data = <DATA> )) {
chomp $data;
next unless $data =~ /^[FGHI]/;
my ($func,@x) = split /,/, $data;
my $c = $f{$func};
$c =~ s/X(\d)/$x[$1]/g;
$c =~ s/(S\d{2})/$s{$1}/;
$c =~ s/^(.*)=rotate_left\((.*),(.*)\)\+(.*)$//;
my $su = 32 - $3;
my $sh = (1 << $3) - 1;
$c = "$1=(((\$r=$2)<<$3)|((\$r>>$su)&$sh))+$4";
$insert .= "\t$c\n";
}
close DATA;
my $dump = '
sub round {
my ($a,$b,$c,$d) = @_[0 .. 3];
my $r;' . $insert . '
$_[0]+$a' . $MSK . ', $_[1]+$b ' . $MSK .
', $_[2]+$c' . $MSK . ', $_[3]+$d' . $MSK . ';
}';
eval $dump;
}
gen_code();
sub _encode_hex { unpack 'H*', $_[0] }
sub md5 {
my $message = padding(join'',@_);
my ($a,$b,$c,$d) = (A,B,C,D);
my $i;
for $i (0 .. (length $message)/64-1) {
my @X = unpack 'V16', substr $message,$i*64,64;
($a,$b,$c,$d) = round($a,$b,$c,$d,@X);
}
pack 'V4',$a,$b,$c,$d;
}
my $strings = {
'd41d8cd98f00b204e9800998ecf8427e' => '',
'0cc175b9c0f1b6a831c399e269772661' => 'a',
'900150983cd24fb0d6963f7d28e17f72' => 'abc',
'f96b697d7cb7938d525a2f31aaf161d0' => 'message digest',
'c3fcd3d76192e4007dfb496cca67e13b' => 'abcdefghijklmnopqrstuvwxyz',
'd174ab98d277d9f5a5611c2c9f419d9f' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
'57edf4a22be3c955ac49da2e2107b67a' => '12345678901234567890123456789012345678901234567890123456789012345678901234567890',
};
for my $k (keys %$strings) {
my $digest = _encode_hex md5($strings->{$k});
is($digest, $k, "$digest is MD5 digest $strings->{$k}");
}
__DATA__
FF,$a,$b,$c,$d,$_[4],7,0xd76aa478,/* 1 */
FF,$d,$a,$b,$c,$_[5],12,0xe8c7b756,/* 2 */
FF,$c,$d,$a,$b,$_[6],17,0x242070db,/* 3 */
FF,$b,$c,$d,$a,$_[7],22,0xc1bdceee,/* 4 */
FF,$a,$b,$c,$d,$_[8],7,0xf57c0faf,/* 5 */
FF,$d,$a,$b,$c,$_[9],12,0x4787c62a,/* 6 */
FF,$c,$d,$a,$b,$_[10],17,0xa8304613,/* 7 */
FF,$b,$c,$d,$a,$_[11],22,0xfd469501,/* 8 */
FF,$a,$b,$c,$d,$_[12],7,0x698098d8,/* 9 */
FF,$d,$a,$b,$c,$_[13],12,0x8b44f7af,/* 10 */
FF,$c,$d,$a,$b,$_[14],17,0xffff5bb1,/* 11 */
FF,$b,$c,$d,$a,$_[15],22,0x895cd7be,/* 12 */
FF,$a,$b,$c,$d,$_[16],7,0x6b901122,/* 13 */
FF,$d,$a,$b,$c,$_[17],12,0xfd987193,/* 14 */
FF,$c,$d,$a,$b,$_[18],17,0xa679438e,/* 15 */
FF,$b,$c,$d,$a,$_[19],22,0x49b40821,/* 16 */
GG,$a,$b,$c,$d,$_[5],5,0xf61e2562,/* 17 */
GG,$d,$a,$b,$c,$_[10],9,0xc040b340,/* 18 */
GG,$c,$d,$a,$b,$_[15],14,0x265e5a51,/* 19 */
GG,$b,$c,$d,$a,$_[4],20,0xe9b6c7aa,/* 20 */
GG,$a,$b,$c,$d,$_[9],5,0xd62f105d,/* 21 */
GG,$d,$a,$b,$c,$_[14],9,0x2441453,/* 22 */
GG,$c,$d,$a,$b,$_[19],14,0xd8a1e681,/* 23 */
GG,$b,$c,$d,$a,$_[8],20,0xe7d3fbc8,/* 24 */
GG,$a,$b,$c,$d,$_[13],5,0x21e1cde6,/* 25 */
GG,$d,$a,$b,$c,$_[18],9,0xc33707d6,/* 26 */
GG,$c,$d,$a,$b,$_[7],14,0xf4d50d87,/* 27 */
GG,$b,$c,$d,$a,$_[12],20,0x455a14ed,/* 28 */
GG,$a,$b,$c,$d,$_[17],5,0xa9e3e905,/* 29 */
GG,$d,$a,$b,$c,$_[6],9,0xfcefa3f8,/* 30 */
GG,$c,$d,$a,$b,$_[11],14,0x676f02d9,/* 31 */
GG,$b,$c,$d,$a,$_[16],20,0x8d2a4c8a,/* 32 */
HH,$a,$b,$c,$d,$_[9],4,0xfffa3942,/* 33 */
HH,$d,$a,$b,$c,$_[12],11,0x8771f681,/* 34 */
HH,$c,$d,$a,$b,$_[15],16,0x6d9d6122,/* 35 */
HH,$b,$c,$d,$a,$_[18],23,0xfde5380c,/* 36 */
HH,$a,$b,$c,$d,$_[5],4,0xa4beea44,/* 37 */
HH,$d,$a,$b,$c,$_[8],11,0x4bdecfa9,/* 38 */
HH,$c,$d,$a,$b,$_[11],16,0xf6bb4b60,/* 39 */
HH,$b,$c,$d,$a,$_[14],23,0xbebfbc70,/* 40 */
HH,$a,$b,$c,$d,$_[17],4,0x289b7ec6,/* 41 */
HH,$d,$a,$b,$c,$_[4],11,0xeaa127fa,/* 42 */
HH,$c,$d,$a,$b,$_[7],16,0xd4ef3085,/* 43 */
HH,$b,$c,$d,$a,$_[10],23,0x4881d05,/* 44 */
HH,$a,$b,$c,$d,$_[13],4,0xd9d4d039,/* 45 */
HH,$d,$a,$b,$c,$_[16],11,0xe6db99e5,/* 46 */
HH,$c,$d,$a,$b,$_[19],16,0x1fa27cf8,/* 47 */
HH,$b,$c,$d,$a,$_[6],23,0xc4ac5665,/* 48 */
II,$a,$b,$c,$d,$_[4],6,0xf4292244,/* 49 */
II,$d,$a,$b,$c,$_[11],10,0x432aff97,/* 50 */
II,$c,$d,$a,$b,$_[18],15,0xab9423a7,/* 51 */
II,$b,$c,$d,$a,$_[9],21,0xfc93a039,/* 52 */
II,$a,$b,$c,$d,$_[16],6,0x655b59c3,/* 53 */
II,$d,$a,$b,$c,$_[7],10,0x8f0ccc92,/* 54 */
II,$c,$d,$a,$b,$_[14],15,0xffeff47d,/* 55 */
II,$b,$c,$d,$a,$_[5],21,0x85845dd1,/* 56 */
II,$a,$b,$c,$d,$_[12],6,0x6fa87e4f,/* 57 */
II,$d,$a,$b,$c,$_[19],10,0xfe2ce6e0,/* 58 */
II,$c,$d,$a,$b,$_[10],15,0xa3014314,/* 59 */
II,$b,$c,$d,$a,$_[17],21,0x4e0811a1,/* 60 */
II,$a,$b,$c,$d,$_[8],6,0xf7537e82,/* 61 */
II,$d,$a,$b,$c,$_[15],10,0xbd3af235,/* 62 */
II,$c,$d,$a,$b,$_[6],15,0x2ad7d2bb,/* 63 */
II,$b,$c,$d,$a,$_[13],21,0xeb86d391,/* 64 */ |
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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)
| "\(.) => \( .|middle3 )" |
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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 (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) )
(de _prim? (N D S)
(use (A X R)
(while (> 2 (setq A (longRand N))))
(setq R 0 X (**Mod A D N))
(loop
(T
(or
(and (=0 R) (= 1 X))
(= X (dec N)) )
T )
(T
(or
(and (> R 0) (= 1 X))
(>= (inc 'R) S) )
NIL )
(setq X (% (* X X) N)) ) ) )
(de prime? (N K)
(default K 50)
(and
(> N 1)
(bit? 1 N)
(let (D (dec N) S 0)
(until (bit? 1 D)
(setq
D (>> 1 D)
S (inc S) ) )
(do K
(NIL (_prim? N D S))
T ) ) ) ) |
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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 := false // true if there is a square prime factor
for p in primes {
if p > j {
break
}
if j%p == 0 {
j /= p
cp++
}
if j%p == 0 {
spf = true
break
}
}
if cp == 0 && i > 2 {
cp = 1
primes << i
}
if !spf {
if cp%2 == 0 {
sum++
} else {
sum--
}
}
merts[i] = sum
if sum == 0 {
zeros++
if i > 1 && merts[i-1] != 0 {
crosses++
}
}
}
return merts, zeros, crosses
}
fn main() {
merts, zeros, crosses := mertens(1000)
println("Mertens sequence - First 199 terms:")
for i := 0; i < 200; i++ {
if i == 0 {
print(" ")
continue
}
if i%20 == 0 {
println('')
}
print(" ${merts[i]:2}")
}
println("\n\nEquals zero $zeros times between 1 and 1000")
println("\nCrosses zero $crosses times between 1 and 1000")
} |
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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 == 1) return 1
var sqFree = isSquareFree.call(n)
var factors = Int.primeFactors(n)
if (sqFree && factors.count % 2 == 0) return 1
if (sqFree) return -1
return 0
}
var M = Fn.new { |x| (1..x).reduce { |sum, n| sum + mu.call(n) } }
System.print("The first 199 Mertens numbers are:")
for (i in 0..9) {
for (j in 0..19) {
if (i == 0 && j == 0) {
System.write(" ")
} else {
System.write("%(Fmt.dm(3, M.call(i*20 + j))) ")
}
}
System.print()
}
// use the recurrence relationship for the last 2 parts rather than calling M directly
var count = 0
var mertens = M.call(1)
for (i in 2..1000) {
mertens = mertens + mu.call(i)
if (mertens == 0) count = count + 1
}
System.print("\nThe Mertens function is zero %(count) times in the range [1, 1000].")
count = 0
var prev = M.call(1)
for (i in 2..1000) {
var next = prev + mu.call(i)
if (next == 0 && prev != 0) count = count + 1
prev = next
}
System.print("\nThe Mertens function crosses zero %(count) times in the range [1, 1000].") |
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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 range(0; length) as $i (""; . + "\($i + 1): \($in[$i])\n")) ) as $prompt
| read($prompt; length) as $read
| if ($read|type) == "string" then $read
else "Thank you for selecting \($in[$read-1])" end
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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 end if
return result
end function
function r32(atom a)
return remainder(a,#100000000)
end function
function rol(atom word,integer bits)
-- left rotate the bits of a 32-bit number by the specified number of bits
return r32(word*power(2,bits))+floor(word/power(2,32-bits))
end function
constant K =
{#d76aa478, #e8c7b756, #242070db, #c1bdceee, #f57c0faf, #4787c62a, #a8304613, #fd469501,
#698098d8, #8b44f7af, #ffff5bb1, #895cd7be, #6b901122, #fd987193, #a679438e, #49b40821,
#f61e2562, #c040b340, #265e5a51, #e9b6c7aa, #d62f105d, #02441453, #d8a1e681, #e7d3fbc8,
#21e1cde6, #c33707d6, #f4d50d87, #455a14ed, #a9e3e905, #fcefa3f8, #676f02d9, #8d2a4c8a,
#fffa3942, #8771f681, #6d9d6122, #fde5380c, #a4beea44, #4bdecfa9, #f6bb4b60, #bebfbc70,
#289b7ec6, #eaa127fa, #d4ef3085, #04881d05, #d9d4d039, #e6db99e5, #1fa27cf8, #c4ac5665,
#f4292244, #432aff97, #ab9423a7, #fc93a039, #655b59c3, #8f0ccc92, #ffeff47d, #85845dd1,
#6fa87e4f, #fe2ce6e0, #a3014314, #4e0811a1, #f7537e82, #bd3af235, #2ad7d2bb, #eb86d391}
constant m_block = {1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,15,16,
2, 7,12, 1, 6,11,16, 5,10,15, 4, 9,14, 3, 8,13,
6, 9,12,15, 2, 5, 8,11,14, 1, 4, 7,10,13,16, 3,
1, 8,15, 6,13, 4,11, 2, 9,16, 7,14, 5,12, 3,10}
constant c_words = {#67452301,#efcdab89,#98badcfe,#10325476}
sequence words
function divide_in_words(sequence message)
-- Divides the string into words (32-bit numbers)
integer l = floor(length(message)/4)
sequence res = repeat(0,l)
for word=1 to l do
res[word] = bytes_to_int(message[word*4-3..word*4])
end for
return res
end function
procedure process_block(sequence block)
-- Updates the words according to the contents of the block
atom a,b,c,d
block = divide_in_words(block)
a = words[1]
b = words[2]
c = words[3]
d = words[4]
-- Round 1
for step=1 to 16 by 4 do
a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uor(and_bits(b,c),and_bits(not_bits(b),d))), 7))
d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uor(and_bits(a,b),and_bits(not_bits(a),c))),12))
c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uor(and_bits(d,a),and_bits(not_bits(d),b))),17))
b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uor(and_bits(c,d),and_bits(not_bits(c),a))),22))
end for
-- Round 2
for step=17 to 32 by 4 do
a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uor(and_bits(b,d),and_bits(c,not_bits(d)))), 5))
d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uor(and_bits(a,c),and_bits(b,not_bits(c)))), 9))
c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uor(and_bits(d,b),and_bits(a,not_bits(b)))),14))
b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uor(and_bits(c,a),and_bits(d,not_bits(a)))),20))
end for
-- Round 3
for step=33 to 48 by 4 do
a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uxor(b,xor_bits(c,d))), 4))
d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uxor(a,xor_bits(b,c))),11))
c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uxor(d,xor_bits(a,b))),16))
b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uxor(c,xor_bits(d,a))),23))
end for
-- Round 4
for step=49 to 64 by 4 do
a = r32(b+rol(r32(a+block[m_block[step ]]+K[step ]+uxor(c,or_bits(b,not_bits(d)))), 6))
d = r32(a+rol(r32(d+block[m_block[step+1]]+K[step+1]+uxor(b,or_bits(a,not_bits(c)))),10))
c = r32(d+rol(r32(c+block[m_block[step+2]]+K[step+2]+uxor(a,or_bits(d,not_bits(b)))),15))
b = r32(c+rol(r32(b+block[m_block[step+3]]+K[step+3]+uxor(d,or_bits(c,not_bits(a)))),21))
end for
-- Update the words
words = deep_copy(words)
words[1] = r32(words[1]+a)
words[2] = r32(words[2]+b)
words[3] = r32(words[3]+c)
words[4] = r32(words[4]+d)
end procedure
function pad_message(sequence message)
-- Add bytes to the end of the message so it can be divided
-- in an exact number of 64-byte blocks.
integer l = length(message),
bytes_to_add = 64-remainder(l+9,64)
if bytes_to_add=64 then bytes_to_add = 0 end if
message = deep_copy(message)
message &= #80
message &= repeat(0,bytes_to_add)
message &= int_to_bytes(l*8)&{0,0,0,0}
return message
end function
global function md5(sequence message)
-- Given a string, returns a 16-byte hash of it.
words = c_words -- Initialize the H words
message = pad_message(message) -- Add bytes to the message
-- Process each 64-byte block
for block=1 to length(message) by 64 do
process_block(message[block..block+63])
end for
-- Convert hash into bytes
return int_to_bytes(words[1])& -- Return the hash
int_to_bytes(words[2])&
int_to_bytes(words[3])&
int_to_bytes(words[4])
end function
if platform()=JS or include_file()=1 then
string fmt = "0x%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X\n"
printf(1,fmt,md5(""))
printf(1,fmt,md5("a"))
printf(1,fmt,md5("abc"))
printf(1,fmt,md5("message digest"))
printf(1,fmt,md5("abcdefghijklmnopqrstuvwxyz"))
printf(1,fmt,md5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"))
printf(1,fmt,md5("12345678901234567890123456789012345678901234567890123456789012345678901234567890"))
end if
|
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; the first line should return valid answers, those of the second line should return clear indications of an error:
123, 12345, 1234567, 987654321, 10001, -10001, -123, -100, 100, -12345
1, 2, -1, -10, 2002, -2002, 0
Show your output on this page.
| #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, -12345, 1, 2, -1, -10, 2002, -2002, 0]
@printf("%10d -> %s\n", n, try middle3(n) catch e e.msg end)
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 primality test is a primality test: an algorithm which determines whether a given number is prime or not.
The algorithm, as modified by Michael O. Rabin to avoid the generalized Riemann hypothesis, is a probabilistic algorithm.
The pseudocode, from Wikipedia is:
Input: n > 2, an odd integer to be tested for primality;
k, a parameter that determines the accuracy of the test
Output: composite if n is composite, otherwise probably prime
write n − 1 as 2s·d with d odd by factoring powers of 2 from n − 1
LOOP: repeat k times:
pick a randomly in the range [2, n − 1]
x ← ad mod n
if x = 1 or x = n − 1 then do next LOOP
repeat s − 1 times:
x ← x2 mod n
if x = 1 then return composite
if x = n − 1 then do next LOOP
return composite
return probably prime
The nature of the test involves big numbers, so the use of "big numbers" libraries (or similar features of the language of your choice) are suggested, but not mandatory.
Deterministic variants of the test exist and can be implemented as extra (not mandatory to complete the task)
| #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 == n - 1)
return true;
a_to_power = (a_to_power * a_to_power) % n;
}
return a_to_power == n - 1;
}
int is_prime(int n){
array(int) prime ;
prime = ({2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 47, 53, 59, 61, 67, 71, 79, 83, 89, 97, 101, 103, 107, 109, 113});
int idx = search( prime, n);
if( n < 113 && n == prime[idx] ){
return 1;
}
if(n < 2047) prime = ({2, 3});
if(n < 1373653)prime = ({2, 3});
if(n < 9080191)prime = ({31, 73});
if(n < 25326001)prime = ({2, 3, 5});
if(n < 3215031751)prime = ({2, 3, 5, 7});
if(n < 4759123141)prime = ({2, 7, 61});
if(n < 1122004669633)prime = ({2, 13, 23, 1662803});
if(n < 2152302898747)prime = ({2, 3, 5, 7, 11});
if(n < 3474749660383)prime = ({2, 3, 5, 7, 11, 13});
if(n < 341550071728321)prime = ({2, 3, 5, 7, 11, 13, 17});
if(n < 3825123056546413051)prime = ({2, 3, 5, 7, 11, 13, 17, 19, 23});
if(n < 18446744073709551616)prime = ({2, 3, 5, 7, 11, 13, 17, 19, 23, 29});
if(n < 318665857834031151167461)prime = ({2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31});
if(n < 3317044064679887385961981)prime = ({2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37});
else prime = ({2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 47, 53, 59, 61, 67, 71});
int d = n - 1;
int s = 0;
while(d % 2 == 0){
d >>= 1;
s += 1;
}
for (int repeat=0 ; repeat < sizeof(prime); repeat++){
int a = prime[repeat];
if(!mr_pass(a, s, d, n)){
return 0;
}
}
return 1;
}
int main() {
array(int) lists;
lists =({35201546659608842026088328007565866231962578784643756647773109869245232364730066609837018108561065242031153677,
10513733234846849736873637829838635104309714688896631127438692162131857778044158273164093838937083421380041997,
24684249032065892333066123534168930441269525239006410135714283699648991959894332868446109170827166448301044689,
76921421106760125285550929240903354966370431827792714920086011488103952094969175731459908117375995349245839343,
32998886283809577512914881459957314326750856532546837122557861905096711274255431870995137546575954361422085081,
30925729459015376480470394633122420870296099995740154747268426836472045107181955644451858184784072167623952123,
14083359469338511572632447718747493405040362318205860500297736061630222431052998057250747900577940212317413063,
10422980533212493227764163121880874101060283221003967986026457372472702684601194916229693974417851408689550781,
36261430139487433507414165833468680972181038593593271409697364115931523786727274410257181186996611100786935727,
15579763548573297857414066649875054392128789371879472432457450095645164702139048181789700140949438093329334293});
for(int i=0;i<sizeof(lists);i++){
int n = lists[i];
int chk = is_prime(n);
if(chk == 1) write(sprintf("%d %s\n",n,"PRIME"));
else write(sprintf("%d %s\n",n,"COMPOSIT"));
}
}
TEST
35201546659608842026088328007565866231962578784643756647773109869245232364730066609837018108561065242031153677 PRIME
10513733234846849736873637829838635104309714688896631127438692162131857778044158273164093838937083421380041997 PRIME
24684249032065892333066123534168930441269525239006410135714283699648991959894332868446109170827166448301044689 PRIME
76921421106760125285550929240903354966370431827792714920086011488103952094969175731459908117375995349245839343 PRIME
32998886283809577512914881459957314326750856532546837122557861905096711274255431870995137546575954361422085081 PRIME
30925729459015376480470394633122420870296099995740154747268426836472045107181955644451858184784072167623952123 PRIME
14083359469338511572632447718747493405040362318205860500297736061630222431052998057250747900577940212317413063 PRIME
10422980533212493227764163121880874101060283221003967986026457372472702684601194916229693974417851408689550781 PRIME
36261430139487433507414165833468680972181038593593271409697364115931523786727274410257181186996611100786935727 PRIME
15579763548573297857414066649875054392128789371879472432457450095645164702139048181789700140949438093329334293 PRIME
|
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 == x.
Task
Write a routine (function, procedure, whatever) to find the Mertens number for any positive integer x.
Use that routine to find and display here, on this page, at least the first 99 terms in a grid layout. (Not just one long line or column of numbers.)
Use that routine to find and display here, on this page, the number of times the Mertens function sequence is equal to zero in the range M(1) through M(1000).
Use that routine to find and display here, on this page, the number of times the Mertens function sequence crosses zero in the range M(1) through M(1000). (Crossing defined as this term equal to zero but preceding term not.)
See also
Wikipedia: Mertens function
Wikipedia: Möbius function
OEIS: A002321 - Mertens's function
OEIS: A028442 - Numbers n such that Mertens's function M(n) is zero
Numberphile - Mertens Conjecture
Stackexchange: compute the mertens function
This is not code golf. The stackexchange link is provided as an algorithm reference, not as a guide.
Related tasks
Möbius function
| #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 prime factors of n
acc:=fcn(n,k,acc,maxD){ // k is 2,3,5,7,9,... not optimum
if(n==1 or k>maxD) acc.close();
else{
q,r:=n.divr(k); // divr-->(quotient,remainder)
if(r==0) return(self.fcn(q,k,acc.write(k),q.toFloat().sqrt()));
return(self.fcn(n,k+1+k.isOdd,acc,maxD)) # both are tail recursion
}
}(n,2,Sink(List),n.toFloat().sqrt());
m:=acc.reduce('*,1); // mulitply factors
if(n!=m) acc.append(n/m); // opps, missed last factor
else acc;
} |
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 selected index number.
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list.
For test purposes use the following four phrases in a list:
fee fie
huff and puff
mirror mirror
tick tock
Note
This task is fashioned after the action of the Bash select statement.
| #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 items"
function _selector(items, prompt::AbstractString)
isempty(items) && return ""
reply = -1
itemcount = length(items)
while !_ok(reply, itemcount)
_menu(items)
print(prompt)
reply = strip(readline(STDIN))
end
return items[parse(Int, reply)]
end
items = ["fee fie", "huff and puff", "mirror mirror", "tick tock"]
item = _selector(items, "Which is from the three pigs: ")
println("You chose: ", item) |
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 to implement the key functionality namely producing a correct message digest for an input string. It is not necessary to mimic all of the calling modes such as adding to a digest one block at a time over subsequent calls.
In addition to coding and verifying your implementation, note any challenges your language presented implementing the solution, implementation choices made, or limitations of your solution.
Solutions on this page should implement MD5 directly and NOT use built in (MD5) functions, call outs to operating system calls or library routines written in other languages as is common in the original MD5 task.
The following are acceptable:
An original implementation from the specification, reference implementation, or pseudo-code
A translation of a correct implementation from another language
A library routine in the same language; however, the source must be included here.
The solutions shown here will provide practical illustrations of bit manipulation, unsigned integers, working with little-endian data. Additionally, the task requires an attention to details such as boundary conditions since being out by even 1 bit will produce dramatically different results. Subtle implementation bugs can result in some hashes being correct while others are wrong. Not only is it critical to get the individual sub functions working correctly, even small errors in padding, endianness, or data layout will result in failure.
RFC 1321
hash code <== string
0xd41d8cd98f00b204e9800998ecf8427e <== ""
0x0cc175b9c0f1b6a831c399e269772661 <== "a"
0x900150983cd24fb0d6963f7d28e17f72 <== "abc"
0xf96b697d7cb7938d525a2f31aaf161d0 <== "message digest"
0xc3fcd3d76192e4007dfb496cca67e13b <== "abcdefghijklmnopqrstuvwxyz"
0xd174ab98d277d9f5a5611c2c9f419d9f <== "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
0x57edf4a22be3c955ac49da2e2107b67a <== "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
In addition, intermediate outputs to aid in developing an implementation can be found here.
The MD5 Message-Digest Algorithm was developed by RSA Data Security, Inc. in 1991.
Warning
Rosetta Code is not a place you should rely on for examples of code in critical roles, including security.
Also, note that MD5 has been broken and should not be used in applications requiring security. For these consider SHA2 or the upcoming SHA3.
| #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
(/ (* (abs (sin (* I 1.0))) `(** 2 32)) 1.0) ) ) ) )
(de mod32 (N)
(& N `(hex "FFFFFFFF")) )
(de not32 (N)
(x| N `(hex "FFFFFFFF")) )
(de add32 @
(mod32 (pass +)) )
(de leftRotate (X C)
(| (mod32 (>> (- C) X)) (>> (- 32 C) X)) )
(de md5 (Str)
(let Len (length Str)
(setq Str
(conc
(need
(- 8 (* 64 (/ (+ Len 1 8 63) 64))) # Pad to 64-8 bytes
(conc
(mapcar char (chop Str)) # Works only with ASCII characters
(cons `(hex "80")) ) # '1' bit
0 ) # Pad with '0'
(make
(setq Len (* 8 Len))
(do 8
(link (& Len 255))
(setq Len (>> 8 Len )) ) ) ) ) )
(let
(H0 `(hex "67452301")
H1 `(hex "EFCDAB89")
H2 `(hex "98BADCFE")
H3 `(hex "10325476") )
(while Str
(let
(A H0 B H1 C H2 D H3
W (make
(do 16
(link
(apply |
(mapcar >> (0 -8 -16 -24) (cut 4 'Str)) ) ) ) ) )
(use (Tmp F G)
(for I 64
(cond
((>= 16 I)
(setq
F (| (& B C) (& (not32 B) D))
G I ) )
((>= 32 I)
(setq
F (| (& D B) (& (not32 D) C))
G (inc (& (inc (* 5 (dec I))) 15)) ) )
((>= 48 I)
(setq
F (x| B C D)
G (inc (& (+ 5 (* 3 (dec I))) 15)) ) )
(T
(setq
F (x| C (| B (not32 D)))
G (inc (& (* 7 (dec I)) 15)) ) ) )
(setq
Tmp D
D C
C B
B
(add32 B
(leftRotate
(add32 A F (get *Md5-K I) (get W G))
(get *Md5-R I) ) )
A Tmp ) ) )
(setq
H0 (add32 H0 A)
H1 (add32 H1 B)
H2 (add32 H2 C)
H3 (add32 H3 D) ) ) )
(pack
(make
(for N (list H0 H1 H2 H3)
(do 4 # Convert to little endian hex string
(link (pad 2 (hex (& N 255))))
(setq N (>> 8 N)) ) ) ) ) ) ) |
Subsets and Splits
Select Specific Languages Codes
Retrieves specific programming language names and codes from training data, providing basic filtering but limited analytical value beyond identifying these particular languages.