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/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
#Lua
Lua
import strutils   # Requires 5 bytes of data store. const Hw = r""" /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/"""   #---------------------------------------------------------------------------------------------------   proc snusp(dsLen: int; code: string) = ## The interpreter.   var ds = newSeq[byte](dsLen) # Data store. dp = 0 # Data pointer. cs = code.splitLines() # Two dimensional code store. ipr, ipc = 0 # Instruction pointers in row ans column. dir = 0 # Direction (0 = right, 1 = down, 2 = left, 3 = up).   # Initialize instruction pointers. for r, row in cs: ipc = row.find('$') if ipc >= 0: ipr = r break   #.................................................................................................   func step() = ## Update the instruction pointers acccording to the direction.   if (dir and 1) == 0: inc ipc, 1 - (dir and 2) else: inc ipr, 1 - (dir and 2)   #.................................................................................................   # Interpreter loop. while ipr in 0..cs.high and ipc in 0..cs[ipr].high: case cs[ipr][ipc] of '>': inc dp of '<': dec dp of '+': inc ds[dp] of '-': dec ds[dp] of '.': stdout.write chr(ds[dp]) of ',': ds[dp] = byte(stdin.readLine()[0]) of '/': dir = not dir of '\\': dir = dir xor 1 of '!': step() of '?': (if ds[dp] == 0: step()) else: discard step()   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule: snusp(5, Hw)
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
import strutils   # Requires 5 bytes of data store. const Hw = r""" /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/"""   #---------------------------------------------------------------------------------------------------   proc snusp(dsLen: int; code: string) = ## The interpreter.   var ds = newSeq[byte](dsLen) # Data store. dp = 0 # Data pointer. cs = code.splitLines() # Two dimensional code store. ipr, ipc = 0 # Instruction pointers in row ans column. dir = 0 # Direction (0 = right, 1 = down, 2 = left, 3 = up).   # Initialize instruction pointers. for r, row in cs: ipc = row.find('$') if ipc >= 0: ipr = r break   #.................................................................................................   func step() = ## Update the instruction pointers acccording to the direction.   if (dir and 1) == 0: inc ipc, 1 - (dir and 2) else: inc ipr, 1 - (dir and 2)   #.................................................................................................   # Interpreter loop. while ipr in 0..cs.high and ipc in 0..cs[ipr].high: case cs[ipr][ipc] of '>': inc dp of '<': dec dp of '+': inc ds[dp] of '-': dec ds[dp] of '.': stdout.write chr(ds[dp]) of ',': ds[dp] = byte(stdin.readLine()[0]) of '/': dir = not dir of '\\': dir = dir xor 1 of '!': step() of '?': (if ds[dp] == 0: step()) else: discard step()   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule: snusp(5, Hw)
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
#Nim
Nim
import strutils   # Requires 5 bytes of data store. const Hw = r""" /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/"""   #---------------------------------------------------------------------------------------------------   proc snusp(dsLen: int; code: string) = ## The interpreter.   var ds = newSeq[byte](dsLen) # Data store. dp = 0 # Data pointer. cs = code.splitLines() # Two dimensional code store. ipr, ipc = 0 # Instruction pointers in row ans column. dir = 0 # Direction (0 = right, 1 = down, 2 = left, 3 = up).   # Initialize instruction pointers. for r, row in cs: ipc = row.find('$') if ipc >= 0: ipr = r break   #.................................................................................................   func step() = ## Update the instruction pointers acccording to the direction.   if (dir and 1) == 0: inc ipc, 1 - (dir and 2) else: inc ipr, 1 - (dir and 2)   #.................................................................................................   # Interpreter loop. while ipr in 0..cs.high and ipc in 0..cs[ipr].high: case cs[ipr][ipc] of '>': inc dp of '<': dec dp of '+': inc ds[dp] of '-': dec ds[dp] of '.': stdout.write chr(ds[dp]) of ',': ds[dp] = byte(stdin.readLine()[0]) of '/': dir = not dir of '\\': dir = dir xor 1 of '!': step() of '?': (if ds[dp] == 0: step()) else: discard step()   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule: snusp(5, Hw)
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
#OCaml
OCaml
with javascript_semantics integer id = 0, ipr = 1, ipc = 1 procedure step() if and_bits(id,1) == 0 then ipc += 1 - and_bits(id,2) else ipr += 1 - and_bits(id,2) end if end procedure procedure snusp(integer dlen, string s) sequence ds = repeat(0,dlen) -- data store integer dp = 1 -- data pointer -- remove leading '\n' from string if present s = trim_head(s,'\n') -- make 2 dimensional instruction store and set instruction pointers sequence cs = split(s,'\n') ipr = 1 ipc = 1 -- look for starting instruction for i=1 to length(cs) do ipc = find('$',cs[i]) if ipc then ipr = i exit end if end for id = 0 -- execute while ipr>=1 and ipr<=length(cs) and ipc>=1 and ipc<=length(cs[ipr]) do integer op = cs[ipr][ipc] switch op do case '>' : dp += 1 case '<' : dp -= 1 case '+' : ds[dp] += 1 case '-' : ds[dp] -= 1 case '.' : puts(1,ds[dp]) case ',' : ds[dp] = getc(0) case '/' : id = not_bits(id) case '\\': id = xor_bits(id,1) case '!' : step() case '?' : if ds[dp]=0 then step() end if end switch step() end while end procedure constant hw = """ /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/""" snusp(5, hw)
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Go
Go
package main   import "fmt"   type F func()   type If2 struct {cond1, cond2 bool}   func (i If2) else1(f F) If2 { if i.cond1 && !i.cond2 { f() } return i }   func (i If2) else2(f F) If2 { if i.cond2 && !i.cond1 { f() } return i }   func (i If2) else0(f F) If2 { if !i.cond1 && !i.cond2 { f() } return i }   func if2(cond1, cond2 bool, f F) If2 { if cond1 && cond2 { f() } return If2{cond1, cond2} }   func main() { a, b := 0, 1 if2 (a == 1, b == 3, func() { fmt.Println("a = 1 and b = 3") }).else1 (func() { fmt.Println("a = 1 and b <> 3") }).else2 (func() { fmt.Println("a <> 1 and b = 3") }).else0 (func() { fmt.Println("a <> 1 and b <> 3") })   // It's also possible to omit any (or all) of the 'else' clauses or to call them out of order a, b = 1, 0 if2 (a == 1, b == 3, func() { fmt.Println("a = 1 and b = 3") }).else0 (func() { fmt.Println("a <> 1 and b <> 3") }).else1 (func() { fmt.Println("a = 1 and b <> 3") }) }
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#REXX
REXX
/*REXX program demonstrates various ways of multiple exponentiations. */ /*┌────────────────────────────────────────────────────────────────────┐ │ The REXX language uses ** for exponentiation. │ │ Also, * * can be used. │ | and even */*power of*/* | └────────────────────────────────────────────────────────────────────┘*/   say ' 5**3**2 ───► ' 5**3**2 say ' (5**3)**2 ───► ' (5**3)**2 say ' 5**(3**2) ───► ' 5**(3**2) /*stick a fork in it, we're done.*/
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Ring
Ring
  see "(5^3)^2 =>" + pow(pow(5,3),2) + nl see "5^(3^2) =>" + pow(5,pow(3,2)) + nl  
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Ruby
Ruby
ar = ["5**3**2", "(5**3)**2", "5**(3**2)", "[5,3,2].inject(:**)"] ar.each{|exp| puts "#{exp}:\t#{eval exp}"}  
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#zkl
zkl
T(1,4,9,16,25,36,"37",49,64,81,100, True,self) .filter(fcn(n){(0).isType(n) and n.isOdd}) //-->L(1,9,25,49,81)
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Raku
Raku
for 1 .. 100 { when $_ %% (3 & 5) { say 'FizzBuzz'; } when $_ %% 3 { say 'Fizz'; } when $_ %% 5 { say 'Buzz'; } default { .say; } }
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#Icon_and_Unicon
Icon and Unicon
![2,3,5,7] | (nc := 11) | (nc +:= |wheel2345)
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Hoon
Hoon
|= n=@ud =/ a=@ud 0 =/ b=@ud 1 |- ?: =(n 0) a $(a b, b (add a b), n (dec n))
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   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   sequence: smallest number greater than previous term with exactly n divisors
#Raku
Raku
sub factors (Int $n) { (1..$n).grep($n %% *) }
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Common_Lisp
Common Lisp
import std.stdio, std.string;   void main(in string[] args) { if (args.length != 2 || args[1].length != args[1].countchars("hHqQ9+")) { writeln("Not valid HQ9+ code."); return; }   ulong accumulator; foreach (immutable c; args[1]) { final switch(c) { case 'Q', 'q': writeln(args[1]); break; case 'H', 'h': writeln("Hello, world!"); break; case '9': int bottles = 99; while (bottles > 1) { writeln(bottles, " bottles of beer on the wall,"); writeln(bottles, " bottles of beer."); writeln("Take one down, pass it around,"); if (--bottles > 1) writeln(bottles, " bottles of beer on the wall.\n"); } writeln("1 bottle of beer on the wall.\n"); break; case '+': accumulator++; break; } } }
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#ALGOL_68
ALGOL 68
MODE OBJ = STRUCT( INT value, STRUCT( STRING message, FLEX[0]STRING args, PROC(REF OBJ)BOOL u0, u1 ) exception );   PROC on u0 = (REF OBJ self, PROC (REF OBJ) BOOL mended)VOID: u0 OF exception OF self := mended;   PROC on u1 = (REF OBJ self, PROC (REF OBJ) BOOL mended)VOID: u1 OF exception OF self := mended;   PRIO INIT = 1, RAISE = 1;   OP INIT = (REF OBJ self, INT value)REF OBJ: ( value OF self := value; u0 OF exception OF self := u1 OF exception OF self := (REF OBJ skip)BOOL: FALSE; args OF exception OF self := message OF exception OF self := "OBJ Exception"; self );   OP RAISE = (REF OBJ self, PROC (REF OBJ) BOOL mended)VOID: IF NOT mended(self) THEN put(stand error, (message OF exception OF self+" not caught - stop", new line)); stop FI;   PROC (REF OBJ)VOID bar, baz; # early declaration is required by the ALGOL 68RS subset language #   PROC foo := VOID:( FOR value FROM 0 TO 1 DO REF OBJ i = LOC OBJ INIT value; on u0(i, (REF OBJ skip)BOOL: (GO TO except u0; SKIP )); bar(i); GO TO end on u0; except u0: print(("Function foo caught exception u0", new line)); end on u0: SKIP OD );   # PROC # bar := (REF OBJ i)VOID:( baz(i) # Nest those calls # );   # PROC # baz := (REF OBJ i)VOID: IF value OF i = 0 THEN i RAISE u0 OF exception OF i ELSE i RAISE u1 OF exception OF i FI;   foo
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#ABAP
ABAP
*&---------------------------------------------------------------------* *& Report ZEXEC_SYS_CMD *& *&---------------------------------------------------------------------* *& *& *&---------------------------------------------------------------------*   REPORT zexec_sys_cmd.   DATA: lv_opsys TYPE syst-opsys, lt_sxpgcotabe TYPE TABLE OF sxpgcotabe, ls_sxpgcotabe LIKE LINE OF lt_sxpgcotabe, ls_sxpgcolist TYPE sxpgcolist, lv_name TYPE sxpgcotabe-name, lv_opcommand TYPE sxpgcotabe-opcommand, lv_index TYPE c, lt_btcxpm TYPE TABLE OF btcxpm, ls_btcxpm LIKE LINE OF lt_btcxpm .   * Initialize lv_opsys = sy-opsys. CLEAR lt_sxpgcotabe[].   IF lv_opsys EQ 'Windows NT'. lv_opcommand = 'dir'. ELSE. lv_opcommand = 'ls'. ENDIF.   * Check commands SELECT * FROM sxpgcotabe INTO TABLE lt_sxpgcotabe WHERE opsystem EQ lv_opsys AND opcommand EQ lv_opcommand.   IF lt_sxpgcotabe IS INITIAL. CLEAR ls_sxpgcolist. CLEAR lv_name. WHILE lv_name IS INITIAL. * Don't mess with other users' commands lv_index = sy-index. CONCATENATE 'ZLS' lv_index INTO lv_name. SELECT * FROM sxpgcostab INTO ls_sxpgcotabe WHERE name EQ lv_name. ENDSELECT. IF sy-subrc = 0. CLEAR lv_name. ENDIF. ENDWHILE. ls_sxpgcolist-name = lv_name. ls_sxpgcolist-opsystem = lv_opsys. ls_sxpgcolist-opcommand = lv_opcommand. * Create own ls command when nothing is declared CALL FUNCTION 'SXPG_COMMAND_INSERT' EXPORTING command = ls_sxpgcolist public = 'X' EXCEPTIONS command_already_exists = 1 no_permission = 2 parameters_wrong = 3 foreign_lock = 4 system_failure = 5 OTHERS = 6. IF sy-subrc <> 0. * Implement suitable error handling here ELSE. * Hooray it worked! Let's try to call it CALL FUNCTION 'SXPG_COMMAND_EXECUTE_LONG' EXPORTING commandname = lv_name TABLES exec_protocol = lt_btcxpm EXCEPTIONS no_permission = 1 command_not_found = 2 parameters_too_long = 3 security_risk = 4 wrong_check_call_interface = 5 program_start_error = 6 program_termination_error = 7 x_error = 8 parameter_expected = 9 too_many_parameters = 10 illegal_command = 11 wrong_asynchronous_parameters = 12 cant_enq_tbtco_entry = 13 jobcount_generation_error = 14 OTHERS = 15. IF sy-subrc <> 0. * Implement suitable error handling here WRITE: 'Cant execute ls - '. CASE sy-subrc. WHEN 1. WRITE: / ' no permission!'. WHEN 2. WRITE: / ' command could not be created!'. WHEN 3. WRITE: / ' parameter list too long!'. WHEN 4. WRITE: / ' security risk!'. WHEN 5. WRITE: / ' wrong call of SXPG_COMMAND_EXECUTE_LONG!'. WHEN 6. WRITE: / ' command cant be started!'. WHEN 7. WRITE: / ' program terminated!'. WHEN 8. WRITE: / ' x_error!'. WHEN 9. WRITE: / ' parameter missing!'. WHEN 10. WRITE: / ' too many parameters!'. WHEN 11. WRITE: / ' illegal command!'. WHEN 12. WRITE: / ' wrong asynchronous parameters!'. WHEN 13. WRITE: / ' cant enqueue job!'. WHEN 14. WRITE: / ' cant create job!'. WHEN 15. WRITE: / ' unknown error!'. WHEN OTHERS. WRITE: / ' unknown error!'. ENDCASE. ELSE. LOOP AT lt_btcxpm INTO ls_btcxpm. WRITE: / ls_btcxpm. ENDLOOP. ENDIF. ENDIF. ENDIF.
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#AArch64_Assembly
AArch64 Assembly
  /* ARM assembly AARCH64 Raspberry PI 3B */ /* program factorial64.s */   /*******************************************/ /* Constantes file */ /*******************************************/ /* for this file see task include a file in language AArch64 assembly*/ .include "../includeConstantesARM64.inc"   /*********************************/ /* Initialized data */ /*********************************/ .data szMessLargeNumber: .asciz "Number N to large. \n" szMessNegNumber: .asciz "Number N is negative. \n"   szMessResult: .asciz "Resultat = @ \n" // message result   /*********************************/ /* UnInitialized data */ /*********************************/ .bss sZoneConv: .skip 24 /*********************************/ /* code section */ /*********************************/ .text .global main main: // entry of program   mov x0,#-5 bl factorial mov x0,#10 bl factorial mov x0,#20 bl factorial mov x0,#30 bl factorial   100: // standard end of the program mov x0,0 // return code mov x8,EXIT // request to exit program svc 0 // perform the system call   /********************************************/ /* calculation */ /********************************************/ /* x0 contains number N */ factorial: stp x1,lr,[sp,-16]! // save registers cmp x0,#0 blt 99f beq 100f cmp x0,#1 beq 100f bl calFactorial cmp x0,#-1 // overflow ? beq 98f ldr x1,qAdrsZoneConv bl conversion10 ldr x0,qAdrszMessResult ldr x1,qAdrsZoneConv bl strInsertAtCharInc // insert result at @ character bl affichageMess // display message b 100f   98: // display error message ldr x0,qAdrszMessLargeNumber bl affichageMess b 100f 99: // display error message ldr x0,qAdrszMessNegNumber bl affichageMess   100: ldp x1,lr,[sp],16 // restaur 2 registers ret // return to address lr x30   qAdrszMessNegNumber: .quad szMessNegNumber qAdrszMessLargeNumber: .quad szMessLargeNumber qAdrsZoneConv: .quad sZoneConv qAdrszMessResult: .quad szMessResult /******************************************************************/ /* calculation */ /******************************************************************/ /* x0 contains the number N */ calFactorial: cmp x0,1 // N = 1 ? beq 100f // yes -> return stp x20,lr,[sp,-16]! // save registers mov x20,x0 // save N in x20 sub x0,x0,1 // call function with N - 1 bl calFactorial cmp x0,-1 // error overflow ? beq 99f // yes -> return mul x10,x20,x0 // multiply result by N umulh x11,x20,x0 // x11 is the hi rd if <> 0 overflow cmp x11,0 mov x11,-1 // if overflow -1 -> x0 csel x0,x10,x11,eq // else x0 = x10   99: ldp x20,lr,[sp],16 // restaur 2 registers 100: ret // return to address lr x30 /********************************************************/ /* File Include fonctions */ /********************************************************/ /* for this file see task include a file in language AArch64 assembly */ .include "../includeARM64.inc"    
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Chef
Chef
(defn ** [x n] (reduce * (repeat n x)))
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Clojure
Clojure
(defn ** [x n] (reduce * (repeat n x)))
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#Io
Io
HailStone := Object clone HailStone sequence := method(n, if(n < 1, Exception raise("hailstone: expect n >= 1 not #{n}" interpolate)) n = n floor // make sure integer value stones := list(n) while (n != 1, n = if(n isEven, n/2, 3*n + 1) stones append(n) ) stones )   if( isLaunchScript, out := HailStone sequence(27) writeln("hailstone(27) has length ",out size,": ", out slice(0,4) join(" ")," ... ",out slice(-4) join(" "))   maxSize := 0 maxN := 0 for(n, 1, 100000-1, out = HailStone sequence(n) if(out size > maxSize, maxSize = out size maxN = n ) )   writeln("For numbers < 100,000, ", maxN, " has the longest sequence of ", maxSize, " elements.") )
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#J
J
hailseq=: -:`(1 3&p.)@.(2&|) ^:(1 ~: ]) ^:a:"0 9!:29]1 9!:27'main 0' main=:3 :0 smoutput 'Hailstone sequence for the number 27' smoutput hailseq 27 smoutput '' smoutput 'Finding number with longest hailstone sequence which is' smoutput 'less than 100000 (and finding that sequence length):' smoutput (I.@(= >./),>./) #@hailseq i.1e5 )
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#Ruby
Ruby
inf = 1.0 / 0.0 # or Float::INFINITY nan = 0.0 / 0.0 # or Float::NAN   expression = [ "1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0", "inf + 1", "5 - inf", "inf * 5", "inf / 5", "inf * 0", "1.0 / inf", "-1.0 / inf", "inf + inf", "inf - inf", "inf * inf", "inf / inf", "inf * 0.0", " 0 < inf", "inf == inf", "nan + 1", "nan * 5", "nan - nan", "nan * inf", "- nan", "nan == nan", "nan > 0", "nan < 0", "nan == 0", "nan <=> 0.0", "0.0 == -0.0", ]   expression.each do |exp| puts "%15s => %p" % [exp, eval(exp)] end
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
#Perl
Perl
with javascript_semantics integer id = 0, ipr = 1, ipc = 1 procedure step() if and_bits(id,1) == 0 then ipc += 1 - and_bits(id,2) else ipr += 1 - and_bits(id,2) end if end procedure procedure snusp(integer dlen, string s) sequence ds = repeat(0,dlen) -- data store integer dp = 1 -- data pointer -- remove leading '\n' from string if present s = trim_head(s,'\n') -- make 2 dimensional instruction store and set instruction pointers sequence cs = split(s,'\n') ipr = 1 ipc = 1 -- look for starting instruction for i=1 to length(cs) do ipc = find('$',cs[i]) if ipc then ipr = i exit end if end for id = 0 -- execute while ipr>=1 and ipr<=length(cs) and ipc>=1 and ipc<=length(cs[ipr]) do integer op = cs[ipr][ipc] switch op do case '>' : dp += 1 case '<' : dp -= 1 case '+' : ds[dp] += 1 case '-' : ds[dp] -= 1 case '.' : puts(1,ds[dp]) case ',' : ds[dp] = getc(0) case '/' : id = not_bits(id) case '\\': id = xor_bits(id,1) case '!' : step() case '?' : if ds[dp]=0 then step() end if end switch step() end while end procedure constant hw = """ /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/""" snusp(5, hw)
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Haskell
Haskell
if2 :: Bool -> Bool -> a -> a -> a -> a -> a if2 p1 p2 e12 e1 e2 e = if p1 then if p2 then e12 else e1 else if p2 then e2 else e   main = print $ if2 True False (error "TT") "TF" (error "FT") (error "FF")  
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Rust
Rust
fn main() { println!("5**3**2 = {:7}", 5u32.pow(3).pow(2)); println!("(5**3)**2 = {:7}", (5u32.pow(3)).pow(2)); println!("5**(3**2) = {:7}", 5u32.pow(3u32.pow(2))); }
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Scala
Scala
$ include "seed7_05.s7i";   const proc: main is func begin writeln("5**3**2 = " <& 5**3**2); writeln("(5**3)**2 = " <& (5**3)**2); writeln("5**(3**2) = " <& 5**(3**2)); end func;
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Seed7
Seed7
$ include "seed7_05.s7i";   const proc: main is func begin writeln("5**3**2 = " <& 5**3**2); writeln("(5**3)**2 = " <& (5**3)**2); writeln("5**(3**2) = " <& 5**(3**2)); end func;
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Sidef
Sidef
var a = [ '5**3**2', '(5**3)**2', '5**(3**2)', '5 ** 3 ** 2', '5 ** 3**2', '5**3 ** 2', '[5,3,2]«**»', ]   a.each {|e| "%-12s == %s\n".printf(e, eval(e)) }
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#ZX_Spectrum_Basic
ZX Spectrum Basic
10 LET items=100: LET filtered=0 20 DIM a(items) 30 FOR i=1 TO items 40 LET a(i)=INT (RND*items) 50 NEXT i 60 FOR i=1 TO items 70 IF FN m(a(i),2)=0 THEN LET filtered=filtered+1: LET a(filtered)=a(i) 80 NEXT i 90 DIM b(filtered) 100 FOR i=1 TO filtered 110 LET b(i)=a(i): PRINT b(i);" "; 120 NEXT i 130 DIM a(1): REM To free memory (well, almost all) 140 DEF FN m(a,b)=a-INT (a/b)*b
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#RapidQ
RapidQ
FOR i=1 TO 100 t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "") PRINT IIF(LEN(t$), t$, i) NEXT i
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#J
J
p:i.20 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 (#~ >:&100)i.&.(p:inv) 150 101 103 107 109 113 127 131 137 139 149 #(#~ >:&7700)i.&.(p:inv) 8000 30 p:10000-1 104729
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Hope
Hope
dec f : num -> num; --- f 0 <= 0; --- f 1 <= 1; --- f(n+2) <= f n + f(n+1);
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   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   sequence: smallest number greater than previous term with exactly n divisors
#REALbasic
REALbasic
Function factors(num As UInt64) As UInt64() 'This function accepts an unsigned 64 bit integer as input and returns an array of unsigned 64 bit integers Dim result() As UInt64 Dim iFactor As UInt64 = 1 While iFactor <= num/2 'Since a factor will never be larger than half of the number If num Mod iFactor = 0 Then result.Append(iFactor) End If iFactor = iFactor + 1 Wend result.Append(num) 'Since a given number is always a factor of itself Return result End Function
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#D
D
import std.stdio, std.string;   void main(in string[] args) { if (args.length != 2 || args[1].length != args[1].countchars("hHqQ9+")) { writeln("Not valid HQ9+ code."); return; }   ulong accumulator; foreach (immutable c; args[1]) { final switch(c) { case 'Q', 'q': writeln(args[1]); break; case 'H', 'h': writeln("Hello, world!"); break; case '9': int bottles = 99; while (bottles > 1) { writeln(bottles, " bottles of beer on the wall,"); writeln(bottles, " bottles of beer."); writeln("Take one down, pass it around,"); if (--bottles > 1) writeln(bottles, " bottles of beer on the wall.\n"); } writeln("1 bottle of beer on the wall.\n"); break; case '+': accumulator++; break; } } }
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#APL
APL
:Namespace Traps ⍝ Traps (exceptions) are just numbers ⍝ 500-999 are reserved for the user U0 U1←900 901   ⍝ Catch ∇foo;i  :For i :In ⍳2  :Trap U0 bar i  :Else ⎕←'foo caught U0'  :EndTrap  :EndFor ∇   ⍝ Throw ∇bar i ⎕SIGNAL U0 U1[i] ∇ :EndNamespace
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#AutoHotkey
AutoHotkey
global U0 := Exception("First Exception") global U1 := Exception("Second Exception")   foo()   foo(){ try bar() catch e MsgBox % "An exception was raised: " e.Message bar() }   bar(){ baz() }   baz(){ static calls := 0 if ( ++calls = 1 ) throw U0 else if ( calls = 2 ) throw U1 }
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#11l
11l
T SillyError String message F (message) .message = message   X.try X SillyError(‘egg’) X.catch SillyError se print(se.message)
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Ada
Ada
with POSIX.Unsafe_Process_Primitives;   procedure Execute_A_System_Command is Arguments : POSIX.POSIX_String_List; begin POSIX.Append (Arguments, "ls"); POSIX.Unsafe_Process_Primitives.Exec_Search ("ls", Arguments); end Execute_A_System_Command;
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Aikido
Aikido
  var lines = system ("ls") foreach line lines { println (line) }  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#ABAP
ABAP
form factorial using iv_val type i. data: lv_res type i value 1. do iv_val times. multiply lv_res by sy-index. enddo.   iv_val = lv_res. endform.
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Common_Lisp
Common Lisp
(defun my-expt-do (a b) (do ((x 1 (* x a)) (y 0 (+ y 1))) ((= y b) x)))
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#D
D
import std.stdio, std.conv;   struct Number(T) { T x; // base alias x this; string toString() const { return text(x); }   Number opBinary(string op)(in int exponent) const pure nothrow @nogc if (op == "^^") in { if (exponent < 0) assert (x != 0, "Division by zero"); } body { debug puts("opBinary ^^");   int zerodir; T factor; if (exponent < 0) { zerodir = +1; factor = T(1) / x; } else { zerodir = -1; factor = x; }   T result = 1; int e = exponent; while (e != 0) if (e % 2 != 0) { result *= factor; e += zerodir; } else { factor *= factor; e /= 2; }   return Number(result); } }   void main() { alias Double = Number!double; writeln(Double(2.5) ^^ 5);   alias Int = Number!int; writeln(Int(3) ^^ 3); writeln(Int(0) ^^ -2); // Division by zero. }
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#Java
Java
  import java.util.ArrayList; import java.util.List;   // task 1 public class HailstoneSequence {   public static void main(String[] args) { // task 2 int n = 27; List<Long> sequence27 = hailstoneSequence(n); System.out.printf("Hailstone sequence for %d has a length of %d:%nhailstone(%d) = %s%n", n, sequence27.size(), n, sequence27);   // task 3 int maxN = 0; int maxLength = 0; for ( int i = 1 ; i < 100_000 ; i++ ) { int seqLength = hailstoneSequence(i).size(); if ( seqLength > maxLength ) { maxLength = seqLength; maxN = i; } } System.out.printf("Longest hailstone sequence less than 100,000: hailstone(%d).length() = %d", maxN, maxLength); }   public static List<Long> hailstoneSequence(long n) { if ( n <= 0 ) { throw new IllegalArgumentException("Must be grater than or equal to zero."); } List<Long> sequence = new ArrayList<>(); sequence.add(n); while ( n > 1 ) { if ( (n & 1) == 0 ) { n /= 2; } else { n = 3 * n + 1; } sequence.add(n); } return sequence; }   }  
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#Rust
Rust
fn main() { let inf: f64 = 1. / 0.; // or std::f64::INFINITY let minus_inf: f64 = -1. / 0.; // or std::f64::NEG_INFINITY let minus_zero: f64 = -1. / inf; // or -0.0 let nan: f64 = 0. / 0.; // or std::f64::NAN // or std::f32 for the above println!("positive infinity: {:+}", inf); println!("negative infinity: {:+}", minus_inf); println!("negative zero: {:+?}", minus_zero); println!("not a number: {:+}", nan); println!(); println!("+inf + 2.0 = {:+}", inf + 2.); println!("+inf - 10.0 = {:+}", inf - 10.); println!("+inf + -inf = {:+}", inf + minus_inf); println!("0.0 * inf = {:+}", 0. * inf); println!("1.0 / -0.0 = {:+}", 1. / -0.); println!("NaN + 1.0 = {:+}", nan + 1.); println!("NaN + NaN = {:+}", nan + nan); println!(); println!("NaN == NaN = {}", nan == nan); println!("0.0 == -0.0 = {}", 0. == -0.); }
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#S-lang
S-lang
foreach $1 ([{-0.0}, {_Inf, "1.0/0"}, {-_Inf, "-1.0/0"}, {_NaN}]) { () = printf("%S", $1[0]); if (length($1) > 1) () = printf("\t%S\n", eval($1[1])); else () = printf("\n"); }
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
#Phix
Phix
with javascript_semantics integer id = 0, ipr = 1, ipc = 1 procedure step() if and_bits(id,1) == 0 then ipc += 1 - and_bits(id,2) else ipr += 1 - and_bits(id,2) end if end procedure procedure snusp(integer dlen, string s) sequence ds = repeat(0,dlen) -- data store integer dp = 1 -- data pointer -- remove leading '\n' from string if present s = trim_head(s,'\n') -- make 2 dimensional instruction store and set instruction pointers sequence cs = split(s,'\n') ipr = 1 ipc = 1 -- look for starting instruction for i=1 to length(cs) do ipc = find('$',cs[i]) if ipc then ipr = i exit end if end for id = 0 -- execute while ipr>=1 and ipr<=length(cs) and ipc>=1 and ipc<=length(cs[ipr]) do integer op = cs[ipr][ipc] switch op do case '>' : dp += 1 case '<' : dp -= 1 case '+' : ds[dp] += 1 case '-' : ds[dp] -= 1 case '.' : puts(1,ds[dp]) case ',' : ds[dp] = getc(0) case '/' : id = not_bits(id) case '\\': id = xor_bits(id,1) case '!' : step() case '?' : if ds[dp]=0 then step() end if end switch step() end while end procedure constant hw = """ /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/""" snusp(5, hw)
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Icon_and_Unicon
Icon and Unicon
procedure main(A) if2 { (A[1] = A[2]), (A[3] = A[4]), # Use PDCO with all three else clauses write("1: both true"), write("1: only first true"), write("1: only second true"), write("1: neither true") } if2 { (A[1] = A[2]), (A[3] = A[4]), # Use same PDCO with only one else clause write("2: both true"), write("2: only first true"), } end   procedure if2(A) # The double-conditional PDCO suspend if @A[1] then if @A[2] then |@A[3] # Run-err if missing 'then' clause else @\A[4] # (all else clauses are optional) else if @A[2] then |@\A[5] else |@\A[6] end
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Simula
Simula
OutText("5** 3 **2: "); OutInt(5** 3 **2, 0); Outimage; OutText("(5**3)**2: "); OutInt((5**3)**2, 0); Outimage; OutText("5**(3**2): "); OutInt(5**(3**2), 0); Outimage
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Smalltalk
Smalltalk
Transcript show:'5**3**2 => '; showCR: 5**3**2. Transcript show:'(5**3)**2 => '; showCR: (5**3)**2. Transcript show:'5**(3**2) => '; showCR: 5**(3**2).
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Stata
Stata
. di (5^3^2) 15625   . di ((5^3)^2) 15625   . di (5^(3^2)) 1953125
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Swift
Swift
precedencegroup ExponentiationPrecedence { associativity: left higherThan: MultiplicationPrecedence }   infix operator ** : ExponentiationPrecedence   @inlinable public func ** <T: BinaryInteger>(lhs: T, rhs: T) -> T { guard lhs != 0 else { return 1 }   var x = lhs var n = rhs var y = T(1)   while n > 1 { switch n & 1 { case 0: n /= 2 case 1: y *= x n = (n - 1) / 2 case _: fatalError() }   x *= x }   return x * y }   print(5 ** 3 ** 2) print((5 ** 3) ** 2) print(5 ** (3 ** 2))
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Rascal
Rascal
import IO;   public void fizzbuzz() { for(int n <- [1 .. 100]){ fb = ((n % 3 == 0) ? "Fizz" : "") + ((n % 5 == 0) ? "Buzz" : ""); println((fb == "") ?"<n>" : fb); } }
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#Java
Java
import java.util.*;   public class PrimeGenerator { private int limit_; private int index_ = 0; private int increment_; private int count_ = 0; private List<Integer> primes_ = new ArrayList<>(); private BitSet sieve_ = new BitSet(); private int sieveLimit_ = 0;   public PrimeGenerator(int initialLimit, int increment) { limit_ = nextOddNumber(initialLimit); increment_ = increment; primes_.add(2); findPrimes(3); }   public int nextPrime() { if (index_ == primes_.size()) { if (Integer.MAX_VALUE - increment_ < limit_) return 0; int start = limit_ + 2; limit_ = nextOddNumber(limit_ + increment_); primes_.clear(); findPrimes(start); } ++count_; return primes_.get(index_++); }   public int count() { return count_; }   private void findPrimes(int start) { index_ = 0; int newLimit = sqrt(limit_); for (int p = 3; p * p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((sieveLimit_ + p - 1)/p)); for (; q <= newLimit; q += 2*p) sieve_.set(q/2 - 1, true); } sieveLimit_ = newLimit; int count = (limit_ - start)/2 + 1; BitSet composite = new BitSet(count); for (int p = 3; p <= newLimit; p += 2) { if (sieve_.get(p/2 - 1)) continue; int q = p * Math.max(p, nextOddNumber((start + p - 1)/p)) - start; q /= 2; for (; q >= 0 && q < count; q += p) composite.set(q, true); } for (int p = 0; p < count; ++p) { if (!composite.get(p)) primes_.add(p * 2 + start); } }   private static int sqrt(int n) { return nextOddNumber((int)Math.sqrt(n)); }   private static int nextOddNumber(int n) { return 1 + 2 * (n/2); }   public static void main(String[] args) { PrimeGenerator pgen = new PrimeGenerator(20, 200000); System.out.println("First 20 primes:"); for (int i = 0; i < 20; ++i) { if (i > 0) System.out.print(", "); System.out.print(pgen.nextPrime()); } System.out.println(); System.out.println("Primes between 100 and 150:"); for (int i = 0; ; ) { int prime = pgen.nextPrime(); if (prime > 150) break; if (prime >= 100) { if (i++ != 0) System.out.print(", "); System.out.print(prime); } } System.out.println(); int count = 0; for (;;) { int prime = pgen.nextPrime(); if (prime > 8000) break; if (prime >= 7700) ++count; } System.out.println("Number of primes between 7700 and 8000: " + count); int n = 10000; for (;;) { int prime = pgen.nextPrime(); if (prime == 0) { System.out.println("Can't generate any more primes."); break; } if (pgen.count() == n) { System.out.println(n + "th prime: " + prime); n *= 10; } } } }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Hy
Hy
(defn fib [n] (if (< n 2) n (+ (fib (- n 2)) (fib (- n 1)))))
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   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   sequence: smallest number greater than previous term with exactly n divisors
#Red
Red
Red []   factors: function [n [integer!]] [ n: absolute n collect [ repeat i (sq: sqrt n) - 1 [ if n % i = 0 [ keep i keep n / i ] ] if sq = sq: to-integer sq [keep sq] ] ]   foreach num [ 24 -64  ; negative 64  ; square 101  ; prime 123456789 ; large ][ print mold/flat sort factors num ]
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   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   sequence: smallest number greater than previous term with exactly n divisors
#Relation
Relation
  program factors(num) relation fact insert 1 set i = 2 while i < num / 2 if num / i = floor(num/i) insert i end if set i = i + 1 end while insert num print end program  
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Delphi
Delphi
  uses System.SysUtils;   procedure runCode(code: string); var c_len, i, bottles: Integer; accumulator: Cardinal; begin c_len := Length(code); accumulator := 0; for i := 1 to c_len do begin case code[i] of 'Q': writeln(code); 'H': Writeln('Hello, world!'); '9': begin bottles := 99; repeat writeln(format('%d bottles of beer on the wall', [bottles])); writeln(format('%d bottles of beer', [bottles])); Writeln('Take one down, pass it around'); dec(bottles); writeln(format('%d bottles of beer on the wall' + sLineBreak, [bottles])); until (bottles <= 0); end; '+': inc(accumulator); end; end; end;
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#11l
11l
T Rule String pattern String replacement Bool terminating F (pattern, replacement, terminating) .pattern = pattern .replacement = replacement .terminating = terminating   F parse(rules) [Rule] result L(line) rules.split("\n") I line.starts_with(‘#’) L.continue I line.trim(‘ ’).empty L.continue   V (pat, rep) = line.split(‘ -> ’)   V terminating = 0B I rep.starts_with(‘.’) rep = rep[1..] terminating = 1B   result.append(Rule(pat, rep, terminating)) R result   F apply(text, rules) V result = text V changed = 1B   L changed == 1B changed = 0B L(rule) rules I rule.pattern C result result = result.replace(rule.pattern, rule.replacement) I rule.terminating R result changed = 1B L.break   R result   V SampleTexts = [‘I bought a B of As from T S.’, ‘I bought a B of As from T S.’, ‘I bought a B of As W my Bgage from T S.’, ‘_1111*11111_’, ‘000000A000000’]   V RuleSets = [ ‘# This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule’,   ‘# Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule’,   ‘# BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule’,   ‘### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> ’,   ‘# Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11’]   L(ruleset) RuleSets V rules = parse(ruleset) print(apply(SampleTexts[L.index], rules))
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#BBC_BASIC
BBC BASIC
REM Allocate error numbers: U0& = 123 U1& = 124   PROCfoo END   DEF PROCfoo ON ERROR LOCAL IF ERR = U0& THEN PRINT "Exception U0 caught in foo" ELSE \ \ RESTORE ERROR : ERROR ERR, REPORT$ PROCbar PROCbar ENDPROC   DEF PROCbar PROCbaz ENDPROC   DEF PROCbaz PRIVATE called% called% += 1 CASE called% OF WHEN 1: ERROR U0&, "Exception U0 thrown" WHEN 2: ERROR U1&, "Exception U1 thrown" ENDCASE ENDPROC  
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#C
C
#include <stdio.h> #include <stdlib.h>   typedef struct exception { int extype; char what[128]; } exception;   typedef struct exception_ctx { exception * exs; int size; int pos; } exception_ctx;   exception_ctx * Create_Ex_Ctx(int length) { const int safety = 8; // alignment precaution. char * tmp = (char*) malloc(safety+sizeof(exception_ctx)+sizeof(exception)*length); if (! tmp) return NULL; exception_ctx * ctx = (exception_ctx*)tmp; ctx->size = length; ctx->pos = -1; ctx->exs = (exception*) (tmp + sizeof(exception_ctx)); return ctx; }   void Free_Ex_Ctx(exception_ctx * ctx) { free(ctx); }   int Has_Ex(exception_ctx * ctx) { return (ctx->pos >= 0) ? 1 : 0; }   int Is_Ex_Type(exception_ctx * exctx, int extype) { return (exctx->pos >= 0 && exctx->exs[exctx->pos].extype == extype) ? 1 : 0; }   void Pop_Ex(exception_ctx * ctx) { if (ctx->pos >= 0) --ctx->pos; }   const char * Get_What(exception_ctx * ctx) { if (ctx->pos >= 0) return ctx->exs[ctx->pos].what; return NULL; }   int Push_Ex(exception_ctx * exctx, int extype, const char * msg) { if (++exctx->pos == exctx->size) { // Use last slot and report error. --exctx->pos; fprintf(stderr, "*** Error: Overflow in exception context.\n"); } snprintf(exctx->exs[exctx->pos].what, sizeof(exctx->exs[0].what), "%s", msg); exctx->exs[exctx->pos].extype = extype; return -1; }   //////////////////////////////////////////////////////////////////////   exception_ctx * GLOBALEX = NULL; enum { U0_DRINK_ERROR = 10, U1_ANGRYBARTENDER_ERROR };   void baz(int n) { if (! n) { Push_Ex(GLOBALEX, U0_DRINK_ERROR , "U0 Drink Error. Insufficient drinks in bar Baz."); return; } else { Push_Ex(GLOBALEX, U1_ANGRYBARTENDER_ERROR , "U1 Bartender Error. Bartender kicked customer out of bar Baz."); return; } }   void bar(int n) { fprintf(stdout, "Bar door is open.\n"); baz(n); if (Has_Ex(GLOBALEX)) goto bar_cleanup; fprintf(stdout, "Baz has been called without errors.\n"); bar_cleanup: fprintf(stdout, "Bar door is closed.\n"); }   void foo() { fprintf(stdout, "Foo entering bar.\n"); bar(0); while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); Pop_Ex(GLOBALEX); } if (Has_Ex(GLOBALEX)) return; fprintf(stdout, "Foo left the bar.\n"); fprintf(stdout, "Foo entering bar again.\n"); bar(1); while (Is_Ex_Type(GLOBALEX, U0_DRINK_ERROR)) { fprintf(stderr, "I am foo() and I deaall wrth U0 DriNk Errors with my own bottle... GOT oNE! [%s]\n", Get_What(GLOBALEX)); Pop_Ex(GLOBALEX); } if (Has_Ex(GLOBALEX)) return; fprintf(stdout, "Foo left the bar.\n"); }     int main(int argc, char ** argv) { exception_ctx * ctx = Create_Ex_Ctx(5); GLOBALEX = ctx;   foo(); if (Has_Ex(ctx)) goto main_ex;   fprintf(stdout, "No errors encountered.\n");   main_ex: while (Has_Ex(ctx)) { fprintf(stderr, "*** Error: %s\n", Get_What(ctx)); Pop_Ex(ctx); } Free_Ex_Ctx(ctx); return 0; }      
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#8086_Assembly
8086 Assembly
;syscall for creating a new file. mov dx,offset filename mov cx,0 mov ah,5Bh int 21h ;if error occurs, will return carry set and error code in ax ;Error code 03h = path not found ;Error code 04h = Too many open files ;Error code 05h = Access denied ;Error code 50h = File already exists   jnc noError ;continue with program   cmp ax,03h je PathNotFoundError ;unimplemented exception handler   cmp ax,04h je TooManyOpenFilesError   cmp ax,05h je AccessDeniedError   cmp ax,50h je FileAlreadyExistsError   noError:
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Ada
Ada
Foo_Error : exception;
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Aime
Aime
sshell ss;   ss.argv.insert("ls");   o_(ss.link);  
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#ALGOL_68
ALGOL 68
system("ls")
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#Action.21
Action!
CARD FUNC Factorial(INT n BYTE POINTER err) CARD i,res   IF n<0 THEN err^=1 RETURN (0) ELSEIF n>8 THEN err^=2 RETURN (0) FI   res=1 FOR i=2 TO n DO res=res*i OD   err^=0 RETURN (res)   PROC Main() INT i,f BYTE err   FOR i=-2 TO 10 DO f=Factorial(i,@err)   IF err=0 THEN PrintF("%I!=%U%E",i,f) ELSEIF err=1 THEN PrintF("%I is negative value%E",i) ELSE PrintF("%I! is to big%E",i) FI OD RETURN
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Delphi
Delphi
  program Exponentiation_operator;   {$APPTYPE CONSOLE}   uses System.SysUtils;   type TDouble = record Value: Double; class operator Implicit(a: TDouble): Double; class operator Implicit(a: Double): TDouble; class operator Implicit(a: TDouble): string; class operator LogicalXor(a: TDouble; b: Integer): TDouble; end;   TInteger = record Value: Integer; class operator Implicit(a: TInteger): Integer; class operator Implicit(a: Integer): TInteger; class operator Implicit(a: TInteger): string; class operator LogicalXor(a: TInteger; b: Integer): TInteger; end;   { TDouble }   class operator TDouble.Implicit(a: TDouble): Double; begin Result := a.Value; end;   class operator TDouble.Implicit(a: Double): TDouble; begin Result.Value := a; end;   class operator TDouble.Implicit(a: TDouble): string; begin Result := a.Value.ToString; end;   class operator TDouble.LogicalXor(a: TDouble; b: Integer): TDouble; var i: Integer; val: Double; begin val := 1; for i := 1 to b do val := val * a.Value; Result.Value := val; end;   { TInteger }   class operator TInteger.Implicit(a: TInteger): Integer; begin Result := a.Value; end;   class operator TInteger.Implicit(a: Integer): TInteger; begin Result.Value := a; end;   class operator TInteger.Implicit(a: TInteger): string; begin Result := a.Value.ToString; end;   class operator TInteger.LogicalXor(a: TInteger; b: Integer): TInteger; var val, i: Integer; begin if b < 0 then raise Exception.Create('Expoent must be greater or equal zero');   val := 1; for i := 1 to b do val := val * a.Value; Result.Value := val; end;   procedure Print(s: string); begin Write(s); end;   var valF: TDouble; valI: TInteger;   begin valF := 5.5; valI := 5;   // Delphi don't have "**" or "^" operator for overload, // "xor" operator has used instead Print('5^5 = '); Print(valI xor 5); print(#10);   Print('5.5^5 = '); Print(valF xor 5); print(#10);   readln; end.
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#Julia
Julia
  ############### in file hailstone.jl ############### module Hailstone   function hailstone(n) ret = [n] while n > 1 if n & 1 > 0 n = 3n + 1 else n = Int(n//2) end append!(ret, n) end return ret end   export hailstone   end   if PROGRAM_FILE == "hailstone.jl" using Hailstone h = hailstone(27) n = length(h) println("The sequence of hailstone(27) is:\n $h.\nThis sequence is of length $n. It starts with $(h[1:4]) and ends with $(h[n-3:end]).") end ############ in file moduletest.jl #################### include("hailstone.jl") using Hailstone function countstones(mi, mx) lengths2occurences = Dict() mostfreq = mi maxcount = 1 for i in mi:mx h = hailstone(i) n = length(h) if haskey(lengths2occurences, n) newoccurences = lengths2occurences[n] + 1 if newoccurences > maxcount maxcount = newoccurences mostfreq = n end lengths2occurences[n] = newoccurences else lengths2occurences[n] = 1 end end mostfreq, maxcount end   nlen, cnt = countstones(1,99999)   print("The most common hailstone sequence length for hailstone(n) for 1 <= n < 100000 is $nlen, which occurs $cnt times.")  
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#Limbo
Limbo
implement Execlib;   include "sys.m"; sys: Sys; include "draw.m";   Execlib: module { init: fn(ctxt: ref Draw->Context, args: list of string); hailstone: fn(i: big): list of big; };   init(nil: ref Draw->Context, nil: list of string) { sys = load Sys Sys->PATH;   seq := hailstone(big 27); l := len seq;   sys->print("hailstone(27): "); for(i := 0; i < 4; i++) { sys->print("%bd, ", hd seq); seq = tl seq; } sys->print("⋯");   while(len seq > 4) seq = tl seq;   while(seq != nil) { sys->print(", %bd", hd seq); seq = tl seq; } sys->print(" (length %d)\n", l);   max := 1; maxn := big 1; for(n := big 2; n < big 100000; n++) { cur := len hailstone(n); if(cur > max) { max = cur; maxn = n; } } sys->print("hailstone(%bd) has length %d\n", maxn, max); }   hailstone(i: big): list of big { if(i == big 1) return big 1 :: nil; if(i % big 2 == big 0) return i :: hailstone(i / big 2); return i :: hailstone(big 3 * i + big 1); }  
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#Lua
Lua
#!/usr/bin/env luajit bit32=bit32 or bit local lib={ hailstone=function(n) local seq={n} while n>1 do n=bit32.band(n,1)==1 and 3*n+1 or n/2 seq[#seq+1]=n end return seq end }   if arg[0] and arg[0]:match("hailstone.lua") then local function printf(fmt, ...) io.write(string.format(fmt, ...)) end local seq=lib.hailstone(27) printf("27 has %d numbers in sequence:\n",#seq) for _,i in ipairs(seq) do printf("%d ", i) end printf("\n") else return lib end  
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#Scala
Scala
object ExtremeFloatingPoint extends App { val negInf = -1.0 / 0.0 //also Double.NegativeInfinity val inf = 1.0 / 0.0 // //also Double.PositiveInfinity val nan = 0.0 / 0.0 // //also Double.NaN val negZero = -2.0 / inf   println("Value: Result: Infinity? Whole?") println(f"Negative inf: ${negInf}%9s ${negInf.isInfinity}%9s ${negInf.isWhole}%9s") println(f"Positive inf: ${inf}%9s ${inf.isInfinity}%9s ${inf.isWhole}%9s") println(f"NaN: ${nan}%9s ${nan.isInfinity}%9s ${nan.isWhole}%9s") println(f"Negative 0: ${negZero}%9s ${negZero.isInfinity}%9s ${negZero.isWhole}%9s") println(f"inf + -inf: ${inf + negInf}%9s ${(inf + negInf).isInfinity}%9s ${(inf + negInf).isWhole}%9s") println(f"0 * NaN: ${0 * nan}%9s ${(inf + negInf).isInfinity}%9s ${(inf + negInf).isWhole}%9s") println(f"NaN == NaN: ${nan == nan}%9s") }
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#Scheme
Scheme
(define infinity (/ 1.0 0.0)) (define minus-infinity (- infinity)) (define zero 0.0) (define minus-zero (- zero)) (define not-a-number (/ 0.0 0.0))   (equal? (list infinity minus-infinity zero minus-zero not-a-number) (list +inf.0 -inf.0 0.0 -0.0 +nan.0)) ; #t  
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
#PicoLisp
PicoLisp
#!/usr/bin/env python3   HW = r''' /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/'''   def snusp(store, code): ds = bytearray(store) # data store dp = 0 # data pointer cs = code.splitlines() # 2 dimensional code store ipr, ipc = 0, 0 # instruction pointers in row and column for r, row in enumerate(cs): try: ipc = row.index('$') ipr = r break except ValueError: pass rt, dn, lt, up = range(4) id = rt # instruction direction. starting direction is always rt def step(): nonlocal ipr, ipc if id&1: ipr += 1 - (id&2) else: ipc += 1 - (id&2) while ipr >= 0 and ipr < len(cs) and ipc >= 0 and ipc < len(cs[ipr]): op = cs[ipr][ipc] if op == '>': dp += 1 elif op == '<': dp -= 1 elif op == '+': ds[dp] += 1 elif op == '-': ds[dp] -= 1 elif op == '.': print(chr(ds[dp]), end='') elif op == ',': ds[dp] = input() elif op == '/': id = ~id elif op == '\\': id ^= 1 elif op == '!': step() elif op == '?': if not ds[dp]: step() step()   if __name__ == '__main__': snusp(5, HW)
http://rosettacode.org/wiki/Execute_SNUSP
Execute SNUSP
Execute SNUSP is an implementation of SNUSP. Other implementations of SNUSP. RCSNUSP SNUSP An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
#Python
Python
#!/usr/bin/env python3   HW = r''' /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/'''   def snusp(store, code): ds = bytearray(store) # data store dp = 0 # data pointer cs = code.splitlines() # 2 dimensional code store ipr, ipc = 0, 0 # instruction pointers in row and column for r, row in enumerate(cs): try: ipc = row.index('$') ipr = r break except ValueError: pass rt, dn, lt, up = range(4) id = rt # instruction direction. starting direction is always rt def step(): nonlocal ipr, ipc if id&1: ipr += 1 - (id&2) else: ipc += 1 - (id&2) while ipr >= 0 and ipr < len(cs) and ipc >= 0 and ipc < len(cs[ipr]): op = cs[ipr][ipc] if op == '>': dp += 1 elif op == '<': dp -= 1 elif op == '+': ds[dp] += 1 elif op == '-': ds[dp] -= 1 elif op == '.': print(chr(ds[dp]), end='') elif op == ',': ds[dp] = input() elif op == '/': id = ~id elif op == '\\': id ^= 1 elif op == '!': step() elif op == '?': if not ds[dp]: step() step()   if __name__ == '__main__': snusp(5, HW)
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Idris
Idris
if2 : Bool -> Bool -> Lazy a -> Lazy a -> Lazy a -> Lazy a -> a if2 True True v _ _ _ = v if2 True False _ v _ _ = v if2 False True _ _ v _ = v if2 _ _ _ _ _ v = v
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#Inform_7
Inform 7
To if2 (c1 - condition) and-or (c2 - condition) begin -- end: (- switch (({c1})*2 + ({c2})) { 3: do -). To else1 -- in if2: (- } until (1); 2: do { -). To else2 -- in if2: (- } until (1); 1: do { -). To else0 -- in if2: (- } until (1); 0: -).
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Tcl
Tcl
foreach expression {5**3**2 (5**3)**2 5**(3**2)} { puts "${expression}:\t[expr $expression]" }
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#VBA
VBA
Public Sub exp() Debug.Print "5^3^2", 5 ^ 3 ^ 2 Debug.Print "(5^3)^2", (5 ^ 3) ^ 2 Debug.Print "5^(3^2)", 5 ^ (3 ^ 2) End Sub
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#VBScript
VBScript
  WScript.StdOut.WriteLine "5^3^2 => " & 5^3^2 WScript.StdOut.WriteLine "(5^3)^2 => " & (5^3)^2 WScript.StdOut.WriteLine "5^(3^2) => " & 5^(3^2)  
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#Verbexx
Verbexx
// Exponentiation order example:   @SAY "5**3**2 = " ( 5**3**2 ); @SAY "(5**3)**2 = " ( (5**3)**2 ); @SAY "5**(3**2) = " ( 5**(3**2) );   /] Output:   5**3**2 = 1953125 (5**3)**2 = 15625 5**(3**2) = 1953125
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Raven
Raven
100 each 1 + as n '' n 3 mod 0 = if 'Fizz' cat n 5 mod 0 = if 'Buzz' cat dup empty if drop n say
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#JavaScript
JavaScript
function primeGenerator(num, showPrimes) { var i, arr = [];   function isPrime(num) { // try primes <= 16 if (num <= 16) return ( num == 2 || num == 3 || num == 5 || num == 7 || num == 11 || num == 13 ); // cull multiples of 2, 3, 5 or 7 if (num % 2 == 0 || num % 3 == 0 || num % 5 == 0 || num % 7 == 0) return false; // cull square numbers ending in 1, 3, 7 or 9 for (var i = 10; i * i <= num; i += 10) { if (num % (i + 1) == 0) return false; if (num % (i + 3) == 0) return false; if (num % (i + 7) == 0) return false; if (num % (i + 9) == 0) return false; } return true; }   if (typeof num == "number") { for (i = 0; arr.length < num; i++) if (isPrime(i)) arr.push(i); // first x primes if (showPrimes) return arr; // xth prime else return arr.pop(); }   if (Array.isArray(num)) { for (i = num[0]; i <= num[1]; i++) if (isPrime(i)) arr.push(i); // primes between x .. y if (showPrimes) return arr; // number of primes between x .. y else return arr.length; } // throw a default error if nothing returned yet // (surrogate for a quite long and detailed try-catch-block anywhere before) throw("Invalid arguments for primeGenerator()"); }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Icon_and_Unicon
Icon and Unicon
procedure main(args) write(fib(integer(!args) | 1000) end   procedure fib(n) static fCache initial { fCache := table() fCache[0] := 0 fCache[1] := 1 } /fCache[n] := fib(n-1) + fib(n-2) return fCache[n] end
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   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   sequence: smallest number greater than previous term with exactly n divisors
#REXX
REXX
/*REXX program displays divisors of any [negative/zero/positive] integer or a range.*/ parse arg LO HI inc . /*obtain the optional args*/ HI= word(HI LO 20, 1); LO= word(LO 1,1); inc= word(inc 1,1) /*define the range options*/ w= length(HI) + 2; numeric digits max(9, w-2);  != '∞' /*decimal digits for // */ @.=left('',7); @.1= "{unity}"; @.2= '[prime]'; @.!= " {∞} " /*define some literals. */ say center('n', w) "#divisors" center('divisors', 60) /*display the header. */ say copies('═', w) "═════════" copies('═' , 60) /* " " separator. */ pn= 0 /*count of prime numbers. */ do k=2 until sq.k>=HI; sq.k= k*k /*memoization for squares.*/ end /*k*/ do n=LO to HI by inc; $= divs(n); #= words($) /*get list of divs; # divs*/ if $==! then do; #= !; $= ' (infinite)'; end /*handle case for infinity*/ p= @.#; if n<0 then if n\==-1 then p= @.. /* " " " negative*/ if [email protected] then pn= pn + 1 /*Prime? Then bump counter*/ say center(n, w) center('['#"]", 9) "──► " p ' ' $ end /*n*/ /* [↑] process a range of integers. */ say say right(pn, 20) ' primes were found.' /*display the number of primes found. */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ divs: procedure expose sq.; parse arg x 1 b; a=1 /*set X and B to the 1st argument. */ if x<2 then do; x= abs(x); if x==1 then return 1; if x==0 then return '∞'; b=x end odd= x // 2 /* [↓] process EVEN or ODD ints. ___*/ do j=2+odd by 1+odd while sq.j<x /*divide by all the integers up to √ x */ if x//j==0 then do; a=a j; b=x%j b; end /*÷? Add divisors to α and ß lists*/ end /*j*/ /* [↑]  % ≡ integer division. ___*/ if sq.j==x then return a j b /*Was X a square? Then insert √ x */ return a b /*return the divisors of both lists. */
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#DWScript
DWScript
procedure RunCode(code : String); var i : Integer; accum, bottles : Integer; begin for i:=1 to Length(code) do begin case code[i] of 'Q', 'q' : PrintLn(code); 'H', 'h' : PrintLn('Hello, world!'); '9' : begin bottles:=99; while bottles>1 do begin Print(bottles); PrintLn(' bottles of beer on the wall,'); Print(bottles); PrintLn(' bottles of beer.'); PrintLn('Take one down, pass it around,'); Dec(bottles); if bottles>1 then begin Print(bottles); PrintLn(' bottles of beer on the wall.'#13#10); end; end; PrintLn('1 bottle of beer on the wall.'); end; '+' : Inc(accum); else PrintLn('Syntax Error'); end; end; end;
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Dyalect
Dyalect
func eval(code) { var accumulator = 0 var opcodes = ( "h": () => print("Hello, World!"), "q": () => print(code), "9": () => { var quantity = 99 while quantity > 1 { print("\(quantity) bottles of beer on the wall, \(quantity) bottles of beer.") print("Take one down and pass it around, \(quantity - 1) bottles of beer.") quantity -= 1 } print("1 bottle of beer on the wall, 1 bottle of beer.") print("Take one down and pass it around, no more bottles of beer on the wall.\n") print("No more bottles of beer on the wall, no more bottles of beer.") print("Go to the store and buy some more, 99 bottles of beer on the wall.") }, "+": () => { accumulator += 1 } )   for c in code { opcodes[c.Lower()]() } }
http://rosettacode.org/wiki/Execute_a_Markov_algorithm
Execute a Markov algorithm
Execute a Markov algorithm You are encouraged to solve this task according to the task description, using any language you may know. Task Create an interpreter for a Markov Algorithm. Rules have the syntax: <ruleset> ::= ((<comment> | <rule>) <newline>+)* <comment> ::= # {<any character>} <rule> ::= <pattern> <whitespace> -> <whitespace> [.] <replacement> <whitespace> ::= (<tab> | <space>) [<whitespace>] There is one rule per line. If there is a   .   (period)   present before the   <replacement>,   then this is a terminating rule in which case the interpreter must halt execution. A ruleset consists of a sequence of rules, with optional comments. Rulesets Use the following tests on entries: Ruleset 1 # This rules file is extracted from Wikipedia: # http://en.wikipedia.org/wiki/Markov_Algorithm A -> apple B -> bag S -> shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate the output: I bought a bag of apples from my brother. Ruleset 2 A test of the terminating rule # Slightly modified from the rules on Wikipedia A -> apple B -> bag S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As from T S. Should generate: I bought a bag of apples from T shop. Ruleset 3 This tests for correct substitution order and may trap simple regexp based replacement routines if special regexp characters are not escaped. # BNF Syntax testing rules A -> apple WWWW -> with Bgage -> ->.* B -> bag ->.* -> money W -> WW S -> .shop T -> the the shop -> my brother a never used -> .terminating rule Sample text of: I bought a B of As W my Bgage from T S. Should generate: I bought a bag of apples with my money from T shop. Ruleset 4 This tests for correct order of scanning of rules, and may trap replacement routines that scan in the wrong order.   It implements a general unary multiplication engine.   (Note that the input expression must be placed within underscores in this implementation.) ### Unary Multiplication Engine, for testing Markov Algorithm implementations ### By Donal Fellows. # Unary addition engine _+1 -> _1+ 1+1 -> 11+ # Pass for converting from the splitting of multiplication into ordinary # addition 1! -> !1 ,! -> !+ _! -> _ # Unary multiplication by duplicating left side, right side times 1*1 -> x,@y 1x -> xX X, -> 1,1 X1 -> 1X _x -> _X ,x -> ,X y1 -> 1y y_ -> _ # Next phase of applying 1@1 -> x,@y 1@_ -> @_ ,@_ -> !_ ++ -> + # Termination cleanup for addition _1 -> 1 1+_ -> 1 _+_ -> Sample text of: _1111*11111_ should generate the output: 11111111111111111111 Ruleset 5 A simple Turing machine, implementing a three-state busy beaver. The tape consists of 0s and 1s,   the states are A, B, C and H (for Halt), and the head position is indicated by writing the state letter before the character where the head is. All parts of the initial tape the machine operates on have to be given in the input. Besides demonstrating that the Markov algorithm is Turing-complete, it also made me catch a bug in the C++ implementation which wasn't caught by the first four rulesets. # Turing machine: three-state busy beaver # # state A, symbol 0 => write 1, move right, new state B A0 -> 1B # state A, symbol 1 => write 1, move left, new state C 0A1 -> C01 1A1 -> C11 # state B, symbol 0 => write 1, move left, new state A 0B0 -> A01 1B0 -> A11 # state B, symbol 1 => write 1, move right, new state B B1 -> 1B # state C, symbol 0 => write 1, move left, new state B 0C0 -> B01 1C0 -> B11 # state C, symbol 1 => write 1, move left, halt 0C1 -> H01 1C1 -> H11 This ruleset should turn 000000A000000 into 00011H1111000
#Ada
Ada
with Ada.Strings.Unbounded;   package Markov is use Ada.Strings.Unbounded; type Ruleset (Length : Natural) is private; type String_Array is array (Positive range <>) of Unbounded_String; function Parse (S : String_Array) return Ruleset; function Apply (R : Ruleset; S : String) return String; private type Entry_Kind is (Comment, Rule); type Set_Entry (Kind : Entry_Kind := Rule) is record case Kind is when Rule => Source  : Unbounded_String; Target  : Unbounded_String; Is_Terminating : Boolean; when Comment => Text  : Unbounded_String; end case; end record; subtype Rule_Entry is Set_Entry (Kind => Rule); type Entry_Array is array (Positive range <>) of Set_Entry; type Ruleset (Length : Natural) is record Entries : Entry_Array (1 .. Length); end record; end Markov;
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#C.23
C#
using System; //Used for Exception and Console classes class Exceptions { class U0 : Exception { } class U1 : Exception { } static int i; static void foo() { for (i = 0; i < 2; i++) try { bar(); } catch (U0) { Console.WriteLine("U0 Caught"); } } static void bar() { baz(); } static void baz(){ if (i == 0) throw new U0(); throw new U1(); }   public static void Main() { foo(); } }
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call
Exceptions/Catch an exception thrown in a nested call
Show how to create a user-defined exception   and   show how to catch an exception raised from several nested calls away.   Create two user-defined exceptions,   U0   and   U1.   Have function   foo   call function   bar   twice.   Have function   bar   call function   baz.   Arrange for function   baz   to raise, or throw exception   U0   on its first call, then exception   U1   on its second.   Function   foo   should catch only exception   U0,   not   U1. Show/describe what happens when the program is run.
#C.2B.2B
C++
#include <iostream> class U0 {}; class U1 {};   void baz(int i) { if (!i) throw U0(); else throw U1(); } void bar(int i) { baz(i); }   void foo() { for (int i = 0; i < 2; i++) { try { bar(i); } catch(U0 e) { std::cout<< "Exception U0 caught\n"; } } }   int main() { foo(); std::cout<< "Should never get here!\n"; return 0; }
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Aikido
Aikido
  try { var lines = readfile ("input.txt") process (lines) } catch (e) { do_somthing(e) }    
http://rosettacode.org/wiki/Exceptions
Exceptions
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops This task is to give an example of an exception handling routine and to "throw" a new exception. Related task   Exceptions Through Nested Calls
#Aime
Aime
void throwing(void) { o_text("throwing...\n"); error("now!"); }   void catching(void) { o_text("ready to catch\n"); if (trap(throwing)) { o_text("caught!\n"); } else { # nothing was thrown } }   integer main(void) { catching();   return 0; }
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#Amazing_Hopper
Amazing Hopper
  #!/usr/bin/hopper   #include <hopper.h>   main:   /* execute "ls -lstar" with no result return (only displayed) */ {"ls -lstar"},execv   /* this form does not allow composition of the line with variables. Save result in the variable "s", and then display it */ s=`ls -l | awk '{if($2=="2")print $0;}'` {"\n",s,"\n"}print   data="2" {""}tok sep   // the same as above, only I can compose the line: {"ls -l | awk '{if($2==\"",data,"\")print $0;}'"}join(s),{s}exec,print {"\n\n"}print   // this does the same as above, with an "execute" macro inside a "let" macro: t=0,let (t := execute( {"ls -l | awk '{if($2==\""},{data},{"\")print $0;}'"} )) {t,"\n"}print   {0}return  
http://rosettacode.org/wiki/Execute_a_system_command
Execute a system command
Task Run either the   ls   system command   (dir   on Windows),   or the   pause   system command. Related task Get system command output
#APL
APL
  h ← ⎕fio['fork_daemon'] '/bin/ls /var' backups games lib lock mail run tmp cache gemini local log opt spool ⎕fio['fclose'] h 0  
http://rosettacode.org/wiki/Factorial
Factorial
Definitions   The factorial of   0   (zero)   is defined as being   1   (unity).   The   Factorial Function   of a positive integer,   n,   is defined as the product of the sequence: n,   n-1,   n-2,   ...   1 Task Write a function to return the factorial of a number. Solutions can be iterative or recursive. Support for trapping negative   n   errors is optional. Related task   Primorial numbers
#ActionScript
ActionScript
public static function factorial(n:int):int { if (n < 0) return 0;   var fact:int = 1; for (var i:int = 1; i <= n; i++) fact *= i;   return fact; }
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#E
E
def power(base, exponent :int) { var r := base if (exponent < 0) { for _ in exponent..0 { r /= base } } else if (exponent <=> 0) { return 1 } else { for _ in 2..exponent { r *= base } } return r }
http://rosettacode.org/wiki/Exponentiation_operator
Exponentiation operator
Most programming languages have a built-in implementation of exponentiation. Task Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants. Related tasks   Exponentiation order   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#EchoLisp
EchoLisp
  ;; this exponentiation function handles integer, rational or float x. ;; n is a positive or negative integer.   (define (** x n) (cond ((zero? n) 1) ((< n 0) (/ (** x (- n)))) ;; x**-n = 1 / x**n ((= n 1) x) ((= n 0) 1) ((odd? n) (* x (** x (1- n)))) ;; x**(2p+1) = x * x**2p (else (let ((m (** x (/ n 2)))) (* m m))))) ;; x**2p = (x**p) * (x**p)   (** 3 0) → 1 (** 3 4) → 81 (** 3 5) → 243 (** 10 10) → 10000000000 (** 1.3 10) → 13.785849184900007   (** -3 5) → -243 (** 3 -4) → 1/81 (** 3.7 -4) → 0.005335720890574502 (** 2/3 7) → 128/2187   (lib 'bigint) (** 666 42) → 38540524895511613165266748863173814985473295063157418576769816295283207864908351682948692085553606681763707358759878656    
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
hailstone[1] = {1}; hailstone[n_] := hailstone[n] = Prepend[hailstone[If[EvenQ[n], n/2, 3 n + 1]], n]; If[$ScriptCommandLine[[1]] == $Input, val = hailstone[27]; Print["hailstone(27) starts with ", val[[;; 4]], ", ends with ", val[[-4 ;;]], ", and has length ", Length[val], "."]; val = MaximalBy[Range[99999], Length@*hailstone][[1]]; Print[val, " has the longest hailstone sequence with length ", Length[hailstone[val]], "."]];
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#Nanoquery
Nanoquery
def hailstone(n) seq = list()   while (n > 1) append seq n if (n % 2)=0 n = int(n / 2) else n = int((3 * n) + 1) end end append seq n return seq end   if main h = hailstone(27) println "hailstone(27)" println "total elements: " + len(hailstone(27)) print h[0] + ", " + h[1] + ", " + h[2] + ", " + h[3] + ", ..., " println h[-4] + ", " + h[-3] + ", " + h[-2] + ", " + h[-1]   max = 0 maxLoc = 0 for i in range(1,99999) result = len(hailstone(i)) if (result > max) max = result maxLoc = i end end print "\nThe number less than 100,000 with the longest sequence is " println maxLoc + " with a length of " + max end
http://rosettacode.org/wiki/Executable_library
Executable library
The general idea behind an executable library is to create a library that when used as a library does one thing; but has the ability to be run directly via command line. Thus the API comes with a CLI in the very same source code file. Task detail Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number. The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task: 2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1 3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length. Create a second executable to calculate the following: Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000. Explain any extra setup/run steps needed to complete the task. Notes: It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment. Interpreters are present in the runtime environment.
#NetRexx
NetRexx
$ jar cvfe RHailstoneSequence.jar RHailstoneSequence RHailstoneSequence.class added manifest adding: RHailstoneSequence.class(in = 2921) (out= 1567)(deflated 46%)
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#Seed7
Seed7
$ include "seed7_05.s7i"; include "float.s7i";   const proc: main is func begin writeln("positive infinity: " <& Infinity); writeln("negative infinity: " <& -Infinity); writeln("negative zero: " <& -0.0); writeln("not a number: " <& NaN);   # some arithmetic writeln("+Infinity + 2.0 = " <& Infinity + 2.0); writeln("+Infinity - 10.1 = " <& Infinity - 10.1); writeln("+Infinity + -Infinity = " <& Infinity + -Infinity); writeln("0.0 * +Infinity = " <& 0.0 * Infinity); writeln("1.0/-0.0 = " <& 1.0 / -0.0); writeln("NaN + 1.0 = " <& NaN + 1.0); writeln("NaN + NaN = " <& NaN + NaN);   # some comparisons writeln("NaN = NaN = " <& NaN = NaN); writeln("isNaN(NaN) = " <& isNaN(NaN)); writeln("0.0 = -0.0 = " <& 0.0 = -0.0); writeln("isNegativeZero(-0.0) = " <& isNegativeZero(-0.0)); writeln("isNegativeZero(0.0) = " <& isNegativeZero(0.0)); end func;
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#Sidef
Sidef
var inf = 1/0 # same as: Inf var nan = 0/0 # same as: NaN   var exprs = [ "1.0 / 0.0", "-1.0 / 0.0", "0.0 / 0.0", "- 0.0", "inf + 1", "5 - inf", "inf * 5", "inf / 5", "inf * 0", "1.0 / inf", "-1.0 / inf", "inf + inf", "inf - inf", "inf * inf", "inf / inf", "inf * 0.0", " 0 < inf", "inf == inf", "nan + 1", "nan * 5", "nan - nan", "nan * inf", "- nan", "nan == nan", "nan > 0", "nan < 0", "nan == 0", "0.0 == -0.0", ]   exprs.each { |expr| "%15s => %s\n".printf(expr, eval(expr)) }   say "-"*40 say("NaN equality: ", NaN == nan) say("Infinity equality: ", Inf == inf) say("-Infinity equality: ", -Inf == -inf)   say "-"*40 say("sqrt(-1) = ", sqrt(-1)) say("tanh(-Inf) = ", tanh(-inf)) say("(-Inf)**2 = ", (-inf)**2) say("(-Inf)**3 = ", (-inf)**3) say("acos(Inf) = ", acos(inf)) say("atan(Inf) = ", atan(inf)) say("log(-1) = ", log(-1)) say("atanh(Inf) = ", atanh(inf))