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/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#EchoLisp
EchoLisp
  (define (eval-with-x prog x) (eval prog (environment-new (list (list 'x x)))))   (define prog '( + 1 (* x x)))   (eval-with-x prog 10) → 101 (eval-with-x prog 1000) → 1000001 (- (eval-with-x prog 1000) (eval-with-x prog 10)) → 999900   ;; check x is unbound (no global) x 😖️ error: #|user| : unbound variable : x  
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#Ada
Ada
  WITH GMP, GMP.Integers, Ada.Text_IO, GMP.Integers.Aliased_Internal_Value, Interfaces.C; USE GMP, Gmp.Integers, Ada.Text_IO, Interfaces.C;   PROCEDURE Main IS FUNCTION "+" (U : Unbounded_Integer) RETURN Mpz_T IS (Aliased_Internal_Value (U)); FUNCTION "+" (S : String) RETURN Unbounded_Integer IS (To_Unbounded_Integer (S)); FUNCTION Image_Cleared (M : Mpz_T) RETURN String IS (Image (To_Unbounded_Integer (M))); N  : Unbounded_Integer := +"9516311845790656153499716760847001433441357"; E  : Unbounded_Integer := +"65537"; D  : Unbounded_Integer := +"5617843187844953170308463622230283376298685"; Plain_Text  : CONSTANT String := "Rosetta Code"; M, M_C, M_D  : Mpz_T; -- We import two C functions from the GMP library which are not in the specs of the gmp package PROCEDURE Mpz_Import (Rop  : Mpz_T; Count : Size_T; Order : Int; Size : Size_T; Endian : Int; Nails : Size_T; Op : Char_Array); PRAGMA Import (C, Mpz_Import, "__gmpz_import");   PROCEDURE Mpz_Export (Rop  : OUT Char_Array; Count : ACCESS Size_T; Order : Int; Size : Size_T; Endian : Int; Nails : Size_T; Op : Mpz_T); PRAGMA Import (C, Mpz_Export, "__gmpz_export"); BEGIN Mpz_Init (M); Mpz_Init (M_C); Mpz_Init (M_D); Mpz_Import (M, Plain_Text'Length + 1, 1, 1, 0, 0, To_C (Plain_Text)); Mpz_Powm (M_C, M, +E, +N); Mpz_Powm (M_D, M_C, +D, +N); Put_Line ("Encoded plain text: " & Image_Cleared (M)); DECLARE Decrypted : Char_Array (1 .. Mpz_Sizeinbase (M_C, 256)); BEGIN Put_Line ("Encryption of this encoding: " & Image_Cleared (M_C)); Mpz_Export (Decrypted, NULL, 1, 1, 0, 0, M_D); Put_Line ("Decryption of the encoding: " & Image_Cleared (M_D)); Put_Line ("Final decryption: " & To_Ada (Decrypted)); END; END Main;  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#PARI.2FGP
PARI/GP
Eratosthenes(lim)={ my(v=Vecsmall(lim\1,unused,1)); forprime(p=2,sqrt(lim), forstep(i=p^2,lim,p, v[i]=0 ) ); for(i=1,lim,if(v[i],print1(i", "))) };
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Phix
Phix
constant CITY_NAME = 1, POPULATION = 2 constant municipalities = {{"Lagos",21}, {"Cairo",15.2}, {"Kinshasa-Brazzaville",11.3}, {"Greater Johannesburg",7.55}, {"Mogadishu",5.85}, {"Khartoum-Omdurman",4.98}, {"Dar Es Salaam",4.7}, {"Alexandria",4.58}, {"Abidjan",4.4}, {"Casablanca",3.98}} function searchfor(sequence s, integer rid, object user_data, bool return_index=false) for i=1 to length(s) do if rid(s[i],user_data) then return iff(return_index?i:s[i]) end if end for return 0 -- not found end function function city_named(sequence si, string city_name) return si[CITY_NAME]==city_name end function ?searchfor(municipalities,city_named,"Dar Es Salaam",true) function smaller_than(sequence si, atom population) return si[POPULATION]<population end function ?searchfor(municipalities,smaller_than,5)[CITY_NAME] function starts_with(sequence si, integer ch) return si[CITY_NAME][1]=ch end function ?searchfor(municipalities,starts_with,'A')[POPULATION]
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#C.2B.2B
C++
#include <string> #include <algorithm> #include <iterator> #include <cstddef> #include <exception> #include <iostream>   // an exception to throw (actually, throwing an exception in this case is generally considered bad style, but it's part of the task) class not_found: public std::exception { public: not_found(std::string const& s): text(s + " not found") {} char const* what() const throw() { return text.c_str(); } ~not_found() throw() {} private: std::string text; };   // needle search function, C-style interface version using standard library std::size_t get_index(std::string* haystack, int haystack_size, std::string needle) { std::size_t index = std::find(haystack, haystack+haystack_size, needle) - haystack; if (index == haystack_size) throw not_found(needle); else return index; }   // needle search function, completely generic style, needs forward iterators // (works with any container, but inefficient if not random-access-iterator) template<typename FwdIter> typename std::iterator_traits<FwdIter>::difference_type fwd_get_index(FwdIter first, FwdIter last, std::string needle) { FwdIter elem = std::find(first, last, needle); if (elem == last) throw not_found(needle); else return std::distance(first, elem); }   // needle search function, implemented directly, needs only input iterator, works efficiently with all sequences template<typename InIter> typename std::iterator_traits<InIter>::difference_type generic_get_index(InIter first, InIter last, std::string needle) { typename std::iterator_traits<InIter>::difference_type index = 0; while (first != last && *first != needle) { ++index; ++first; } if (first == last) throw not_found(needle); else return index; }   // ----------------------------------------------------------------------------------------------------------------------------------   // a sample haystack (content copied from Haskell example) std::string haystack[] = { "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo" };   // some useful helper functions template<typename T, std::size_t sz> T* begin(T (&array)[sz]) { return array; } template<typename T, std::size_t sz> T* end(T (&array)[sz]) { return array + sz; } template<typename T, std::size_t sz> std::size_t size(T (&array)[sz]) { return sz; }   // test function searching a given needle with each of the methods void test(std::string const& needle) { std::cout << "-- C style interface --\n"; try { std::size_t index = get_index(haystack, size(haystack), needle); std::cout << needle << " found at index " << index << "\n"; } catch(std::exception& exc) // better catch standard exceptions as well; me might e.g. run out of memory { std::cout << exc.what() << "\n"; }   std::cout << "-- generic interface, first version --\n"; try { std::size_t index = fwd_get_index(begin(haystack), end(haystack), needle); std::cout << needle << " found at index " << index << "\n"; } catch(std::exception& exc) // better catch standard exceptions as well; me might e.g. run out of memory { std::cout << exc.what() << "\n"; }   std::cout << "-- generic interface, second version --\n"; try { std::size_t index = generic_get_index(begin(haystack), end(haystack), needle); std::cout << needle << " found at index " << index << "\n"; } catch(std::exception& exc) // better catch standard exceptions as well; me might e.g. run out of memory { std::cout << exc.what() << "\n"; } }   int main() { std::cout << "\n=== Word which only occurs once ===\n"; test("Wally"); std::cout << "\n=== Word occuring multiple times ===\n"; test("Bush"); std::cout << "\n=== Word not occuring at all ===\n"; test("Goofy"); }
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Maxima
Maxima
/* Here is how to create a function and return a value at runtime. In the first example, the function is made global, i.e. it still exists after the statement is run. In the second example, the function is declared local. The evaluated string may read or write any variable defined before eval_string is run. */   kill(f)$   eval_string("block(f(x) := x^2 + 1, f(2))"); 5   fundef(f); /* f(x) := x^2 + 1 */   eval_string("block([f], local(f), f(x) := x^3 + 1, f(2))"); 9   fundef(f); /* f(x) := x^2 + 1 */
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Nanoquery
Nanoquery
exec("println \"hello, world\"") exec("a = 1\nif a = 1\nprintln \"a is 1\"\nend\nprintln \"test\"")
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Nim
Nim
import ../compiler/[nimeval, llstream, ast], strformat, os   let std = findNimStdLibCompileTime() let modules = [std, std / "pure", std / "std", std / "core"] var intr = createInterpreter("script", modules)   #dynamic variable let varname = commandLineParams()[0] let expr = commandLineParams()[1]   #wrap the naked variable name and expression in a definition and proc,respectively to create valid code #for simplicity, the variable will always be an int, but one could of course define the type at runtime #globals and procs must be exported with * to be accessable #we also need to import any modules needed by the runtime code intr.evalScript(llStreamOpen(&"import math,sugar; var {varname}*:int; proc output*():auto = {expr}"))   for i in 0..2: #set 'varname' to a value intr.getGlobalValue(intr.selectUniqueSymbol(varname)).intval = i #evaluate the expression and get the result let output = intr.callRoutine(intr.selectRoutine("output"), []) #depending on the expression, the result could be any type #as an example, here we check for int,float,or string case output.kind of nkIntLit: echo expr, " = ", output.intval of nkFloatLit: echo expr, " = ", output.floatval of nkStrLit: echo expr, " = ", output.strval else: discard   destroyInterpreter(intr)
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Raku
Raku
sub comma { $^i.flip.comb(3).join(',').flip }   use Math::Primesieve;   my $sieve = Math::Primesieve.new;   my @primes = $sieve.primes(10_000_000);   my %filter = @primes.Set;   my $primes = @primes.classify: { %filter{($_ - 1)/2} ?? 'safe' !! 'unsafe' };   for 'safe', 35, 'unsafe', 40 -> $type, $quantity { say "The first $quantity $type primes are:";   say $primes{$type}[^$quantity]».&comma;   say "The number of $type primes up to {comma $_}: ", comma $primes{$type}.first(* > $_, :k) // +$primes{$type} for 1e6, 1e7;   say ''; }
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Elena
Elena
import extensions; import extensions'scripting;   public program() { var text := program_arguments[1]; var arg := program_arguments[2];   var program := lscript.interpret(text); console.printLine( text,",",arg," = ",program.eval(arg.toReal())); }
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Erlang
Erlang
  -module( runtime_evaluation ).   -export( [evaluate_form/2, form_from_string/1, task/0] ).   evaluate_form( Form, {Variable_name, Value} ) -> Bindings = erl_eval:add_binding( Variable_name, Value, erl_eval:new_bindings() ), {value, Evaluation, _} = erl_eval:expr( Form, Bindings ), Evaluation.   form_from_string( String ) -> {ok, Tokens, _} = erl_scan:string( String ), {ok, [Form]} = erl_parse:parse_exprs( Tokens ), Form.   task() -> Form = form_from_string( "X." ), Variable1 = evaluate_form( Form, {'X', 1} ), io:fwrite( "~p~n", [Variable1] ), Variable2 = evaluate_form( Form, {'X', 2} ), io:fwrite( "~p~n", [Variable2] ), io:fwrite( "~p~n", [Variable2 - Variable1] ).  
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#ALGOL_68
ALGOL 68
  COMMENT First cut. Doesn't yet do blocking and deblocking. Also, as encryption and decryption are identical operations but for the reciprocal exponents used, only one has been implemented below.   A later release will address these issues. COMMENT   BEGIN PR precision=1000 PR MODE LLI = LONG LONG INT; CO For brevity CO PROC mod power = (LLI base, exponent, modulus) LLI : BEGIN LLI result := 1, b := base, e := exponent; IF exponent < 0 THEN put (stand error, (("Negative exponent", exponent, newline))) ELSE WHILE e > 0 DO (ODD e | result := (result * b) MOD modulus); e OVERAB 2; b := (b * b) MOD modulus OD FI; result END; PROC modular inverse = (LLI a, m) LLI : BEGIN PROC extended gcd = (LLI x, y) []LLI : BEGIN LLI v := 1, a := 1, u := 0, b := 0, g := x, w := y; WHILE w>0 DO LLI q := g % w, t := a - q * u; a := u; u := t; t := b - q * v; b := v; v := t; t := g - q * w; g := w; w := t OD; a PLUSAB (a < 0 | u | 0); (a, b, g) END; [] LLI egcd = extended gcd (a, m); (egcd[3] > 1 | 0 | egcd[1] MOD m) END; PROC number to string = (LLI number) STRING : BEGIN [] CHAR map = (blank + "ABCDEFGHIJKLMNOPQRSTUVWXYZ")[@0]; LLI local number := number; INT length := SHORTEN SHORTEN ENTIER long long log(number) + 1; (ODD length | length PLUSAB 1); [length % 2] CHAR text; FOR i FROM length % 2 BY -1 TO 1 DO INT index = SHORTEN SHORTEN (local number MOD 100); text[i] := (index > 26 | "?" | map[index]); local number := local number % 100 OD; text END; CO The parameters of a particular RSA cryptosystem CO LLI p = 3490529510847650949147849619903898133417764638493387843990820577; LLI q = 32769132993266709549961988190834461413177642967992942539798288533; LLI n = p * q; LLI phi n = (p-1) * (q-1); LLI e = 9007; LLI d = modular inverse (e, phi n); CO A ciphertext CO LLI cipher text = 96869613754622061477140922254355882905759991124574319874695120930816298225145708356931476622883989628013391990551829945157815154; CO Print out the corresponding plain text CO print (number to string (mod power (ciphertext, d, n))) END  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Pascal
Pascal
  program primes(output)   const PrimeLimit = 1000;   var primes: set of 1 .. PrimeLimit; n, k: integer; needcomma: boolean;   begin { calculate the primes } primes := [2 .. PrimeLimit]; for n := 1 to trunc(sqrt(PrimeLimit)) do begin if n in primes then begin k := n*n; while k < PrimeLimit do begin primes := primes - [k]; k := k + n end end end;   { output the primes } needcomma := false; for n := 1 to PrimeLimit do if n in primes then begin if needcomma then write(', '); write(n); needcomma := true end end.  
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#PHP
PHP
  <?php   $data_array = [ ['name' => 'Lagos', 'population' => 21.0], ['name' => 'Cairo', 'population' => 15.2], ['name' => 'Kinshasa-Brazzaville', 'population' => 11.3], ['name' => 'Greater Johannesburg', 'population' => 7.55], ['name' => 'Mogadishu', 'population' => 5.85], ['name' => 'Khartoum-Omdurman', 'population' => 4.98], ['name' => 'Dar Es Salaam', 'population' => 4.7], ['name' => 'Alexandria', 'population' => 4.58], ['name' => 'Abidjan', 'population' => 4.4], ['name' => 'Casablanca', 'population' => 3.98], ]; $found=0; $search_name = 'Dar Es Salaam'; echo "Find the (zero-based) index of the first city in the list whose name is \"$search_name\" - 6";   $index = array_search($search_name, array_column($data_array, 'name')); $population = $data_array[$index]['population']; echo "\nAnswer 1: Index: [$index] Population for $search_name is $population Million\n";   $search_val = 5; echo "\nFind the name of the first city in this list whose population is less than $search_val million - Khartoum-Omdurman"; foreach ($data_array as $index => $row) { if ($row['population'] < $search_val) { $name = $row['name']; echo "\nAnswer 2: Index [$index] Population for $row[name] is $row[population] Million\n"; break; } }   $search_term = 'A'; echo "\n\nFind the population of the first city in this list whose name starts with the letter \"$search_term\" - 4.58"; foreach ($data_array as $index => $row) { if (strpos($row['name'], $search_term) === 0) { echo "\nAnswer 3: Index: [$index] Population for $row[name] is $row[population] Million\n"; break; } }   echo "\nDone...";   Output: Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" - 6 Answer 1: Index: [6] Population for Dar Es Salaam is 4.7 Million   Find the name of the first city in this list whose population is less than 5 million - Khartoum-Omdurman Answer 2: Index [5] Population for Khartoum-Omdurman is 4.98 Million   Find the population of the first city in this list whose name starts with the letter "A" - 4.58 Answer 3: Index: [7] Population for Alexandria is 4.58 Million   Done...  
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Ceylon
Ceylon
shared test void searchAListTask() { value haystack = [ "Zig", "Zag", "Wally", "Ronald", "Bush", "Krusty", "Charlie", "Bush", "Bozo"];   assert(exists firstIdx = haystack.firstOccurrence("Bush")); assert(exists lastIdx = haystack.lastOccurrence("Bush"));   assertEquals(firstIdx, 4); assertEquals(lastIdx, 7); }
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Oforth
Oforth
"[ [ $a, 12], [$b, 1.2], [ $c, [ $aaa, $bbb, $ccc ] ], [ $torun, #first ] ]" perform .s [1] (List) [[a, 12], [b, 1.2], [c, [aaa, bbb, ccc]], [torun, #first]]   "12 13 +" perform [1:interpreter] ExCompiler : Can't evaluate <+>
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#ooRexx
ooRexx
  a = .array~of(1, 2, 3) ins = "loop num over a; say num; end" interpret ins  
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#OxygenBasic
OxygenBasic
    function ExecSeries(string s,double b,e,i) as string '=================================================== ' sys a,p string v,u,tab,cr,er ' 'PREPARE OUTPUT BUFFER ' p=1 cr=chr(13) chr(10) tab=chr(9) v=nuls 4096 mid v,p,s+cr+cr p+=4+len s ' double x,y,z 'shared variables ' 'COMPILE ' a=compile s er=error if er then print "runtime error: " er : exit function end if ' 'EXECUTE ' for x=b to e step i if p+128>=len v then v+=nuls len(v) 'extend buffer end if call a u=str(x) tab str(y) cr mid v,p,u : p+=len u next ' freememory a 'release compiled code ' return left v,p-1 'results ' end function   '===== 'TESTS '=====   'Expression, StartVal, EndVal stepVal, Increment   print ExecSeries "y=x*x*x", 1, 10, 1 print ExecSeries "y=sqrt x",1, 9 , 1    
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#REXX
REXX
/*REXX program lists a sequence (or a count) of ──safe── or ──unsafe── primes. */ parse arg N kind _ . 1 . okind; upper kind /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 35 /*Not specified? Then assume default.*/ if kind=='' | kind=="," then kind= 'SAFE' /* " " " " " */ if _\=='' then call ser 'too many arguments specified.' if kind\=='SAFE' & kind\=='UNSAFE' then call ser 'invalid 2nd argument: ' okind if kind =='UNSAFE' then safe= 0; else safe= 1 /*SAFE is a binary value for function.*/ w = linesize() - 1 /*obtain the usable width of the term. */ tell= (N>0); @.=; N= abs(N) /*N is negative? Then don't display. */ !.=0;  !.1=2;  !.2=3;  !.3=5;  !.4=7;  !.5=11;  !.6=13;  !.7=17;  !.8=19; #= 8 @.=''; @.2=1; @.3=1; @.5=1; @.7=1; @.11=1; @.13=1; @.17=1; @.19=1; start= # + 1 m= 0; lim=0 /*# is the number of low primes so far*/ $=; do i=1 for # while lim<=N; j= !.i /* [↓] find primes, and maybe show 'em*/ call safeUnsafe; $= strip($) /*go see if other part of a KIND prime.*/ end /*i*/ /* [↑] allows faster loop (below). */ /* [↓] N: default lists up to 35 #'s.*/ do j=!.#+2 by 2 while lim<N /*continue on with the next odd prime. */ if j // 3 == 0 then iterate /*is this integer a multiple of three? */ parse var j '' -1 _ /*obtain the last decimal digit of J */ if _ == 5 then iterate /*is this integer a multiple of five? */ if j // 7 == 0 then iterate /* " " " " " " seven? */ if j //11 == 0 then iterate /* " " " " " " eleven?*/ if j //13 == 0 then iterate /* " " " " " " 13 ? */ if j //17 == 0 then iterate /* " " " " " " 17 ? */ if j //19 == 0 then iterate /* " " " " " " 19 ? */ /* [↓] divide by the primes. ___ */ do k=start to # while !.k * !.k<=j /*divide J by other primes ≤ √ J */ if j // !.k ==0 then iterate j /*÷ by prev. prime? ¬prime ___ */ end /*k*/ /* [↑] only divide up to √ J */ #= # + 1 /*bump the count of number of primes. */  !.#= j; @.j= 1 /*define a prime and its index value.*/ call safeUnsafe /*go see if other part of a KIND prime.*/ end /*j*/ /* [↓] display number of primes found.*/ if $\=='' then say $ /*display any residual primes in $ list*/ say if tell then say commas(m)' ' kind "primes found." else say commas(m)' ' kind "primes found below or equal to " commas(N). exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ add: m= m+1; lim= m; if \tell & j>N then do; lim= j; m= m-1; end; else call app; return 1 app: if tell then if length($ j)>w then do; say $; $ =j; end; else $= $ j; return 1 ser: say; say; say '***error***' arg(1); say; say; exit 13 /*tell error message. */ commas: parse arg _; do jc=length(_)-3 to 1 by -3; _=insert(',', _, jc); end; return _ /*──────────────────────────────────────────────────────────────────────────────────────*/ safeUnsafe: ?= (j-1) % 2 /*obtain the other part of KIND prime. */ if safe then if @.? == '' then return 0 /*not a safe prime.*/ else return add() /*is " " " */ else if @.? == '' then return add() /*is an unsafe prime.*/ else return 0 /*not " " " */
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Factor
Factor
USE: eval : eval-bi@- ( a b program -- n ) tuck [ ( y -- z ) eval ] 2bi@ - ;
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Forth
Forth
: f-" ( a b snippet" -- ) [char] " parse ( code len ) 2dup 2>r evaluate swap 2r> evaluate - . ;   2 3 f-" dup *" \ 5 (3*3 - 2*2)
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Genyris
Genyris
defmacro add100() (+ x 100)   var x 23 var firstresult (add100) x = 1000 print + firstresult (add100)
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#C
C
  #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gmp.h>   int main(void) { mpz_t n, d, e, pt, ct;   mpz_init(pt); mpz_init(ct); mpz_init_set_str(n, "9516311845790656153499716760847001433441357", 10); mpz_init_set_str(e, "65537", 10); mpz_init_set_str(d, "5617843187844953170308463622230283376298685", 10);   const char *plaintext = "Rossetta Code"; mpz_import(pt, strlen(plaintext), 1, 1, 0, 0, plaintext);   if (mpz_cmp(pt, n) > 0) abort();   mpz_powm(ct, pt, e, n); gmp_printf("Encoded:  %Zd\n", ct);   mpz_powm(pt, ct, d, n); gmp_printf("Decoded:  %Zd\n", pt);   char buffer[64]; mpz_export(buffer, NULL, 1, 1, 0, 0, pt); printf("As String: %s\n", buffer);   mpz_clears(pt, ct, n, e, d, NULL); return 0; }  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Perl
Perl
sub sieve { my $n = shift; my @composite; for my $i (2 .. int(sqrt($n))) { if (!$composite[$i]) { for (my $j = $i*$i; $j <= $n; $j += $i) { $composite[$j] = 1; } } } my @primes; for my $i (2 .. $n) { $composite[$i] || push @primes, $i; } @primes; }
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#PicoLisp
PicoLisp
(scl 2)   (de *Data ("Lagos" 21.0) ("Cairo" 15.2) ("Kinshasa-Brazzaville" 11.3) ("Greater Johannesburg" 7.55) ("Mogadishu" 5.85) ("Khartoum-Omdurman" 4.98) ("Dar Es Salaam" 4.7) ("Alexandria" 4.58) ("Abidjan" 4.4) ("Casablanca" 3.98) )   (test 6 (dec (index (assoc "Dar Es Salaam" *Data) *Data)) )   (test "Khartoum-Omdurman" (car (find '((L) (> 5.0 (cadr L))) *Data)) )   (test 4.58 (cadr (find '((L) (pre? "A" (car L))) *Data)) )
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#PowerShell
PowerShell
  $jsonData = @' [ { "Name": "Lagos", "Population": 21.0 }, { "Name": "Cairo", "Population": 15.2 }, { "Name": "Kinshasa-Brazzaville", "Population": 11.3 }, { "Name": "Greater Johannesburg", "Population": 7.55 }, { "Name": "Mogadishu", "Population": 5.85 }, { "Name": "Khartoum-Omdurman", "Population": 4.98 }, { "Name": "Dar Es Salaam", "Population": 4.7 }, { "Name": "Alexandria", "Population": 4.58 }, { "Name": "Abidjan", "Population": 4.4 }, { "Name": "Casablanca", "Population": 3.98 } ] '@   $cities = $jsonData | ConvertFrom-JSON  
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Clojure
Clojure
(let [haystack ["Zig" "Zag" "Wally" "Ronald" "Bush" "Krusty" "Charlie" "Bush" "Bozo"]] (let [idx (.indexOf haystack "Zig")] (if (neg? idx) (throw (Error. "item not found.")) idx)))
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Oz
Oz
declare %% simplest case: just evaluate expressions without bindings R1 = {Compiler.virtualStringToValue "{Abs ~42}"} {Show R1}   %% eval expressions with additional bindings and %% the possibility to kill the evaluation by calling KillProc KillProc R2 = {Compiler.evalExpression "{Abs A}" unit('A':~42) ?KillProc} {Show R2}   %% full control: add and remove bindings, eval expressions or %% statements, set compiler switches etc. Engine = {New Compiler.engine init} {Engine enqueue(setSwitch(expression false))} %% statements instead of expr. {Engine enqueue(mergeEnv(env('A':42 'System':System)))} {Engine enqueue(feedVirtualString("{System.show A}"))}
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#PARI.2FGP
PARI/GP
runme(f)={ f() };   runme( ()->print("Hello world!") )
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Perl
Perl
my ($a, $b) = (-5, 7); $ans = eval 'abs($a * $b)'; # => 35
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Ring
Ring
  load "stdlib.ring"   see "working..." + nl   p = 1 num = 0 limit1 = 36 limit2 = 41 safe1 = 1000000 safe2 = 10000000   see "the first 35 Safeprimes are: " + nl while true p = p + 1 p2 = (p-1)/2 if isprime(p) and isprime(p2) num = num + 1 if num < limit1 see " " + p else exit ok ok end   see nl + "the first 40 Unsafeprimes are: " + nl p = 1 num = 0 while true p = p + 1 p2 = (p-1)/2 if isprime(p) and not isprime(p2) num = num + 1 if num < limit2 see " " + p else exit ok ok end   p = 1 num1 = 0 num2 = 0 while true p = p + 1 p2 = (p-1)/2 if isprime(p) and isprime(p2) if p < safe1 num1 = num1 + 1 ok if p < safe2 num2 = num2 + 1 else exit ok ok end   see nl + "safe primes below 1,000,000: " + num1 + nl see "safe primes below 10,000,000: " + num2 + nl   p = 1 num1 = 0 num2 = 0 while true p = p + 1 p2 = (p-1)/2 if isprime(p) and not isprime(p2) if p < safe1 num1 = num1 + 1 ok if p < safe2 num2 = num2 + 1 else exit ok ok end   see "unsafe primes below 1,000,000: " + num1 + nl see "unsafe primes below 10,000,000: " + num2 + nl   see "done..." + nl  
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Ruby
Ruby
require "prime" class Integer def safe_prime? #assumes prime ((self-1)/2).prime? end end   def format_parts(n) partitions = Prime.each(n).partition(&:safe_prime?).map(&:count) "There are %d safes and %d unsafes below #{n}."% partitions end   puts "First 35 safe-primes:" p Prime.each.lazy.select(&:safe_prime?).take(35).to_a puts format_parts(1_000_000), "\n"   puts "First 40 unsafe-primes:" p Prime.each.lazy.reject(&:safe_prime?).take(40).to_a puts format_parts(10_000_000)  
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Go
Go
package main   import ( "bitbucket.org/binet/go-eval/pkg/eval" "fmt" "go/parser" "go/token" )   func main() { // an expression on x squareExpr := "x*x"   // parse to abstract syntax tree fset := token.NewFileSet() squareAst, err := parser.ParseExpr(squareExpr) if err != nil { fmt.Println(err) return } // create an environment or "world" w := eval.NewWorld()   // allocate a variable wVar := new(intV)   // bind the variable to the name x err = w.DefineVar("x", eval.IntType, wVar) if err != nil { fmt.Println(err) return } // bind the expression AST to the world squareCode, err := w.CompileExpr(fset, squareAst) if err != nil { fmt.Println(err) return } // directly manipulate value of variable within world *wVar = 5 // evaluate r0, err := squareCode.Run() if err != nil { fmt.Println(err) return } // change value *wVar-- // revaluate r1, err := squareCode.Run() if err != nil { fmt.Println(err) return } // print difference fmt.Println(r0.(eval.IntValue).Get(nil) - r1.(eval.IntValue).Get(nil)) }   // int value implementation. type intV int64   func (v *intV) String() string { return fmt.Sprint(*v) } func (v *intV) Get(*eval.Thread) int64 { return int64(*v) } func (v *intV) Set(_ *eval.Thread, x int64) { *v = intV(x) } func (v *intV) Assign(t *eval.Thread, o eval.Value) { *v = intV(o.(eval.IntValue).Get(t)) }
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#C.23
C#
using System; using System.Numerics; using System.Text;   class Program { static void Main(string[] args) { BigInteger n = BigInteger.Parse("9516311845790656153499716760847001433441357"); BigInteger e = 65537; BigInteger d = BigInteger.Parse("5617843187844953170308463622230283376298685");   const string plaintextstring = "Hello, Rosetta!"; byte[] plaintext = ASCIIEncoding.ASCII.GetBytes(plaintextstring); BigInteger pt = new BigInteger(plaintext); if (pt > n) throw new Exception();   BigInteger ct = BigInteger.ModPow(pt, e, n); Console.WriteLine("Encoded: " + ct);   BigInteger dc = BigInteger.ModPow(ct, d, n); Console.WriteLine("Decoded: " + dc);   string decoded = ASCIIEncoding.ASCII.GetString(dc.ToByteArray()); Console.WriteLine("As ASCII: " + decoded); } }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Phix
Phix
constant limit = 1000 sequence primes = {} sequence flags = repeat(1, limit) for i=2 to floor(sqrt(limit)) do if flags[i] then for k=i*i to limit by i do flags[k] = 0 end for end if end for for i=2 to limit do if flags[i] then primes &= i end if end for pp(primes,{pp_Maxlen,77})
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Python
Python
cities = [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ]   def first(query): return next(query, None)   print( first(index for index, city in enumerate(cities) if city['name'] == "Dar Es Salaam"), first(city['name'] for city in cities if city['population'] < 5), first(city['population'] for city in cities if city['name'][0] == 'A'), sep='\n')
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#CLU
CLU
% Search an indexable, ordered collection. % The collection needs to provide `indexes' and `fetch'; % the element type needs to provide `equal'. search = proc [T, U: type] (haystack: T, needle: U) returns (int) signals (not_found) where T has indexes: itertype (T) yields (int), fetch: proctype (T,int) returns (U) signals (bounds), U has equal: proctype (U,U) returns (bool) for i: int in T$indexes(haystack) do if needle = haystack[i] then return (i) end end signal not_found end search   start_up = proc () as = array[string] str_search = search[as,string]   po: stream := stream$primary_output() haystack: as := as$ ["Zig","Zag","Wally","Ronald","Bush","Krusty","Charlie","Bush","Bozo"] needles: as := as$ ["Ronald","McDonald","Bush","Obama"]   for needle: string in as$elements(needles) do stream$puts(po, needle || ": ") stream$putl(po, int$unparse(str_search(haystack,needle))) except when not_found: stream$putl(po, "not found") end end end start_up
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Phix
Phix
-- demo\rosetta\Runtime_evaluation.exw without javascript_semantics requires("1.0.1") include eval.e -- (not an autoinclude, pulls in around 90% of the interpreter/compiler proper) string code = """ integer i = 0 bool r_init = false sequence r if not r_init then r = {} end if for k=1 to 4 do i += k r &= k end for """ ?eval(code,{"i","r"}) -- prints {10,{1,2,3,4}} ?eval(code,{"r"},{{"r_init",true},{"r",{5}}}) -- prints {5,1,2,3,4} ?eval(code,{"i"},{{"i",15}}) -- prints {25} {} = eval(`puts(1,"Hello World\n")`) -- prints Hello World
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#PHP
PHP
  <?php $code = 'echo "hello world"'; eval($code); $code = 'return "hello world"'; print eval($code);  
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#PicoLisp
PicoLisp
program demo = compile_string(#" string name=\"demo\"; string hello() { return(\"hello, i am \"+name); }");   demo()->hello(); Result: "hello, i am demo"
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Rust
Rust
fn is_prime(n: i32) -> bool { for i in 2..n { if i * i > n { return true; } if n % i == 0 { return false; } } n > 1 }   fn is_safe_prime(n: i32) -> bool { is_prime(n) && is_prime((n - 1) / 2) }   fn is_unsafe_prime(n: i32) -> bool { is_prime(n) && !is_prime((n - 1) / 2) }   fn next_prime(n: i32) -> i32 { for i in (n+1).. { if is_prime(i) { return i; } } 0 }   fn main() { let mut safe = 0; let mut unsf = 0; let mut p = 2;   print!("first 35 safe primes: "); while safe < 35 { if is_safe_prime(p) { safe += 1; print!("{} ", p); } p = next_prime(p); } println!("");   p = 2;   print!("first 35 unsafe primes: "); while unsf < 35 { if is_unsafe_prime(p) { unsf += 1; print!("{} ", p); } p = next_prime(p); } println!("");   p = 2; safe = 0; unsf = 0;   while p < 1000000 { if is_safe_prime(p) { safe += 1; } else { unsf += 1; } p = next_prime(p); } println!("safe primes below 1,000,000: {}", safe); println!("unsafe primes below 1,000,000: {}", unsf);   while p < 10000000 { if is_safe_prime(p) { safe += 1; } else { unsf += 1; } p = next_prime(p); } println!("safe primes below 10,000,000: {}", safe); println!("unsafe primes below 10,000,000: {}", unsf); }
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Groovy
Groovy
def cruncher = { x1, x2, program -> Eval.x(x1, program) - Eval.x(x2, program) }
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#J
J
EvalWithX=. monad : 0 'CODE V0 V1'=. y (". CODE [ x=. V1) - (". CODE [ x=. V0) )   EvalWithX '^x';0;1 1.71828183
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#Common_Lisp
Common Lisp
(defparameter *n* 9516311845790656153499716760847001433441357) (defparameter *e* 65537) (defparameter *d* 5617843187844953170308463622230283376298685)   ;; magic (defun encode-string (message) (parse-integer (reduce #'(lambda (x y) (concatenate 'string x y)) (loop for c across message collect (format nil "~2,'0d" (- (char-code c) 32))))))   ;; sorcery (defun decode-string (message) (coerce (loop for (a b) on (loop for char across (write-to-string message) collect char) by #'cddr collect (code-char (+ (parse-integer (coerce (list a b) 'string)) 32))) 'string))   ;; ACTUAL RSA ALGORITHM STARTS HERE ;;   ;; fast modular exponentiation: runs in O(log exponent) ;; acc is initially 1 and contains the result by the end (defun mod-exp (base exponent modulus acc) (if (= exponent 0) acc (mod-exp (mod (* base base) modulus) (ash exponent -1) modulus (if (= (mod exponent 2) 1) (mod (* acc base) modulus) acc))))   ;; to encode a message, we first convert it to its integer form. ;; then, we raise it to the *e* power, modulo *n* (defun encode-rsa (message) (mod-exp (encode-string message) *e* *n* 1))   ;; to decode a message, we raise it to *d* power, modulo *n* ;; and then convert it back into a string (defun decode-rsa (message) (decode-string (mod-exp message *d* *n* 1)))  
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   def sequence /# ( ini end [step] ) #/ ( ) swap for 0 put endfor enddef   1000 var limit   ( 1 limit ) sequence   ( 2 limit ) for >ps ( tps dup * limit tps ) for dup limit < if 0 swap set else drop endif endfor cps endfor ( 1 limit 0 ) remove pstack
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Racket
Racket
  #lang racket   (define (findf/pos proc lst) (let loop ([lst lst] [pos 0]) (cond [(null? lst) #f] [(proc (car lst)) pos] [else (loop (cdr lst) (add1 pos))])))  
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Raku
Raku
my @cities = { name => 'Lagos', population => 21.0 }, { name => 'Cairo', population => 15.2 }, { name => 'Kinshasa-Brazzaville', population => 11.3 }, { name => 'Greater Johannesburg', population => 7.55 }, { name => 'Mogadishu', population => 5.85 }, { name => 'Khartoum-Omdurman', population => 4.98 }, { name => 'Dar Es Salaam', population => 4.7 }, { name => 'Alexandria', population => 4.58 }, { name => 'Abidjan', population => 4.4 }, { name => 'Casablanca', population => 3.98 }, ;   say @cities.first(*<name> eq 'Dar Es Salaam', :k); say @cities.first(*<population> < 5).<name>; say @cities.first(*<name>.match: /^A/).<population>;
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#COBOL
COBOL
*> This is written to COBOL85, which does not include exceptions. IDENTIFICATION DIVISION. PROGRAM-ID. Search-List.   DATA DIVISION. WORKING-STORAGE SECTION. 01 haystack-area. 78 Haystack-Size VALUE 10. 03 haystack-data. 05 FILLER PIC X(7) VALUE "Zig". 05 FILLER PIC X(7) VALUE "Zag". 05 FILLER PIC X(7) VALUE "Wally". 05 FILLER PIC X(7) VALUE "Ronald". 05 FILLER PIC X(7) VALUE "Bush". 05 FILLER PIC X(7) VALUE "Krusty". 05 FILLER PIC X(7) VALUE "Charlie". 05 FILLER PIC X(7) VALUE "Bush". 05 FILLER PIC X(7) VALUE "Boz". 05 FILLER PIC X(7) VALUE "Zag".   03 haystack-table REDEFINES haystack-data. 05 haystack PIC X(7) OCCURS Haystack-Size TIMES INDEXED BY haystack-index.   01 needle PIC X(7).   PROCEDURE DIVISION. main. MOVE "Bush" TO needle PERFORM find-needle   MOVE "Goofy" TO needle PERFORM find-needle   * *> Extra task MOVE "Bush" TO needle PERFORM find-last-of-needle   GOBACK .   find-needle. SEARCH haystack AT END DISPLAY needle " not found."   WHEN haystack (haystack-index) = needle DISPLAY "Found " needle " at " haystack-index "." END-SEARCH .   find-last-of-needle. PERFORM VARYING haystack-index FROM Haystack-Size BY -1 UNTIL haystack-index = 0 OR haystack (haystack-index) = needle END-PERFORM   IF haystack-index = 0 DISPLAY needle " not found." ELSE DISPLAY "Found last of " needle " at " haystack-index "." END-IF .
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Pike
Pike
program demo = compile_string(#" string name=\"demo\"; string hello() { return(\"hello, i am \"+name); }");   demo()->hello(); Result: "hello, i am demo"
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#PowerShell
PowerShell
  $test2plus2 = '2 + 2 -eq 4' Invoke-Expression $test2plus2  
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Python
Python
>>> exec ''' x = sum([1,2,3,4]) print x ''' 10
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Shale
Shale
#!/usr/local/bin/shale   // Safe and unsafe primes. // // Safe prime p: (p - 1) / 2 is prime // Unsafe prime: any prime that is not a safe prime   primes library   init dup var { pl sieve type primes::() 10000000 0 pl generate primes::() } =   isSafe dup var { 1 - 2 / pl isprime primes::() } =   comma dup var { n dup var swap = t dup var n 1000 / = b dup var n 1000 % =   t 0 == { b print } { t.value comma() b ",%03d" printf } if } =   go dup var { n var c1 var c10 var i var p var   "The first 35 safe primes are:" print n 0 = c1 0 = c10 0 = i 0 = { i count pl:: < } { p i pl get primes::() = p isSafe() { n 35 < { p " %d" printf n++ n 35 == { "" println } ifthen } ifthen   p 1000000 < { c1++ } ifthen   c10++ } ifthen   i++ } while "Number of safe primes below 1,000,000 is " print c1.value comma() "" println "Number of safe primes below 10,000,000 is " print c10.value comma() "" println   "The first 40 unsafe primes are:" print n 0 = c1 0 = c10 0 = i 0 = { i count pl:: < } { p i pl get primes::() = p isSafe() not { n 40 < { p " %d" printf n++ n 40 == { "" println } ifthen } ifthen   p 1000000 < { c1++ } ifthen   c10++ } ifthen   i++ } while "Number of unsafe primes below 1,000,000 is " print c1.value comma() "" println "Number of unsafe primes below 10,000,000 is " print c10.value comma() "" println } =   init() go()  
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Sidef
Sidef
func is_safeprime(p) { is_prime(p) && is_prime((p-1)/2) }   func is_unsafeprime(p) { is_prime(p) && !is_prime((p-1)/2) }   func safeprime_count(from, to) { from..to -> count_by(is_safeprime) }   func unsafeprime_count(from, to) { from..to -> count_by(is_unsafeprime) }   say "First 35 safe-primes:" say (1..Inf -> lazy.grep(is_safeprime).first(35).join(' ')) say '' say "First 40 unsafe-primes:" say (1..Inf -> lazy.grep(is_unsafeprime).first(40).join(' ')) say '' say "There are #{safeprime_count(1, 1e6)} safe-primes bellow 10^6" say "There are #{unsafeprime_count(1, 1e6)} unsafe-primes bellow 10^6" say '' say "There are #{safeprime_count(1, 1e7)} safe-primes bellow 10^7" say "There are #{unsafeprime_count(1, 1e7)} unsafe-primes bellow 10^7"
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Java
Java
import java.io.File; import java.lang.reflect.Method; import java.net.URI; import java.util.Arrays; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider;   public class Eval { private static final String CLASS_NAME = "TempPleaseDeleteMe";   private static class StringCompiler extends SimpleJavaFileObject { final String m_sourceCode;   private StringCompiler( final String sourceCode ) { super( URI.create( "string:///" + CLASS_NAME + Kind.SOURCE.extension ), Kind.SOURCE ); m_sourceCode = sourceCode; }   @Override public CharSequence getCharContent( final boolean ignoreEncodingErrors ) { return m_sourceCode; }   private boolean compile() { final JavaCompiler javac = ToolProvider.getSystemJavaCompiler();   return javac.getTask( null, javac.getStandardFileManager( null, null, null ), null, null, null, Arrays.asList( this ) ).call(); }   private double callEval( final double x ) throws Exception { final Class<?> clarse = Class.forName( CLASS_NAME ); final Method eval = clarse.getMethod( "eval", double.class );   return ( Double ) eval.invoke( null, x ); } }   public static double evalWithX( final String code, final double x ) throws Exception { final StringCompiler sc = new StringCompiler( "class " + CLASS_NAME + "{public static double eval(double x){return (" + code + ");}}" );   if ( ! sc.compile() ) throw new RuntimeException( "Compiler error" ); return sc.callEval( x ); }   public static void main( final String [] args ) throws Exception /* lazy programmer */ { final String expression = args [ 0 ]; final double x1 = Double.parseDouble( args [ 1 ] ); final double x2 = Double.parseDouble( args [ 2 ] );   System.out.println( evalWithX( expression, x1 ) - evalWithX( expression, x2 ) ); } }
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#D
D
void main() { import std.stdio, std.bigint, std.algorithm, std.string, std.range, modular_exponentiation;   immutable txt = "Rosetta Code"; writeln("Plain text: ", txt);   // A key set big enough to hold 16 bytes of plain text in // a single block (to simplify the example) and also big enough // to demonstrate efficiency of modular exponentiation. immutable BigInt n = "2463574872878749457479".BigInt * "3862806018422572001483".BigInt; immutable BigInt e = 2 ^^ 16 + 1; immutable BigInt d = "5617843187844953170308463622230283376298685";   // Convert plain text to a number. immutable txtN = reduce!q{ (a << 8) | uint(b) }(0.BigInt, txt); if (txtN >= n) return writeln("Plain text message too long."); writeln("Plain text as a number: ", txtN);   // Encode a single number. immutable enc = txtN.powMod(e, n); writeln("Encoded: ", enc);   // Decode a single number. auto dec = enc.powMod(d, n); writeln("Decoded: ", dec);   // Convert number to text. char[] decTxt; for (; dec; dec >>= 8) decTxt ~= (dec & 0xff).toInt; writeln("Decoded number as text: ", decTxt.retro); }
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#PHP
PHP
  function iprimes_upto($limit) { for ($i = 2; $i < $limit; $i++) { $primes[$i] = true; }   for ($n = 2; $n < $limit; $n++) { if ($primes[$n]) { for ($i = $n*$n; $i < $limit; $i += $n) { $primes[$i] = false; } } }   return $primes; }   echo wordwrap( 'Primes less or equal than 1000 are : ' . PHP_EOL . implode(' ', array_keys(iprimes_upto(1000), true, true)), 100 );  
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#REXX
REXX
/*REXX program (when using criteria) locates values (indices) from an associate array. */ $="Lagos=21, Cairo=15.2, Kinshasa-Brazzaville=11.3, Greater Johannesburg=7.55, Mogadishu=5.85,", "Khartoum-Omdurman=4.98, Dar Es Salaam=4.7, Alexandria=4.58, Abidjan=4.4, Casablanca=3.98" @.= '(city not found)'; city.= "(no city)" /*city search results for not found.*/ /* [↓] construct associate arrays. */ do #=0 while $\=''; parse var $ c '=' p "," $; c=space(c); parse var c a 2; @.c=# city.#=c; pop.#=p; pop.c=#; if @.a==@. then @.a=c; /*assign city, pop, indices.*/ end /*#*/ /* [↑] city array starts at 0 index*/ /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ task 1: show the INDEX of a city.*/ town= 'Dar Es Salaam' /*the name of a city for the search.*/ say 'The city of ' town " has an index of: " @.town /*show (zero─based) index of a city.*/ say /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ task 2: show 1st city whose pop<5 M*/ many=5 /*size of a city's pop in millions. */ do k=0 for # until pop.k<many; end /*find a city's pop from an index. */ say '1st city that has a population less than ' many " million is: " city.k say /*▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒ task 3: show 1st city with A* name.*/ c1= 'A' /*1st character of a city for search*/ say '1st city that starts with the letter' c1 "is: " @.c1 /*stick a fork in it, all done*/
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Common_Lisp
Common Lisp
(let ((haystack '(Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo))) (dolist (needle '(Washington Bush)) (let ((index (position needle haystack))) (if index (progn (print index) (princ needle)) (progn (print needle) (princ "is not in haystack"))))))
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Quackery
Quackery
10 $ "1 swap times [ i 1+ * ]" quackery echo
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#R
R
expr1 <- quote(a+b*c) expr2 <- parse(text="a+b*c")[[1]] expr3 <- call("+", quote(`a`), call("*", quote(`b`), quote(`c`)))
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Racket
Racket
  #lang racket (require racket/sandbox) (define e (make-evaluator 'racket)) (e '(define + *)) (e '(+ 10 20)) (+ 10 20) ;; (e '(delete-file "/etc/passwd")) ;; --> delete-file: `delete' access denied for /etc/passwd  
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Simula
Simula
  BEGIN   CLASS BOOLARRAY(N); INTEGER N; BEGIN BOOLEAN ARRAY DATA(0:N-1); END BOOLARRAY;   CLASS INTARRAY(N); INTEGER N; BEGIN INTEGER ARRAY DATA(0:N-1); END INTARRAY;   REF(BOOLARRAY) PROCEDURE SIEVE(LIMIT); INTEGER LIMIT; BEGIN REF(BOOLARRAY) C; INTEGER P, P2; LIMIT := LIMIT+1; COMMENT TRUE DENOTES COMPOSITE, FALSE DENOTES PRIME. ; C :- NEW BOOLARRAY(LIMIT); COMMENT ALL FALSE BY DEFAULT ; C.DATA(0) := TRUE; C.DATA(1) := TRUE; COMMENT APART FROM 2 ALL EVEN NUMBERS ARE OF COURSE COMPOSITE ; FOR I := 4 STEP 2 UNTIL LIMIT-1 DO C.DATA(I) := TRUE; COMMENT START FROM 3. ; P := 3; WHILE TRUE DO BEGIN P2 := P * P; IF P2 >= LIMIT THEN BEGIN GO TO OUTER_BREAK; END; I := P2; WHILE I < LIMIT DO BEGIN C.DATA(I) := TRUE; I := I + 2 * P; END; WHILE TRUE DO BEGIN P := P + 2; IF NOT C.DATA(P) THEN BEGIN GO TO INNER_BREAK; END; END; INNER_BREAK: END; OUTER_BREAK: SIEVE :- C; END SIEVE;   COMMENT MAIN BLOCK ;   REF(BOOLARRAY) SIEVED; REF(INTARRAY) UNSAFE, SAFE; INTEGER I, COUNT;   COMMENT SIEVE UP TO 10 MILLION ; SIEVED :- SIEVE(10000000);   SAFE :- NEW INTARRAY(35); COUNT := 0; I := 3; WHILE COUNT < 35 DO BEGIN IF NOT SIEVED.DATA(I) AND NOT SIEVED.DATA((I-1)//2) THEN BEGIN SAFE.DATA(COUNT) := I; COUNT := COUNT+1; END; I := I+2; END; OUTTEXT("THE FIRST 35 SAFE PRIMES ARE:"); OUTIMAGE; OUTCHAR('['); FOR I := 0 STEP 1 UNTIL 35-1 DO BEGIN IF I>0 THEN OUTCHAR(' '); OUTINT(SAFE.DATA(I), 0); END; OUTCHAR(']'); OUTIMAGE; OUTIMAGE;   COUNT := 0; FOR I := 3 STEP 2 UNTIL 1000000 DO BEGIN IF NOT SIEVED.DATA(I) AND NOT SIEVED.DATA((I-1)//2) THEN BEGIN COUNT := COUNT+1; END; END; OUTTEXT("THE NUMBER OF SAFE PRIMES BELOW 1,000,000 IS "); OUTINT(COUNT, 0); OUTIMAGE; OUTIMAGE;   FOR I := 1000001 STEP 2 UNTIL 10000000 DO BEGIN IF NOT SIEVED.DATA(I) AND NOT SIEVED.DATA((I-1)//2) THEN COUNT := COUNT+1; END; OUTTEXT("THE NUMBER OF SAFE PRIMES BELOW 10,000,000 IS "); OUTINT(COUNT, 0); OUTIMAGE; OUTIMAGE;   UNSAFE :- NEW INTARRAY(40); UNSAFE.DATA(0) := 2; COMMENT SINCE (2 - 1)/2 IS NOT PRIME ; COUNT := 1; I := 3; WHILE COUNT < 40 DO BEGIN IF NOT SIEVED.DATA(I) AND SIEVED.DATA((I-1)//2) THEN BEGIN UNSAFE.DATA(COUNT) := I; COUNT := COUNT+1; END; I := I+2; END; OUTTEXT("THE FIRST 40 UNSAFE PRIMES ARE:"); OUTIMAGE; OUTCHAR('['); FOR I := 0 STEP 1 UNTIL 40-1 DO BEGIN IF I>0 THEN OUTCHAR(' '); OUTINT(UNSAFE.DATA(I), 0); END; OUTCHAR(']'); OUTIMAGE; OUTIMAGE;   COUNT := 1; FOR I := 3 STEP 2 UNTIL 1000000 DO BEGIN IF NOT SIEVED.DATA(I) AND SIEVED.DATA((I-1)//2) THEN COUNT := COUNT+1; END; OUTTEXT("THE NUMBER OF UNSAFE PRIMES BELOW 1,000,000 IS "); OUTINT(COUNT, 0); OUTIMAGE; OUTIMAGE;   FOR I := 1000001 STEP 2 UNTIL 10000000 DO BEGIN IF NOT SIEVED.DATA(I) AND SIEVED.DATA((I-1)//2) THEN COUNT := COUNT+1; END; OUTTEXT("THE NUMBER OF UNSAFE PRIMES BELOW 10,000,000 IS "); OUTINT(COUNT, 0); OUTIMAGE;     END  
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Smalltalk
Smalltalk
[ | isSafePrime printFirstNElements |   isSafePrime := [:p | ((p-1)//2) isPrime]. printFirstNElements := [:coll :n | (coll to:n) do:[:p | Transcript show:p] separatedBy:[Transcript space] ]. (Iterator on:[:b | Integer primesUpTo:10000000 do:b]) partition:isSafePrime into:[:savePrimes :unsavePrimes | |nSaveBelow1M nSaveBelow10M nUnsaveBelow1M nUnsaveBelow10M|   nSaveBelow1M := savePrimes count:[:p | p < 1000000]. nSaveBelow10M := savePrimes size.   nUnsaveBelow1M := unsavePrimes count:[:p | p < 1000000]. nUnsaveBelow10M := unsavePrimes size.   Transcript showCR: 'first 35 safe primes:'. printFirstNElements value:savePrimes value:35. Transcript cr.   Transcript show: 'safe primes below 1,000,000: '. Transcript showCR:nSaveBelow1M printStringWithThousandsSeparator.   Transcript show: 'safe primes below 10,000,000: '. Transcript showCR:nSaveBelow10M printStringWithThousandsSeparator.   Transcript showCR: 'first 40 unsafe primes:'. printFirstNElements value:unsavePrimes value:40. Transcript cr.   Transcript show: 'unsafe primes below 1,000,000: '. Transcript showCR:nUnsaveBelow1M printStringWithThousandsSeparator.   Transcript show: 'unsafe primes below 10,000,000: '. Transcript showCR:nUnsaveBelow10M printStringWithThousandsSeparator. ] ] benchmark:'runtime: safe primes'
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#JavaScript
JavaScript
function evalWithX(expr, a, b) { var x = a; var atA = eval(expr); x = b; var atB = eval(expr); return atB - atA; }
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Jsish
Jsish
/* Runtime evaluation in an environment, in Jsish */ function evalWithX(expr, a, b) { var x = a; var atA = eval(expr); x = b; var atB = eval(expr); return atB - atA; }   ;evalWithX('Math.exp(x)', 0, 1); ;evalWithX('Math.exp(x)', 1, 0);   /* =!EXPECTSTART!= evalWithX('Math.exp(x)', 0, 1) ==> 1.71828182845905 evalWithX('Math.exp(x)', 1, 0) ==> -1.71828182845905 =!EXPECTEND!= */
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#Delphi
Delphi
  program RSA_code;   {$APPTYPE CONSOLE}   uses System.SysUtils, Velthuis.BigIntegers;   type TRSA = record private n, e, d: BigInteger; class function PlainTextAsNumber(data: AnsiString): BigInteger; static; class function NumberAsPlainText(Num: BigInteger): AnsiString; static; public constructor Create(n, e, d: string); function Encode(data: AnsiString): string; function Decode(code: string): AnsiString; end;   function EncodeRSA(data: AnsiString): string; var n, e, d, bb, ptn, etn, dtn: BigInteger; begin // a key set big enough to hold 16 bytes of plain text in // a single block (to simplify the example) and also big enough // to demonstrate efficiency of modular exponentiation. n := '9516311845790656153499716760847001433441357'; e := '65537'; d := '5617843187844953170308463622230283376298685';   for var c in data do begin bb := ord(c); ptn := (ptn shl 8) or bb; end;   if BigInteger.Compare(ptn, n) >= 0 then begin Writeln('Plain text message too long'); exit; end; writeln('Plain text as a number:', ptn.ToString); writeln(ptn.ToString);   // encode a single number etn := BigInteger.ModPow(ptn, e, n); Writeln('Encoded: ', etn.ToString);   // decode a single number dtn := BigInteger.ModPow(etn, d, n); Writeln('Decoded: ', dtn.ToString);   // convert number to text var db: AnsiString; var bff: BigInteger := $FF; while dtn.BitLength > 0 do begin db := ansichar((dtn and bff).AsInteger) + db; dtn := dtn shr 8; end; Write('Decoded number as text:"', db, '"'); end;   const pt = 'Rosetta Code';   { TRSA }   constructor TRSA.Create(n, e, d: string); begin self.n := n; self.e := e; self.d := d; end;   function TRSA.Decode(code: string): AnsiString; var etn, dtn: BigInteger; begin // decode a single number etn := code; dtn := BigInteger.ModPow(etn, d, n); Result := NumberAsPlainText(dtn); end;   function TRSA.Encode(data: AnsiString): string; var ptn: BigInteger; begin ptn := PlainTextAsNumber(data);   // encode a single number Result := BigInteger.ModPow(ptn, e, n).ToString; end;   class function TRSA.NumberAsPlainText(Num: BigInteger): AnsiString; var bff: BigInteger; begin // convert number to text bff := $FF; Result := ''; while Num.BitLength > 0 do begin Result := ansichar((Num and bff).AsInteger) + Result; Num := Num shr 8; end; end;   class function TRSA.PlainTextAsNumber(data: AnsiString): BigInteger; var c: AnsiChar; bb, n: BigInteger; begin Result := 0; n := '9516311845790656153499716760847001433441357'; for c in data do begin bb := ord(c); Result := (Result shl 8) or bb; end;   if BigInteger.Compare(Result, n) >= 0 then raise Exception.Create('Plain text message too long'); end;   var RSA: TRSA; Encoded: string;   const n = '9516311845790656153499716760847001433441357'; e = '65537'; d = '5617843187844953170308463622230283376298685'; TEST_WORD = 'Rosetta Code';   begin RSA := TRSA.Create(n, e, d); Encoded := RSA.Encode(TEST_WORD); writeln('Plain text: ', TEST_WORD); writeln('Encoded: ', Encoded); writeln('Decoded: ', RSA.Decode(Encoded)); Readln; end.
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#11l
11l
random:seed(Int(Time().unix_time())) V total = 0 V count = 0   [Int] attributes L total < 75 | count < 2 attributes = (0..5).map(attribute -> (sum(sorted((0..3).map(roll -> random:(1 .. 6)))[1..])))   L(attribute) attributes I attribute >= 15 count++   total = sum(attributes)   print(total‘ ’attributes)
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#Picat
Picat
  primes(N) = L => A = new_array(N), foreach(I in 2..floor(sqrt(N))) if (var(A[I])) then foreach(J in I**2..I..N) A[J]=0 end end end, L=[I : I in 2..N, var(A[I])].  
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Ring
Ring
  # Project : Search a list of records   cities = [[:name = "Lagos",:population = 21.0 ], [:name = "Cairo",:population = 15.2 ], [:name = "Kinshasa-Brazzaville",:population = 11.3 ], [:name = "Greater Johannesburg",:population = 7.55], [:name = "Mogadishu",:population = 5.85], [:name = "Khartoum-Omdurman",:population = 4.98], [:name = "Dar Es Salaam",:population = 4.7 ], [:name = "Alexandria",:population = 4.58], [:name = "Abidjan",:population = 4.4 ], [:name = "Casablanca",:population = 3.98]]   for n = 1 to len(cities) if cities[n][:name] = "Dar Es Salaam" see n-1 + nl ok next   for n = 1 to len(cities) if cities[n][:population] < 5.00 see cities[n][:name] + nl exit ok next   for n = 1 to len(cities) if left(cities[n][:name],1) = "A" see cities[n][:population] + nl exit ok next  
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Ruby
Ruby
cities = [ {name: "Lagos", population: 21}, {name: "Cairo", population: 15.2}, {name: "Kinshasa-Brazzaville", population: 11.3}, {name: "Greater Johannesburg", population: 7.55}, {name: "Mogadishu", population: 5.85}, {name: "Khartoum-Omdurman", population: 4.98}, {name: "Dar Es Salaam", population: 4.7}, {name: "Alexandria", population: 4.58}, {name: "Abidjan", population: 4.4}, {name: "Casablanca", population: 3.98}, ]   puts cities.index{|city| city[:name] == "Dar Es Salaam"} # => 6 puts cities.find {|city| city[:population] < 5.0}[:name] # => Khartoum-Omdurman puts cities.find {|city| city[:name][0] == "A"}[:population] # => 4.58  
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#D
D
import std.algorithm, std.range, std.string;   auto firstIndex(R, T)(R hay, T needle) { auto i = countUntil(hay, needle); if (i == -1) throw new Exception("No needle found in haystack"); return i; }   auto lastIndex(R, T)(R hay, T needle) { return walkLength(hay) - firstIndex(retro(hay), needle) - 1; }   void main() { auto h = split("Zig Zag Wally Ronald Bush Krusty Charlie Bush Bozo"); assert(firstIndex(h, "Bush") == 4); assert(lastIndex(h, "Bush") == 7); }
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Raku
Raku
use MONKEY-SEE-NO-EVAL;   my ($a, $b) = (-5, 7); my $ans = EVAL 'abs($a * $b)'; # => 35
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#REBOL
REBOL
a: -5 b: 7 answer: do [abs a * b] ; => 35
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#REXX
REXX
/*REXX program illustrates the ability to execute code entered at runtime (from C.L.)*/ numeric digits 10000000 /*ten million digits should do it. */ bee=51 stuff= 'bee=min(-2,44); say 13*2 "[from inside the box.]"; abc=abs(bee)' interpret stuff say 'bee=' bee say 'abc=' abc say /* [↓] now, we hear from the user. */ say 'enter an expression:' pull expression say say 'expression entered is:' expression say   interpret '?='expression   say 'length of result='length(?) say ' left 50 bytes of result='left(?,50)"···" say 'right 50 bytes of result=···'right(?, 50) /*stick a fork in it, we're all done. */
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Swift
Swift
import Foundation   class PrimeSieve { var composite: [Bool]   init(size: Int) { composite = Array(repeating: false, count: size/2) var p = 3 while p * p <= size { if !composite[p/2 - 1] { let inc = p * 2 var q = p * p while q <= size { composite[q/2 - 1] = true q += inc } } p += 2 } }   func isPrime(number: Int) -> Bool { if number < 2 { return false } if (number & 1) == 0 { return number == 2 } return !composite[number/2 - 1] } }   func commatize(_ number: Int) -> String { let n = NSNumber(value: number) return NumberFormatter.localizedString(from: n, number: .decimal) }   let limit1 = 1000000 let limit2 = 10000000   class PrimeInfo { let maxPrint: Int var count1: Int var count2: Int var primes: [Int]   init(maxPrint: Int) { self.maxPrint = maxPrint count1 = 0 count2 = 0 primes = [] }   func addPrime(prime: Int) { count2 += 1 if prime < limit1 { count1 += 1 } if count2 <= maxPrint { primes.append(prime) } }   func printInfo(name: String) { print("First \(maxPrint) \(name) primes: \(primes)") print("Number of \(name) primes below \(commatize(limit1)): \(commatize(count1))") print("Number of \(name) primes below \(commatize(limit2)): \(commatize(count2))") } }   var safePrimes = PrimeInfo(maxPrint: 35) var unsafePrimes = PrimeInfo(maxPrint: 40)   let sieve = PrimeSieve(size: limit2)   for prime in 2..<limit2 { if sieve.isPrime(number: prime) { if sieve.isPrime(number: (prime - 1)/2) { safePrimes.addPrime(prime: prime) } else { unsafePrimes.addPrime(prime: prime) } } }   safePrimes.printInfo(name: "safe") unsafePrimes.printInfo(name: "unsafe")
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Visual_Basic_.NET
Visual Basic .NET
Imports System.Console   Namespace safety Module SafePrimes Dim pri_HS As HashSet(Of Integer) = Primes(10_000_000).ToHashSet()   Sub Main() For Each UnSafe In {False, True} : Dim n As Integer = If(UnSafe, 40, 35) WriteLine($"The first {n} {If(UnSafe, "un", "")}safe primes are:") WriteLine(String.Join(" ", pri_HS.Where(Function(p) UnSafe Xor pri_HS.Contains(p \ 2)).Take(n))) Next : Dim limit As Integer = 1_000_000 : Do Dim part = pri_HS.TakeWhile(Function(l) l < limit), sc As Integer = part.Count(Function(p) pri_HS.Contains(p \ 2)) WriteLine($"Of the primes below {limit:n0}: {sc:n0} are safe, and {part.Count() - sc:n0} are unsafe.") : If limit = 1_000_000 Then limit *= 10 Else Exit Do Loop End Sub   Private Iterator Function Primes(ByVal bound As Integer) As IEnumerable(Of Integer) If bound < 2 Then Return Yield 2 Dim composite As BitArray = New BitArray((bound - 1) \ 2) Dim limit As Integer = (CInt((Math.Sqrt(bound))) - 1) \ 2 For i As Integer = 0 To limit - 1 : If composite(i) Then Continue For Dim prime As Integer = 2 * i + 3 : Yield prime Dim j As Integer = (prime * prime - 2) \ 2 While j < composite.Count : composite(j) = True : j += prime : End While Next For i As integer = limit To composite.Count - 1 : If Not composite(i) Then Yield 2 * i + 3 Next End Function End Module End Namespace
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#11l
11l
F rk4(f, x0, y0, x1, n) V vx = [0.0] * (n + 1) V vy = [0.0] * (n + 1) V h = (x1 - x0) / Float(n) V x = x0 V y = y0 vx[0] = x vy[0] = y L(i) 1..n V k1 = h * f(x, y) V k2 = h * f(x + 0.5 * h, y + 0.5 * k1) V k3 = h * f(x + 0.5 * h, y + 0.5 * k2) V k4 = h * f(x + h, y + k3) vx[i] = x = x0 + i * h vy[i] = y = y + (k1 + k2 + k2 + k3 + k3 + k4) / 6 R (vx, vy)   F f(Float x, Float y) -> Float R x * sqrt(y)   V (vx, vy) = rk4(f, 0.0, 1.0, 10.0, 100) L(x, y) zip(vx, vy)[(0..).step(10)] print(‘#2.1 #4.5 #2.8’.format(x, y, y - (4 + x * x) ^ 2 / 16))
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Julia
Julia
macro evalwithx(expr, a, b) return quote x = $a tmp = $expr x = $b return $expr - tmp end end   @evalwithx(2 ^ x, 3, 5) # raw expression (AST)
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Kotlin
Kotlin
// Kotlin JS version 1.1.4-3   fun evalWithX(expr: String, a: Double, b: Double) { var x = a val atA = eval(expr) x = b val atB = eval(expr) return atB - atA }   fun main(args: Array<String>) { println(evalWithX("Math.exp(x)", 0.0, 1.0)) }
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#11l
11l
T Token T.enum Kind INT FLOAT STRING IDENT LPAR RPAR END   Kind kind String val   F (kind, val = ‘’) .kind = kind .val = val   F lex(input_str) [Token] result V pos = 0   F current() R I @pos < @input_str.len {@input_str[@pos]} E Char("\0")   L pos < input_str.len V ch = input_str[pos] I ch == ‘(’ pos++ result.append(Token(Token.Kind.LPAR)) E I ch == ‘)’ pos++ result.append(Token(Token.Kind.RPAR)) E I ch C ‘0’..‘9’ V num = ‘’ V kind = Token.Kind.INT L current() C ‘0’..‘9’ num ‘’= current() pos++ I current() == ‘.’ num ‘’= current() kind = FLOAT pos++ L current() C ‘0’..‘9’ num ‘’= current() pos++ result.append(Token(kind, num)) E I ch C (‘ ’, "\t", "\n", "\r") pos++ E I ch == ‘"’ V str = ‘’ pos++ L current() != ‘"’ str ‘’= current() pos++ pos++ result.append(Token(Token.Kind.STRING, str)) E V BannedChars = Set([‘ ’, "\t", ‘"’, ‘(’, ‘)’, ‘;’]) V ident = ‘’ L current() !C BannedChars ident ‘’= current() pos++ result.append(Token(Token.Kind.IDENT, ident))   result.append(Token(Token.Kind.END)) R result   F indent(s, count) R (count * ‘ ’)‘’s.replace("\n", "\n"(count * ‘ ’))   T SExpr T.enum Kind INT FLOAT STRING IDENT LIST   Kind kind String val [SExpr] children   F (kind, val = ‘’) .kind = kind .val = val   F to_str() I .kind C (SExpr.Kind.INT, SExpr.Kind.FLOAT, SExpr.Kind.IDENT) R .val E I .kind == STRING R ‘"’(.val)‘"’ E I .kind == LIST V result = ‘(’ L(i, ex) enumerate(.children) I ex.kind == LIST & ex.children.len > 1 result ‘’= "\n" result ‘’= indent(ex.to_str(), 2) E I i > 0 result ‘’= ‘ ’ result ‘’= ex.to_str() R result‘)’ assert(0B)   V input_str = ‘ ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) ’ V tokens = lex(input_str) V pos = 0   F current() R I :pos < :tokens.len {:tokens[:pos]} E Token(Token.Kind.END)   F parse() -> SExpr V token = current()  :pos++ I token.kind == INT R SExpr(SExpr.Kind.INT, token.val) E I token.kind == FLOAT R SExpr(SExpr.Kind.FLOAT, token.val) E I token.kind == STRING R SExpr(SExpr.Kind.STRING, token.val) E I token.kind == IDENT R SExpr(SExpr.Kind.IDENT, token.val) E I token.kind == LPAR V result = SExpr(SExpr.Kind.LIST) L current().kind !C (Token.Kind.RPAR, Token.Kind.END) result.children.append(parse()) assert(current().kind != END, ‘Missing right paren ')'’)  :pos++ R result assert(0B)   print(parse().to_str())
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#Erlang
Erlang
  %%% @author Tony Wallace <[email protected]> %%% @doc %%% For details of the algorithms used see %%% https://en.wikipedia.org/wiki/Modular_exponentiation %%% @end %%% Created : 21 Jul 2021 by Tony Wallace <tony@resurrection>   -module mod. -export [mod_mult/3,mod_exp/3,binary_exp/2,test/0].   mod_mult(I1,I2,Mod) when I1 > Mod, is_integer(I1), is_integer(I2), is_integer(Mod) -> mod_mult(I1 rem Mod,I2,Mod); mod_mult(I1,I2,Mod) when I2 > Mod, is_integer(I1), is_integer(I2), is_integer(Mod) -> mod_mult(I1,I2 rem Mod,Mod); mod_mult(I1,I2,Mod) when is_integer(I1), is_integer(I2), is_integer(Mod) -> (I1 * I2) rem Mod.   mod_exp(Base,Exp,Mod) when is_integer(Base), is_integer(Exp), is_integer(Mod), Base > 0, Exp > 0, Mod > 0 -> binary_exp_mod(Base,Exp,Mod); mod_exp(_,0,_) -> 1.     binary_exp(Base,Exponent) when is_integer(Base), is_integer(Exponent), Base > 0, Exponent > 0 -> binary_exp(Base,Exponent,1); binary_exp(_,0) -> 1.   binary_exp(_,0,Result) -> Result; binary_exp(Base,Exponent,Acc) -> binary_exp(Base*Base,Exponent bsr 1,Acc * exp_factor(Base,Exponent)).     binary_exp_mod(Base,Exponent,Mod) -> binary_exp_mod(Base rem Mod,Exponent,Mod,1). binary_exp_mod(_,0,_,Result) -> Result; binary_exp_mod(Base,Exponent,Mod,Acc) -> binary_exp_mod((Base*Base) rem Mod, Exponent bsr 1,Mod,(Acc * exp_factor(Base,Exponent))rem Mod).   exp_factor(_,0) -> 1; exp_factor(Base,1) -> Base; exp_factor(Base,Exponent) -> exp_factor(Base,Exponent band 1).   test() -> 445 = mod_exp(4,13,497), %% Rosetta code example: R = 1527229998585248450016808958343740453059 = mod_exp(2988348162058574136915891421498819466320163312926952423791023078876139, 2351399303373464486466122544523690094744975233415544072992656881240319, binary_exp(10,40)), R.   %%%------------------------------------------------------------------- %%% @author Tony Wallace <[email protected]> %%% @doc %%% Blocking not implemented. Runtime exception if message too long %%% Not a practical issue as RSA usually limited to symmetric key exchange %%% However as a key exchange tool no advantage in compressing plaintext %%% so that is not done either. %%% @end %%% Created : 24 Jul 2021 by Tony Wallace <tony@resurrection> %%%-------------------------------------------------------------------   -module rsa. -export([key_gen/2,encrypt/2,decrypt/2,test/0]). -type key() :: {integer(),integer()}. key_gen({N,D},E) -> {{E,N},{D,N}}. -spec encrypt(key(),integer()) -> integer(). encrypt({E,N},MessageInt) when MessageInt < N -> mod:mod_exp(MessageInt,E,N). -spec decrypt(key(),integer()) -> integer(). decrypt({D,N},Message) -> mod:mod_exp(Message,D,N). test() -> PlainText=10722935, N = 9516311845790656153499716760847001433441357, E = 65537, D = 5617843187844953170308463622230283376298685, {PublicKey,PrivateKey} = key_gen({N,D},E), PlainText =:= decrypt(PrivateKey, encrypt(PublicKey,PlainText)).    
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#8086_Assembly
8086 Assembly
bits 16 cpu 8086 putch: equ 2h time: equ 2ch org 100h section .text mov ah,time ; Retrieve system time from MS-DOS int 21h call rseed ; Seed the RNG rolls: xor ah,ah ; AH=0 (running total) mov dx,6 ; DH=0 (amount >=15), DL=6 (counter) mov di,attrs attr: call roll4 ; Roll an attribute mov al,14 cmp al,bh ; Set carry if BH=15 or more mov al,bh ; AL = roll sbb bh,bh ; BH=0 if no carry, -1 if carry sub dh,bh ; DH+=1 if >=15 add ah,al ; Add to running total mov [di],al ; Save roll inc di ; Next memory address dec dl ; One fewer roll left jnz attr cmp ah,75 ; Rolling total < 75? jb rolls ; Then roll again. cmp dh,2 ; Fewer than 2 attrs < 15? jb rolls ; Then roll again. ;;; Print the attributes mov cx,6 ; 6 attributes p2: mov bl,10 ; divide by 10 to get digits mov di,attrs print: xor ah,ah ; AX = attribute mov al,[di] div bl ; divide by 10 add ax,3030h ; add '0' to quotient (AH) and remainder (AL) mov dx,ax mov ah,putch int 21h ; print quotient first mov dl,dh ; then remainder int 21h mov dl,' ' ; then a space int 21h inc di ; Next attribute loop print ret ; Back to DOS ;;; Do 4 rolls, and get result of max 3 roll4: xor bx,bx ; BH = running total dec bl ; BL = lowest value mov cx,4 ; Four times .roll: call d6 ; Roll D6 cmp al,bl ; Lower than current lowest value? jnb .high ; If so, mov bl,al ; Set new lowest value .high: add bh,al ; Add to running total loop .roll ; If not 4 rolls yet, loop back sub bh,bl ; Subtract lowest value (giving sum of high 3) ret ;;; Roll a D6 d6: call rand ; Get random number and al,7 ; Between 0 and 7 cmp al,6 ; If 6 or higher, jae d6 ; Then get new random number inc al ; [1..6] instead of [0..5] ret ;;; Seed the random number generator with 4 bytes rseed: xor [rnddat],cx xor [rnddat+2],dx ;;; "X ABC" random number generator ;;; Generates 8-bit random number in AL rand: push cx ; Keep registers push dx mov cx,[rnddat] ; CL=X CH=A mov dx,[rnddat+2] ; DL=B DH=C xor ch,dh ; A ^= C xor ch,cl ; A ^= X add dl,ch ; B += A mov al,dl ; R = B shr al,1 ; R >>= 1 xor al,ch ; R ^= A add al,dh ; R += C mov dh,al ; C = R mov [rnddat],cx ; Store new state mov [rnddat+2],dx pop dx ; Restore registers pop cx ret section .bss rnddat: resb 4 ; RNG state attrs: resb 6 ; Rolled attributes
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#PicoLisp
PicoLisp
(de sieve (N) (let Sieve (range 1 N) (set Sieve) (for I (cdr Sieve) (when I (for (S (nth Sieve (* I I)) S (nth (cdr S) I)) (set S) ) ) ) (filter bool Sieve) ) )
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Rust
Rust
struct City { name: &'static str, population: f64, }   fn main() { let cities = [ City { name: "Lagos", population: 21.0, }, City { name: "Cairo", population: 15.2, }, City { name: "Kinshasa-Brazzaville", population: 11.3, }, City { name: "Greater Johannesburg", population: 7.55, }, City { name: "Mogadishu", population: 5.85, }, City { name: "Khartoum-Omdurman", population: 4.98, }, City { name: "Dar Es Salaam", population: 4.7, }, City { name: "Alexandria", population: 4.58, }, City { name: "Abidjan", population: 4.4, }, City { name: "Casablanca", population: 3.98, }, ];   println!( "{:?}", cities.iter().position(|city| city.name == "Dar Es Salaam") ); println!( "{:?}", cities .iter() .find(|city| city.population < 5.0) .map(|city| city.name) ); println!( "{:?}", cities .iter() .find(|city| city.name.starts_with('A')) .map(|city| city.population) ); }  
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Scala
Scala
object SearchListOfRecords extends App { val cities = Vector( City("Lagos", 21.0e6), City("Cairo", 15.2e6), City("Kinshasa-Brazzaville", 11.3e6), City("Greater Johannesburg", 7.55e6), City("Mogadishu", 5.85e6), City("Khartoum-Omdurman", 4.98e6), City("Dar Es Salaam", 4.7e6), City("Alexandria", 4.58e6), City("Abidjan", 4.4e6), City("Casablanca", 3.98e6) )   def index = cities.indexWhere((_: City).name == "Dar Es Salaam")   def name = cities.find(_.pop < 5.0e6).map(_.name)   def pop = cities.find(_.name(0) == 'A').map(_.pop)   case class City(name: String, pop: Double)   println( s"Index of first city whose name is 'Dar Es Salaam' = $index\n" + s"Name of first city whose population is less than 5 million = ${name.get}\n" + f"Population of first city whose name starts with 'A' = ${pop.get}%,.0f")   }
http://rosettacode.org/wiki/Search_a_list
Search a list
Task[edit] Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Extra credit Return the largest index to a needle that has multiple occurrences in the haystack. See also Search a list of records
#Delphi
Delphi
program Needle;   {$APPTYPE CONSOLE}   uses SysUtils, Classes;   var list: TStringList; needle: string; ind: Integer; begin list := TStringList.Create; try list.Append('triangle'); list.Append('fork'); list.Append('limit'); list.Append('baby'); list.Append('needle');   list.Sort;   needle := 'needle'; ind := list.IndexOf(needle); if ind < 0 then raise Exception.Create('Needle not found') else begin Writeln(ind); Writeln(list[ind]); end;   Readln; finally list.Free; end; end.
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Ring
Ring
  Eval("nOutput = 5+2*5 " ) See "5+2*5 = " + nOutput + nl Eval("for x = 1 to 10 see x + nl next") Eval("func test see 'message from test!' ") test()  
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Ruby
Ruby
a, b = 5, -7 ans = eval "(a * b).abs" # => 35
http://rosettacode.org/wiki/Runtime_evaluation
Runtime evaluation
Task Demonstrate a language's ability for programs to execute code written in the language provided at runtime. Show what kind of program fragments are permitted (e.g. expressions vs. statements), and how to get values in and out (e.g. environments, arguments, return values), if applicable what lexical/static environment the program is evaluated in, and what facilities for restricting (e.g. sandboxes, resource limits) or customizing (e.g. debugging facilities) the execution. You may not invoke a separate evaluator program, or invoke a compiler and then its output, unless the interface of that program, and the syntax and means of executing it, are considered part of your language/library/platform. For a more constrained task giving a specific program fragment to evaluate, see Eval in environment.
#Scheme
Scheme
> (define x 37) > (eval '(+ x 5)) 42 > (eval '(+ x 5) (interaction-environment)) 42 > (eval '(+ x 5) (scheme-report-environment 5)) ;; provides R5RS definitions   Error: identifier not visible x. Type (debug) to enter the debugger. > (display (eval (read))) (+ 4 5) ;; this is input from the user. 9
http://rosettacode.org/wiki/Safe_primes_and_unsafe_primes
Safe primes and unsafe primes
Definitions   A   safe prime   is a prime   p   and where   (p-1)/2   is also prime.   The corresponding prime  (p-1)/2   is known as a   Sophie Germain   prime.   An   unsafe prime   is a prime   p   and where   (p-1)/2   isn't   a prime.   An   unsafe prime   is a prime that   isn't   a   safe   prime. Task   Find and display (on one line) the first   35   safe primes.   Find and display the   count   of the safe primes below   1,000,000.   Find and display the   count   of the safe primes below 10,000,000.   Find and display (on one line) the first   40   unsafe primes.   Find and display the   count   of the unsafe primes below   1,000,000.   Find and display the   count   of the unsafe primes below 10,000,000.   (Optional)   display the   counts   and   "below numbers"   with commas. Show all output here. Related Task   strong and weak primes. Also see   The OEIS article:     safe   primes.   The OEIS article:   unsafe primes.
#Wren
Wren
import "/math" for Int import "/fmt" for Fmt   var c = Int.primeSieve(1e7, false) // need primes up to 10 million here var safe = List.filled(35, 0) var count = 0 var i = 3 while (count < 35) { if (!c[i] && !c[(i-1)/2]) { safe[count] = i count = count + 1 } i = i + 2 } System.print("The first 35 safe primes are:\n%(safe.join(" "))\n")   count = 35 while (i < 1e6) { if (!c[i] && !c[(i-1)/2]) count = count + 1 i = i + 2 } Fmt.print("The number of safe primes below 1,000,000 is $,d.\n", count)   while (i < 1e7) { if (!c[i] && !c[(i-1)/2]) count = count + 1 i = i + 2 } Fmt.print("The number of safe primes below 10,000,000 is $,d.\n", count)   var unsafe = List.filled(40, 0) unsafe[0] = 2 count = 1 i = 3 while (count < 40) { if (!c[i] && c[(i-1)/2]) { unsafe[count] = i count = count + 1 } i = i + 2 } System.print("The first 40 unsafe primes are:\n%(unsafe.join(" "))\n")   count = 40 while (i < 1e6) { if (!c[i] && c[(i-1)/2]) count = count + 1 i = i + 2 } Fmt.print("The number of unsafe primes below 1,000,000 is $,d.\n", count)   while (i < 1e7) { if (!c[i] && c[(i-1)/2]) count = count + 1 i = i + 2 } Fmt.print("The number of unsafe primes below 10,000,000 is $,d.\n", count)
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#Action.21
Action!
INCLUDE "D2:PRINTF.ACT" ;from the Action! Tool Kit INCLUDE "H6:REALMATH.ACT"   DEFINE PTR="CARD"   REAL one,two,four,six   PROC Init() IntToReal(1,one) IntToReal(2,two) IntToReal(4,four) IntToReal(6,six) RETURN   PROC Fun=*(REAL POINTER x,y,res) DEFINE JSR="$20" DEFINE RTS="$60" [JSR $00 $00 ;JSR to address set by SetFun RTS]   PROC SetFun(PTR p) PTR addr   addr=Fun+1 ;location of address of JSR PokeC(addr,p) RETURN   PROC Rate(REAL POINTER x,y,res) REAL tmp   Sqrt(y,tmp)  ;tmp=sqrt(y) RealMult(x,tmp,res) ;res=x*sqrt(y) RETURN   PROC RK4(PTR f REAL POINTER dx,x,y,res) REAL k1,k2,k3,k4,dx2,k12,k22,tmp1,tmp2,tmp3   SetFun(f) Fun(x,y,tmp1)  ;tmp1=f(x,y) RealMult(dx,tmp1,k1) ;k1=dx*f(x,y)   RealDiv(dx,two,dx2)  ;dx2=dx/2 RealDiv(k1,two,k12)  ;k12=k1/2 RealAdd(x,dx2,tmp1)  ;tmp1=x+dx/2 RealAdd(y,k12,tmp2)  ;tmp2=y+k1/2 Fun(tmp1,tmp2,tmp3)  ;tmp3=f(x+dx/2,y+k1/2) RealMult(dx,tmp3,k2) ;k2=dx*f(x+dx/2,y+k1/2)   RealDiv(k2,two,k22)  ;k22=k2/2 RealAdd(y,k22,tmp2)  ;tmp2=y+k2/2 Fun(tmp1,tmp2,tmp3)  ;tmp3=f(x+dx/2,y+k2/2) RealMult(dx,tmp3,k3) ;k3=dx*f(x+dx/2,y+k2/2)   RealAdd(x,dx,tmp1)  ;tmp1=x+dx RealAdd(y,k3,tmp2)  ;tmp2=y+k3 Fun(tmp1,tmp2,tmp3)  ;tmp3=f(x+dx,y+k3) RealMult(dx,tmp3,k4) ;k4=dx*f(x+dx,y+k3)   RealAdd(k2,k3,tmp1)  ;tmp1=k2+k3 RealMult(two,tmp1,tmp2) ;tmp2=2*k2+2*k3 RealAdd(k1,tmp2,tmp1)  ;tmp3=k1+2*k2+2*k3 RealAdd(tmp1,k4,tmp2)  ;tmp2=k1+2*k2+2*k3+k4 RealDiv(tmp2,six,tmp1)  ;tmp1=(k1+2*k2+2*k3+k4)/6 RealAdd(y,tmp1,res)  ;res=y+(k1+2*k2+2*k3+k4)/6 RETURN   PROC Calc(REAL POINTER x,res) REAL tmp1,tmp2   RealMult(x,x,tmp1)  ;tmp1=x*x RealDiv(tmp1,four,tmp2) ;tmp2=x*x/4 RealAdd(tmp2,one,tmp1)  ;tmp1=x*x/4+1 Power(tmp1,two,res)  ;res=(x*x/4+1)^2 RETURN   PROC RelError(REAL POINTER a,b,res) REAL tmp   RealDiv(a,b,tmp)  ;tmp=a/b RealSub(tmp,one,res) ;res=a/b-1 RETURN   PROC Main() REAL x0,x1,x,dx,y,y2,err,tmp1,tmp2 CHAR ARRAY s(20) INT i,n   Put(125) PutE() ;clear the screen MathInit() Init() PrintF("%-2S %-11S %-8S%E","x","y","rel err")   IntToReal(0,x0) IntToReal(10,x1) ValR("0.1",dx)   RealSub(x1,x0,tmp1)  ;tmp1=x1-x0 RealDiv(tmp1,dx,tmp2)  ;tmp2=(x1-x0)/dx n=RealToInt(tmp2)  ;n=(x1-x0)/dx i=0 IntToReal(1,y) DO IntToReal(i,tmp1)  ;tmp1=i RealMult(dx,tmp1,tmp2) ;tmp2=i*dx RealAdd(x0,tmp2,x)  ;x=x0+i*dx   IF i MOD 10=0 THEN Calc(x,y2) RelError(y,y2,err) StrR(x,s) PrintF("%-2S ",s) StrR(y,s) PrintF("%-11S ",s) StrR(err,s) PrintF("%-8S%E",s) FI   i==+1 IF i>n THEN EXIT FI   RK4(rate,dx,x,y,tmp1)  ;tmp1=rk4(rate,dx,x0+dx*(i-1),y) RealAssign(tmp1,y)  ;y=rk4(rate,dx,x0+dx*(i-1),y) OD RETURN
http://rosettacode.org/wiki/Runge-Kutta_method
Runge-Kutta method
Given the example Differential equation: y ′ ( t ) = t × y ( t ) {\displaystyle y'(t)=t\times {\sqrt {y(t)}}} With initial condition: t 0 = 0 {\displaystyle t_{0}=0} and y 0 = y ( t 0 ) = y ( 0 ) = 1 {\displaystyle y_{0}=y(t_{0})=y(0)=1} This equation has an exact solution: y ( t ) = 1 16 ( t 2 + 4 ) 2 {\displaystyle y(t)={\tfrac {1}{16}}(t^{2}+4)^{2}} Task Demonstrate the commonly used explicit   fourth-order Runge–Kutta method   to solve the above differential equation. Solve the given differential equation over the range t = 0 … 10 {\displaystyle t=0\ldots 10} with a step value of δ t = 0.1 {\displaystyle \delta t=0.1} (101 total points, the first being given) Print the calculated values of y {\displaystyle y} at whole numbered t {\displaystyle t} 's ( 0.0 , 1.0 , … 10.0 {\displaystyle 0.0,1.0,\ldots 10.0} ) along with error as compared to the exact solution. Method summary Starting with a given y n {\displaystyle y_{n}} and t n {\displaystyle t_{n}} calculate: δ y 1 = δ t × y ′ ( t n , y n ) {\displaystyle \delta y_{1}=\delta t\times y'(t_{n},y_{n})\quad } δ y 2 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 1 ) {\displaystyle \delta y_{2}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{1})} δ y 3 = δ t × y ′ ( t n + 1 2 δ t , y n + 1 2 δ y 2 ) {\displaystyle \delta y_{3}=\delta t\times y'(t_{n}+{\tfrac {1}{2}}\delta t,y_{n}+{\tfrac {1}{2}}\delta y_{2})} δ y 4 = δ t × y ′ ( t n + δ t , y n + δ y 3 ) {\displaystyle \delta y_{4}=\delta t\times y'(t_{n}+\delta t,y_{n}+\delta y_{3})\quad } then: y n + 1 = y n + 1 6 ( δ y 1 + 2 δ y 2 + 2 δ y 3 + δ y 4 ) {\displaystyle y_{n+1}=y_{n}+{\tfrac {1}{6}}(\delta y_{1}+2\delta y_{2}+2\delta y_{3}+\delta y_{4})} t n + 1 = t n + δ t {\displaystyle t_{n+1}=t_{n}+\delta t\quad }
#Ada
Ada
with Ada.Text_IO; use Ada.Text_IO; with Ada.Numerics.Generic_Elementary_Functions; procedure RungeKutta is type Floaty is digits 15; type Floaty_Array is array (Natural range <>) of Floaty; package FIO is new Ada.Text_IO.Float_IO(Floaty); use FIO; type Derivative is access function(t, y : Floaty) return Floaty; package Math is new Ada.Numerics.Generic_Elementary_Functions (Floaty); function calc_err (t, calc : Floaty) return Floaty;   procedure Runge (yp_func : Derivative; t, y : in out Floaty_Array; dt : Floaty) is dy1, dy2, dy3, dy4 : Floaty; begin for n in t'First .. t'Last-1 loop dy1 := dt * yp_func(t(n), y(n)); dy2 := dt * yp_func(t(n) + dt / 2.0, y(n) + dy1 / 2.0); dy3 := dt * yp_func(t(n) + dt / 2.0, y(n) + dy2 / 2.0); dy4 := dt * yp_func(t(n) + dt, y(n) + dy3); t(n+1) := t(n) + dt; y(n+1) := y(n) + (dy1 + 2.0 * (dy2 + dy3) + dy4) / 6.0; end loop; end Runge;   procedure Print (t, y : Floaty_Array; modnum : Positive) is begin for i in t'Range loop if i mod modnum = 0 then Put("y("); Put (t(i), Exp=>0, Fore=>0, Aft=>1); Put(") = "); Put (y(i), Exp=>0, Fore=>0, Aft=>8); Put(" Error:"); Put (calc_err(t(i),y(i)), Aft=>5); New_Line; end if; end loop; end Print;   function yprime (t, y : Floaty) return Floaty is begin return t * Math.Sqrt (y); end yprime; function calc_err (t, calc : Floaty) return Floaty is actual : constant Floaty := (t**2 + 4.0)**2 / 16.0; begin return abs(actual-calc); end calc_err;   dt : constant Floaty := 0.10; N : constant Positive := 100; t_arr, y_arr : Floaty_Array(0 .. N); begin t_arr(0) := 0.0; y_arr(0) := 1.0; Runge (yprime'Access, t_arr, y_arr, dt); Print (t_arr, y_arr, 10); end RungeKutta;
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Liberty_BASIC
Liberty BASIC
    expression$ = "x^2 - 7" Print (EvaluateWithX(expression$, 5) - EvaluateWithX(expression$, 3)) End   Function EvaluateWithX(expression$, x) EvaluateWithX = Eval(expression$) End Function
http://rosettacode.org/wiki/Runtime_evaluation/In_an_environment
Runtime evaluation/In an environment
x x x Do so in a way which: does not involve string manipulation of the input source code is plausibly extensible to a runtime-chosen set of bindings rather than just x does not make x a global variable or note that these are impossible. See also For more general examples and language-specific details, see Eval. Dynamic variable names is a similar task.
#Lua
Lua
  code = loadstring"return x^2" --this doesn't really need to be input, does it? val1 = setfenv(code, {x = io.read() + 0})() val2 = setfenv(code, {x = io.read() + 0})() print(val2 - val1)  
http://rosettacode.org/wiki/S-expressions
S-expressions
S-Expressions   are one convenient way to parse and store data. Task Write a simple reader and writer for S-Expressions that handles quoted and unquoted strings, integers and floats. The reader should read a single but nested S-Expression from a string and store it in a suitable datastructure (list, array, etc). Newlines and other whitespace may be ignored unless contained within a quoted string. “()”   inside quoted strings are not interpreted, but treated as part of the string. Handling escaped quotes inside a string is optional;   thus “(foo"bar)” maybe treated as a string “foo"bar”, or as an error. For this, the reader need not recognize “\” for escaping, but should, in addition, recognize numbers if the language has appropriate datatypes. Languages that support it may treat unquoted strings as symbols. Note that with the exception of “()"” (“\” if escaping is supported) and whitespace there are no special characters. Anything else is allowed without quotes. The reader should be able to read the following input ((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)"))) and turn it into a native datastructure. (see the Pike, Python and Ruby implementations for examples of native data structures.) The writer should be able to take the produced list and turn it into a new S-Expression. Strings that don't contain whitespace or parentheses () don't need to be quoted in the resulting S-Expression, but as a simplification, any string may be quoted. Extra Credit Let the writer produce pretty printed output with indenting and line-breaks.
#Ada
Ada
with Ada.Strings.Unbounded; private with Ada.Containers.Indefinite_Vectors;   generic with procedure Print_Line(Indention: Natural; Line: String); package S_Expr is   function "-"(S: String) return Ada.Strings.Unbounded.Unbounded_String renames Ada.Strings.Unbounded.To_Unbounded_String;   function "+"(U: Ada.Strings.Unbounded.Unbounded_String) return String renames Ada.Strings.Unbounded.To_String;   type Empty_Data is tagged null record; subtype Data is Empty_Data'Class; procedure Print(This: Empty_Data; Indention: Natural); -- any object form class Data knows how to print itself -- objects of class data are either List of Data or Atomic -- atomic objects hold either an integer or a float or a string   type List_Of_Data is new Empty_Data with private; overriding procedure Print(This: List_Of_Data; Indention: Natural); function First(This: List_Of_Data) return Data; function Rest(This: List_Of_Data) return List_Of_Data; function Empty(This: List_Of_Data) return Boolean;   type Atomic is new Empty_Data with null record;   type Str_Data is new Atomic with record Value: Ada.Strings.Unbounded.Unbounded_String; Quoted: Boolean := False; end record; overriding procedure Print(This: Str_Data; Indention: Natural);   type Int_Data is new Atomic with record Value: Integer; end record; overriding procedure Print(This: Int_Data; Indention: Natural);   type Flt_Data is new Atomic with record Value: Float; end record; overriding procedure Print(This: Flt_Data; Indention: Natural);   private   package Vectors is new Ada.Containers.Indefinite_Vectors (Index_Type => Positive, Element_Type => Data);   type List_Of_Data is new Empty_Data with record Values: Vectors.Vector; end record;   end S_Expr;
http://rosettacode.org/wiki/RSA_code
RSA code
Given an RSA key (n,e,d), construct a program to encrypt and decrypt plaintext messages strings. Background RSA code is used to encode secret messages. It is named after Ron Rivest, Adi Shamir, and Leonard Adleman who published it at MIT in 1977. The advantage of this type of encryption is that you can distribute the number “ n {\displaystyle n} ” and “ e {\displaystyle e} ” (which makes up the Public Key used for encryption) to everyone. The Private Key used for decryption “ d {\displaystyle d} ” is kept secret, so that only the recipient can read the encrypted plaintext. The process by which this is done is that a message, for example “Hello World” is encoded as numbers (This could be encoding as ASCII or as a subset of characters a = 01 , b = 02 , . . . , z = 26 {\displaystyle a=01,b=02,...,z=26} ). This yields a string of numbers, generally referred to as "numerical plaintext", “ P {\displaystyle P} ”. For example, “Hello World” encoded with a=1,...,z=26 by hundreds would yield 08051212152315181204 {\displaystyle 08051212152315181204} . The plaintext must also be split into blocks so that the numerical plaintext is smaller than n {\displaystyle n} otherwise the decryption will fail. The ciphertext, C {\displaystyle C} , is then computed by taking each block of P {\displaystyle P} , and computing C ≡ P e mod n {\displaystyle C\equiv P^{e}\mod n} Similarly, to decode, one computes P ≡ C d mod n {\displaystyle P\equiv C^{d}\mod n} To generate a key, one finds 2 (ideally large) primes p {\displaystyle p} and q {\displaystyle q} . the value “ n {\displaystyle n} ” is simply: n = p × q {\displaystyle n=p\times q} . One must then choose an “ e {\displaystyle e} ” such that gcd ( e , ( p − 1 ) × ( q − 1 ) ) = 1 {\displaystyle \gcd(e,(p-1)\times (q-1))=1} . That is to say, e {\displaystyle e} and ( p − 1 ) × ( q − 1 ) {\displaystyle (p-1)\times (q-1)} are relatively prime to each other. The decryption value d {\displaystyle d} is then found by solving d × e ≡ 1 mod ( p − 1 ) × ( q − 1 ) {\displaystyle d\times e\equiv 1\mod (p-1)\times (q-1)} The security of the code is based on the secrecy of the Private Key (decryption exponent) “ d {\displaystyle d} ” and the difficulty in factoring “ n {\displaystyle n} ”. Research into RSA facilitated advances in factoring and a number of factoring challenges. Keys of 768 bits have been successfully factored. While factoring of keys of 1024 bits has not been demonstrated, NIST expected them to be factorable by 2010 and now recommends 2048 bit keys going forward (see Asymmetric algorithm key lengths or NIST 800-57 Pt 1 Revised Table 4: Recommended algorithms and minimum key sizes). Summary of the task requirements: Encrypt and Decrypt a short message or two using RSA with a demonstration key. Implement RSA do not call a library. Encode and decode the message using any reversible method of your choice (ASCII or a=1,..,z=26 are equally fine). Either support blocking or give an error if the message would require blocking) Demonstrate that your solution could support real keys by using a non-trivial key that requires large integer support (built-in or libraries). There is no need to include library code but it must be referenced unless it is built into the language. The following keys will be meet this requirement;however, they are NOT long enough to be considered secure: n = 9516311845790656153499716760847001433441357 e = 65537 d = 5617843187844953170308463622230283376298685 Messages can be hard-coded into the program, there is no need for elaborate input coding. Demonstrate that your implementation works by showing plaintext, intermediate results, encrypted text, and decrypted text. Warning Rosetta Code is not a place you should rely on for examples of code in critical roles, including security. Cryptographic routines should be validated before being used. For a discussion of limitations and please refer to Talk:RSA_code#Difference_from_practical_cryptographical_version.
#F.23
F#
  //Nigel Galloway February 12th., 2018 let RSA n g l = bigint.ModPow(l,n,g) let encrypt = RSA 65537I 9516311845790656153499716760847001433441357I let m_in = System.Text.Encoding.ASCII.GetBytes "The magic words are SQUEAMISH OSSIFRAGE"|>Array.chunkBySize 16|>Array.map(Array.fold(fun n g ->(n*256I)+(bigint(int g))) 0I) let n = Array.map encrypt m_in let decrypt = RSA 5617843187844953170308463622230283376298685I 9516311845790656153499716760847001433441357I let g = Array.map decrypt n let m_out = Array.collect(fun n->Array.unfold(fun n->if n>0I then Some(byte(int (n%256I)),n/256I) else None) n|>Array.rev) g|>System.Text.Encoding.ASCII.GetString printfn "'The magic words are SQUEAMISH OSSIFRAGE' as numbers -> %A\nEncrypted -> %A\nDecrypted -> %A\nAs text -> %A" m_in n g m_out  
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program rpg64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   .equ NBTIRAGES, 4 .equ NBTIRAGESOK, 3 .equ NBVALUES, 6 .equ TOTALMIN, 75 .equ MAXVALUE, 15 .equ NBMAXVALUE, 2   /*********************************/ /* Initialized data */ /*********************************/ .data sMessResult: .asciz "Value = @ \n" szCarriageReturn: .asciz "\n" sMessResultT: .asciz "Total = @ \n" sMessResultQ: .asciz "Values above 15 = @ \n"     .align 4 qGraine: .quad 123456789   /*********************************/ /* UnInitialized data */ /*********************************/ .bss tqTirages: .skip 8 * NBTIRAGES tqValues: .skip 8 * NBVALUES   sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program   1: // begin loop 1 mov x2,0 // counter value >15 mov x4,0 // loop indice mov x5,0 // total ldr x3,qAdrtqValues // table values address 2: bl genValue // call generate value str x0,[x3,x4,lsl 3] // store in table add x5,x5,x0 // compute total cmp x0,MAXVALUE // count value >= 15 add x6,x2,1 csel x2,x6,x2,ge add x4,x4,1 // increment indice cmp x4,NBVALUES // end ? blt 2b cmp x5,TOTALMIN // compare 75 blt 1b // < loop cmp x2,#NBMAXVALUE // compare value > 15 blt 1b // < loop ldr x0,qAdrtqValues // display values bl displayTable mov x0,x5 // total   ldr x1,qAdrsZoneConv // display value bl conversion10 // call conversion decimal ldr x0,qAdrsMessResultT ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message   mov x0,x2 // counter value > 15 ldr x1,qAdrsZoneConv // display value bl conversion10 // call conversion decimal ldr x0,qAdrsMessResultQ ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   qAdrsZoneConv: .quad sZoneConv qAdrszCarriageReturn: .quad szCarriageReturn qAdrsMessResult: .quad sMessResult qAdrsMessResultT: .quad sMessResultT qAdrsMessResultQ: .quad sMessResultQ qAdrtqValues: .quad tqValues /******************************************************************/ /* generate value */ /******************************************************************/ /* x0 returns the value */ genValue: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers mov x3,0 // indice loop ldr x1,qAdrtqTirages // table tirage address 1: mov x0,6 bl genereraleas // result 0 to 5 add x0,x0,#1 // for 1 to 6 str x0,[x1,x3,lsl 3] // store tirage add x3,x3,1 // increment indice cmp x3,NBTIRAGES // end ? blt 1b // no -> loop ldr x0,qAdrtqTirages // table tirage address mov x1,#0 // first item mov x2,#NBTIRAGES // number of tirages bl shellSort // sort table decreasing mov x3,#0 // raz indice loop mov x0,#0 // total ldr x1,qAdrtqTirages // table tirage address 2: ldr x2,[x1,x3,lsl 3] // read tirage add x0,x0,x2 // compute sum add x3,x3,1 // increment indice cmp x3,NBTIRAGESOK // end ? blt 2b 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 qAdrtqTirages: .quad tqTirages /***************************************************/ /* shell Sort decreasing */ /***************************************************/ /* x0 contains the address of table */ /* x1 contains the first element but not use !! */ /* this routine use first element at index zero !!! */ /* x2 contains the number of element */ shellSort: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers stp x4,x5,[sp,-16]! // save registers stp x6,x7,[sp,-16]! // save registers stp x8,x9,[sp,-16]! // save registers sub x2,x2,1 // index last item mov x1,x2 // init gap = last item 1: // start loop 1 lsr x1,x1,1 // gap = gap / 2 cbz x1,100f // if gap = 0 -> end mov x3,x1 // init loop indice 1 2: // start loop 2 ldr x4,[x0,x3,lsl 3] // load first value mov x5,x3 // init loop indice 2 3: // start loop 3 cmp x5,x1 // indice < gap blt 4f // yes -> end loop 2 sub x6,x5,x1 // index = indice - gap ldr x8,[x0,x6,lsl 3] // load second value cmp x4,x8 // compare values ble 4f str x8,[x0,x5,lsl 3] // store if > sub x5,x5,x1 // indice = indice - gap b 3b // and loop 4: // end loop 3 str x4,[x0,x5,lsl 3] // store value 1 at indice 2 add x3,x3,1 // increment indice 1 cmp x3,x2 // end ? ble 2b // no -> loop 2 b 1b // yes loop for new gap   100: // end function ldp x8,x9,[sp],16 // restaur 2 registers ldp x6,x7,[sp],16 // restaur 2 registers ldp x4,x5,[sp],16 // restaur 2 registers ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /******************************************************************/ /* Display table elements */ /******************************************************************/ /* x0 contains the address of table */ displayTable: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers mov x2,x0 // table address mov x3,0 1: // loop display table ldr x0,[x2,x3,lsl 3] ldr x1,qAdrsZoneConv // display value bl conversion10 // call function ldr x0,qAdrsMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message add x3,x3,1 cmp x3,NBVALUES - 1 ble 1b ldr x0,qAdrszCarriageReturn bl affichageMess 100: ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   /***************************************************/ /* Generation random number */ /* algo xorshift (see wikipedia) */ /***************************************************/ /* x0 contains limit */ genereraleas: stp x1,lr,[sp,-16]! // save registers stp x2,x3,[sp,-16]! // save registers cbz x0,100f mov x3,x0 // maxi value ldr x0,qAdrqGraine // graine ldr x2,[x0] lsl x1,x2,13 eor x2,x2,x1 lsr x1,x2,7 eor x2,x2,x1 lsl x1,x2,17 eor x1,x2,x1 str x1,[x0] // sauver graine udiv x2,x1,x3 // msub x0,x2,x3,x1 // compute result modulo limit   100: // end function ldp x2,x3,[sp],16 // restaur 2 registers ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30 /*****************************************************/ qAdrqGraine: .quad qGraine /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"  
http://rosettacode.org/wiki/RPG_attributes_generator
RPG attributes generator
RPG   =   Role Playing Game. You're running a tabletop RPG, and your players are creating characters. Each character has six core attributes: strength, dexterity, constitution, intelligence, wisdom, and charisma. One way of generating values for these attributes is to roll four, 6-sided dice (d6) and sum the three highest rolls, discarding the lowest roll. Some players like to assign values to their attributes in the order they're rolled. To ensure generated characters don't put players at a disadvantage, the following requirements must be satisfied: The total of all character attributes must be at least 75. At least two of the attributes must be at least 15. However, this can require a lot of manual dice rolling. A programatic solution would be much faster. Task Write a program that: Generates 4 random, whole values between 1 and 6. Saves the sum of the 3 largest values. Generates a total of 6 values this way. Displays the total, and all 6 values once finished. The order in which each value was generated must be preserved. The total of all 6 values must be at least 75. At least 2 of the values must be 15 or more.
#Action.21
Action!
TYPE Result=[BYTE success,sum,highCount] BYTE FUNC GenerateAttrib() BYTE i,v,min,sum   min=255 sum=0 FOR i=0 TO 3 DO v=Rand(6)+1 IF v<min THEN min=v FI sum==+v OD RETURN (sum-min)   PROC Generate(BYTE ARRAY a BYTE len Result POINTER res) BYTE i,v,count   res.highCount=0 res.sum=0 FOR i=0 TO len-1 DO v=GenerateAttrib() IF v>=15 THEN res.highCount==+1 FI res.sum==+v a(i)=v OD IF res.highCount<2 OR res.sum<75 THEN res.success=0 ELSE res.success=1 FI RETURN   PROC Main() DEFINE count="6" BYTE ARRAY a(count) Result res BYTE i   res.success=0 WHILE res.success=0 DO Generate(a,count,res) Print("attribs: ") FOR i=0 TO count-1 DO PrintB(a(i)) IF i<count-1 THEN Put(',) FI OD PrintF(" sum=%B highCount=%B ",res.sum,res.highCount) IF res.success THEN PrintE("success") ELSE PrintE("failed") FI OD RETURN
http://rosettacode.org/wiki/Sieve_of_Eratosthenes
Sieve of Eratosthenes
This task has been clarified. Its programming examples are in need of review to ensure that they still fit the requirements of the task. The Sieve of Eratosthenes is a simple algorithm that finds the prime numbers up to a given integer. Task Implement the   Sieve of Eratosthenes   algorithm, with the only allowed optimization that the outer loop can stop at the square root of the limit, and the inner loop may start at the square of the prime just found. That means especially that you shouldn't optimize by using pre-computed wheels, i.e. don't assume you need only to cross out odd numbers (wheel based on 2), numbers equal to 1 or 5 modulo 6 (wheel based on 2 and 3), or similar wheels based on low primes. If there's an easy way to add such a wheel based optimization, implement it as an alternative version. Note It is important that the sieve algorithm be the actual algorithm used to find prime numbers for the task. Related tasks   Emirp primes   count in factors   prime decomposition   factors of an integer   extensible prime generator   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division
#PL.2FI
PL/I
eratos: proc options (main) reorder;   dcl i fixed bin (31); dcl j fixed bin (31); dcl n fixed bin (31); dcl sn fixed bin (31);   dcl hbound builtin; dcl sqrt builtin;   dcl sysin file; dcl sysprint file;   get list (n); sn = sqrt(n);   begin; dcl primes(n) bit (1) aligned init ((*)((1)'1'b));   i = 2;   do while(i <= sn); do j = i ** 2 by i to hbound(primes, 1); /* Adding a test would just slow down processing! */ primes(j) = '0'b; end;   do i = i + 1 to sn until(primes(i)); end; end;   do i = 2 to hbound(primes, 1); if primes(i) then put data(i); end; end; end eratos;
http://rosettacode.org/wiki/Search_a_list_of_records
Search a list of records
Many programming languages provide convenient ways to look for a known value in a simple list of strings or numbers. But what if the elements of the list are themselves compound records/objects/data-structures, and the search condition is more complex than a simple equality test? Task[edit] Write a function/method/etc. that can find the first element in a given list matching a given condition. It should be as generic and reusable as possible. (Of course if your programming language already provides such a feature, you can use that instead of recreating it.) Then to demonstrate its functionality, create the data structure specified under #Data set, and perform on it the searches specified under #Test cases. Data set The data structure to be used contains the names and populations (in millions) of the 10 largest metropolitan areas in Africa, and looks as follows when represented in JSON: [ { "name": "Lagos", "population": 21.0 }, { "name": "Cairo", "population": 15.2 }, { "name": "Kinshasa-Brazzaville", "population": 11.3 }, { "name": "Greater Johannesburg", "population": 7.55 }, { "name": "Mogadishu", "population": 5.85 }, { "name": "Khartoum-Omdurman", "population": 4.98 }, { "name": "Dar Es Salaam", "population": 4.7 }, { "name": "Alexandria", "population": 4.58 }, { "name": "Abidjan", "population": 4.4 }, { "name": "Casablanca", "population": 3.98 } ] However, you shouldn't parse it from JSON, but rather represent it natively in your programming language. The top-level data structure should be an ordered collection (i.e. a list, array, vector, or similar). Each element in this list should be an associative collection that maps from keys to values (i.e. a struct, object, hash map, dictionary, or similar). Each of them has two entries: One string value with key "name", and one numeric value with key "population". You may rely on the list being sorted by population count, as long as you explain this to readers. If any of that is impossible or unreasonable in your programming language, then feel free to deviate, as long as you explain your reasons in a comment above your solution. Test cases Search Expected result Find the (zero-based) index of the first city in the list whose name is "Dar Es Salaam" 6 Find the name of the first city in this list whose population is less than 5 million Khartoum-Omdurman Find the population of the first city in this list whose name starts with the letter "A" 4.58 Guidance If your programming language supports higher-order programming, then the most elegant way to implement the requested functionality in a generic and reusable way, might be to write a function (maybe called "find_index" or similar), that takes two arguments: The list to search through. A function/lambda/closure (the so-called "predicate"), which will be applied in turn to each element in the list, and whose boolean return value defines whether that element matches the search requirement. If this is not the approach which would be most natural or idiomatic in your language, explain why, and show what is. Related tasks Search a list
#Scheme
Scheme
  (import (scheme base) (scheme char) (scheme write) (srfi 1) ; lists (srfi 132)) ; sorting   (define-record-type <places> ; compound data type is a record with two fields (make-place name population) place? (name place-name) (population place-population))   (define *items* (list-sort ; sort by decreasing population (lambda (r1 r2) (> (place-population r1) (place-population r2))) (list (make-place "Lagos" 21.0) (make-place "Cairo" 15.2) (make-place "Kinshasa-Brazzaville" 11.3) (make-place "Greater Johannesburg" 7.55) (make-place "Mogadishu" 5.85) (make-place "Khartoum-Omdurman" 4.98) (make-place "Dar Es Salaam" 4.7) (make-place "Alexandria" 4.58) (make-place "Abidjan" 4.4) (make-place "Casablanca" 3.98))))   ;; Find the (zero-based) index of the first city in the list ;; whose name is "Dar Es Salaam" (display "Test 1: ") (display (list-index (lambda (item) (string=? "Dar Es Salaam" (place-name item))) *items*)) (newline)   ;; Find the name of the first city in this list ;; whose population is less than 5 million (display "Test 2: ") (display (place-name (find (lambda (item) (< (place-population item) 5.0)) *items*))) (newline)   ;; Find the population of the first city in this list ;; whose name starts with the letter "A" (display "Test 3: ") (display (place-population (find (lambda (item) (char=? (string-ref (place-name item) 0) #\A)) *items*))) (newline)