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/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
#PL.2FI
PL/I
factors: procedure options(main); declare i binary( 15 )fixed; declare n binary( 15 )fixed; do n = 90 to 100; put skip list( 'factors of: ', n, ': ' ); do i = 1 to n; if mod(n, i) = 0 then put edit( i )(f(4)); end; end; end factors;  
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#11l
11l
F hello() print(‘Hello, world!’)   String src F quine() print(:src)   F bottles() L(i) (99.<2).step(-1) print(‘#. bottles of beer on the wall’.format(i)) print(‘#. bottles of beer’.format(i)) print(‘Take one down, pass it around’) print(‘#. bottles of beer on the wall’.format(i - 1)) print()   print(‘2 bottles of beer on the wall’) print(‘2 bottles of beer’) print(‘Take one down, pass it around’) print(‘1 bottle of beer on the wall’) print()   print(‘1 bottle of beer on the wall’) print(‘1 bottle of beer’) print(‘Take one down, pass it around’) print(‘No more bottles of beer on the wall’) print()   print(‘No more bottles of beer on the wall’) print(‘No more bottles of beer on the wall’) print(‘Go to the store and buy some more’) print(‘99 bottles of beer on the wall.’) print()   V acc = 0 F incr()  :acc++   :start: src = File(:argv[1]).read()   [Char = (() -> N)] dispatch dispatch[Char(‘h’)] = hello dispatch[Char(‘q’)] = quine dispatch[Char(‘9’)] = bottles dispatch[Char(‘+’)] = incr   L(i) src.lowercase() I i C dispatch dispatch[i]()
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.   For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it. Bonus Points Run all 5 sample programs at the aforementioned website and output their results.
#Wren
Wren
var NOP = 0 var LDA = 1 var STA = 2 var ADD = 3 var SUB = 4 var BRZ = 5 var JMP = 6 var STP = 7   var ops = {"NOP": NOP, "LDA": LDA, "STA": STA, "ADD": ADD, "SUB": SUB, "BRZ": BRZ, "JMP": JMP, "STP": STP}   var load = Fn.new { |prog| var mem = List.filled(32, 0) var lines = prog.trimEnd().split("\n") for (i in 0...lines.count) { var line = lines[i].trim() var split = line.split(" ") var instr = split[0] var addr = 0 if (split.count == 2) addr = Num.fromString(split[1]) if (ops[instr]) { mem[i] = ops[instr] * 32 + addr } else { var v = Num.fromString(instr) if (v) mem[i] = v } } return mem }   var output = Fn.new { |acc| System.print(acc) }   var interp = Fn.new { |prog| var acc = 0 var pc = 0 var mem = load.call(prog) while (true) { var instr = mem[pc] >> 5 var addr = mem[pc] % 32 pc = pc + 1 if (instr == LDA) { acc = mem[addr] } else if (instr == STA) { mem[addr] = acc } else if (instr == ADD) { acc = acc + mem[addr] if (acc > 255) acc = acc - 256 } else if (instr == SUB) { acc = acc - mem[addr] if (acc < 0) acc = acc + 256 } else if (instr == BRZ) { if (acc == 0) pc = addr } else if (instr == JMP) { pc = addr } if (instr == STP || pc > 31) break } output.call(acc) }   var progs = [ """ LDA 3 ADD 4 STP 2 2 """, """ LDA 12 ADD 10 STA 12 LDA 11 SUB 13 STA 11 BRZ 8 JMP 0 LDA 12 STP 8 7 0 1 """, """ LDA 14 STA 15 ADD 13 STA 14 LDA 15 STA 13 LDA 16 SUB 17 BRZ 11 STA 16 JMP 0 LDA 14 STP 1 1 0 8 1 """, """ LDA 13 ADD 15 STA 5 ADD 16 STA 7 NOP STA 14 NOP BRZ 11 STA 15 JMP 0 LDA 14 STP LDA 0 0 28 1       6 0 2 26 5 20 3 30 1 22 4 24 """, """ 0 0 STP NOP LDA 3 SUB 29 BRZ 18 LDA 3 STA 29 BRZ 14 LDA 1 ADD 31 STA 1 JMP 2 LDA 0 ADD 31 STA 0 JMP 2 LDA 3 STA 29 LDA 0 ADD 30 ADD 3 STA 0 LDA 1 ADD 30 ADD 3 STA 1 JMP 2 0 1 3 """ ] for (prog in progs) interp.call(prog)
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
#MUMPS
MUMPS
USER>write 3e145 30000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 USER>write 3e146 <MAXNUMBER>
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols binary   negInf = double -1.0 / 0.0; knegInf = Double.NEGATIVE_INFINITY inf = double 1.0 / 0.0; kinf = Double.POSITIVE_INFINITY nan = double 0.0 / 0.0; knan = Double.NaN negZero = double -2.0 / inf; knegZero = -2.0 / Double.POSITIVE_INFINITY   say "Negative inf: " Rexx(negInf).right(10) '|' knegInf say "Positive inf: " Rexx(inf).right(10) '|' kinf say "NaN: " Rexx(nan).right(10) '|' knan say "Negative 0: " Rexx(negZero).right(10) '|' knegZero say "inf + -inf: " Rexx(inf + negInf).right(10) '|' (kinf + knegInf) say "0 * NaN: " Rexx(0 * nan).right(10) '|' (0 * knan) say "NaN == NaN: " Rexx(nan == nan).right(10) '|' (knan == knan)   return  
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.
#C
C
# # snusp.icn, A Modular SNUSP interpreter #   $define VERSION 0.6   # allow a couple of cli options link options   # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4   record position(row, col) global dir, ip, ram   procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug   opts := options(argv, "-h! -v! -d!", errorproc) \opts["v"] & verbose := 1 \opts["h"] & show_help(verbose) \opts["d"] & debug := 1   ip := position(1,1)   # initial direction dir := DRIGHT   # prepare initial memory ram := list(1, 0)   # prepare code field codespace := []   fn := open(argv[1], "r") | &input if (fn === &input) & \opts["h"] then return   while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) # track starting indicator if /col := find("$", codespace[row]) then { ip.row := row ip.col := col } row +:= 1 }   if \verbose then { write("Starting at ", ip.row, ", ", ip.col, " with codespace:") every write(!codespace) }   dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]", " row: ", ip.row, " col: ", ip.col, " dp: ", dp, " ram[dp]: ", ram[dp]) } case ch of { # six of the bf instructions "+": ram[dp] +:= 1 "-": ram[dp] -:= 1 ">": resize(dp +:= 1) "<": dp -:= 1 ".": writes(char(ram[dp]) | char(0)) ",": ram[dp] := getche() # direction change, LURD, RULD, SKIP, SKIPZ "\\": { # LURD case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } "/": { # RULD case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } "!": step() "?": { # skipz if ram[dp] = 0 then { step() } } # modular SNUSP "@": { # Enter push(dirs, dir) push(ips, copy(ip)) } "#": { # Leave if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end   # advance the ip depending on direction procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end   # enlarge memory when needed procedure resize(elements) until *ram >= elements do put(ram, 0) end   # quick help or verbose help procedure show_help(verbose) write("SNUSP interpeter in Unicon, version ", VERSION) write("CORE and MODULAR, not yet BLOATED") write() write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]") write(" -h, help") write(" -v, verbose (and verbose help") write(" -d, debug (step tracer)") if \verbose then { write() write("Instructions:") write(" + INCR, Increment current memory location") write(" - DECR, Decrement current memory location") write(" > RIGHT, Advance memory pointer") write(" < LEFT, Retreat memory pointer") write(" . WRITE, Output contents of current memory cell, in ASCII") write(" , READ, Accept key and place byte value in current memory cell") write(" \\ LURD, If going:") write(" left, go up") write(" up, go left") write(" right, go down") write(" down, go right") write(" / RULD, If going:") write(" right, go up") write(" up, go right") write(" left, go down") write(" down, go left") write(" !, SKIP, Move forward one step in current direction") write(" ?, SKIPZ, If current memory cell is zero then SKIP") write("Modular SNUSP adds:") write(" @, ENTER, Push direction and instruction pointer") write(" #, LEAVE, Pop direction and instruction pointer and SKIP") write() write("All other characters are NOOP, explicitly includes =,|,spc") write(" $, can set the starting location; first one found") write() write("Hello world examples:") write() write("CORE SNUSP:") write("/++++!/===========?\\>++.>+.+++++++..+++\\") write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./") write("$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\") write(" \\==-<<<<+>+++/ /=.>.+>.--------.-/") write() write("Modular SNUSP:") write(" /@@@@++++# #+++@@\ #-----@@@\\n") write("$@\\H.@/e.+++++++l.l.+++o.>>++++.< .<@/w.@\\o.+++r.++@\\l.@\\d.>+.@/.#") write(" \\@@@@=>++++>+++++<<@+++++# #---@@/!=========/!==/") write() } end
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.
#Coq
Coq
  Notation "A /\ B" := (and A B)  
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.
#D
D
void if2(T1, T2, T3, T4)(in bool c1, in bool c2, lazy T1 first, lazy T2 both, lazy T3 second, lazy T4 none) { if (c1) { if (c2) both; else first; } else { if (c2) second; else none; } }   void test(in bool a, in bool b) { import std.stdio; if2(a, b, writeln("first"), writeln("both"), writeln("second"), writeln("none")); }   void main() { test(1 < 2, 3 > 4); test(1 < 2, 1 < 2); test(3 > 4, 3 > 4); test(3 > 4, 1 < 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
#CLU
CLU
start_up = proc () po: stream := stream$primary_output()   stream$putl(po, "5**3**2 = " || int$unparse(5**3**2)) stream$putl(po, "(5**3)**2 = " || int$unparse((5**3)**2)) stream$putl(po, "5**(3**2) = " || int$unparse(5**(3**2))) end start_up
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
#Common_Lisp
Common Lisp
(expt (expt 5 3) 2) (expt 5 (expt 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
#D
D
void main() { import std.stdio, std.math, std.algorithm;   writefln("5 ^^ 3 ^^ 2 = %7d", 5 ^^ 3 ^^ 2); writefln("(5 ^^ 3) ^^ 2 = %7d", (5 ^^ 3) ^^ 2); writefln("5 ^^ (3 ^^ 2) = %7d", 5 ^^ (3 ^^ 2)); writefln("[5, 3, 2].reduce!pow = %7d", [5, 3, 2].reduce!pow); }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#REXX
REXX
/*REXX program calculates and displays factorions in bases nine ───► twelve. */ parse arg LOb HIb lim . /*obtain optional arguments from the CL*/ if LOb=='' | LOb=="," then LOb= 9 /*Not specified? Then use the default.*/ if HIb=='' | HIb=="," then HIb= 12 /* " " " " " " */ if lim=='' | lim=="," then lim= 1500000 - 1 /* " " " " " " */   do fact=0 to HIb;  !.fact= !(fact) /*use memoization for factorials. */ end /*fact*/   do base=LOb to HIb /*process all the required bases. */ @= 1 2 /*initialize the list (@) to 1 & 2. */ do j=3 for lim-2; $= 0 /*initialize the sum ($) to zero. */ t= j /*define the target (for the sum !'s).*/ do until t==0; d= t // base /*obtain a "digit".*/ $= $ + !.d /*add  !(d) to sum.*/ t= t % base /*get a new target.*/ end /*until*/ if $==j then @= @ j /*Good factorial sum? Then add to list.*/ end /*i*/ say say 'The factorions for base ' right( base, length(HIb) ) " are: " @ end /*base*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ !: procedure; parse arg x;  !=1; do j=2 to x;  !=!*j; end; return ! /*factorials*/
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Ruby
Ruby
  def factorion?(n, base) n.digits(base).sum{|digit| (1..digit).inject(1, :*)} == n end   (9..12).each do |base| puts "Base #{base} factorions: #{(1..1_500_000).select{|n| factorion?(n, base)}.join(" ")} " end  
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.
#VBA
VBA
  Option Explicit   Sub Main() Dim evens() As Long, i As Long Dim numbers() As Long   For i = 1 To 100000 ReDim Preserve numbers(1 To i) numbers(i) = i Next i   evens = FilterInNewArray(numbers)   Debug.Print "Count of initial array : " & UBound(numbers) & ", first item : " & numbers(LBound(numbers)) & ", last item : " & numbers(UBound(numbers)) Debug.Print "Count of new array : " & UBound(evens) & ", first item : " & evens(LBound(evens)) & ", last item : " & evens(UBound(evens))   FilterInPlace numbers   Debug.Print "Count of initial array (filtered): " & UBound(numbers) & ", first item : " & numbers(LBound(numbers)) & ", last item : " & numbers(UBound(numbers)) End Sub   Private Function FilterInNewArray(arr() As Long) As Long() Dim i As Long, t() As Long, cpt As Long For i = LBound(arr) To UBound(arr) If IsEven(arr(i)) Then cpt = cpt + 1 ReDim Preserve t(1 To cpt) t(cpt) = i End If Next i FilterInNewArray = t End Function   Private Sub FilterInPlace(arr() As Long) Dim i As Long, cpt As Long For i = LBound(arr) To UBound(arr) If IsEven(arr(i)) Then cpt = cpt + 1 arr(cpt) = i End If Next i ReDim Preserve arr(1 To cpt) End Sub   Private Function IsEven(Number As Long) As Boolean IsEven = (CLng(Right(CStr(Number), 1)) And 1) = 0 End Function
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
#PowerShell
PowerShell
for ($i = 1; $i -le 100; $i++) { if ($i % 15 -eq 0) { "FizzBuzz" } elseif ($i % 5 -eq 0) { "Buzz" } elseif ($i % 3 -eq 0) { "Fizz" } else { $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.
#Dart
Dart
Iterable<int> primesMap() { Iterable<int> oddprms() sync* { yield(3); yield(5); // need at least 2 for initialization final Map<int, int> bpmap = {9: 6}; final Iterator<int> bps = oddprms().iterator; bps.moveNext(); bps.moveNext(); // skip past 3 to 5 int bp = bps.current; int n = bp; int q = bp * bp; while (true) { n += 2; while (n >= q || bpmap.containsKey(n)) { if (n >= q) { final int inc = bp << 1; bpmap[bp * bp + inc] = inc; bps.moveNext(); bp = bps.current; q = bp * bp; } else { final int inc = bpmap.remove(n); int next = n + inc; while (bpmap.containsKey(next)) { next += inc; } bpmap[next] = inc; } n += 2; } yield(n); } } return [2].followedBy(oddprms()); }   void main() { print("The first 20 primes:"); String str = "( "; primesMap().take(20).forEach((p)=>str += "$p "); print(str + ")"); print("Primes between 100 and 150:"); str = "( "; primesMap().skipWhile((p)=>p<100).takeWhile((p)=>p<150) .forEach((p)=>str += "$p "); print(str + ")"); print("Number of primes between 7700 and 8000: ${ primesMap().skipWhile((p)=>p<7700).takeWhile((p)=>p<8000).length }"); print("The 10,000th prime: ${ primesMap().skip(9999).first }"); final start = DateTime.now().millisecondsSinceEpoch; final answer = primesMap().takeWhile((p)=>p<2000000).reduce((a,p)=>a+p); final elapsed = DateTime.now().millisecondsSinceEpoch - start; }
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
#F.C5.8Drmul.C3.A6
Fōrmulæ
fib := function(n) local a; a := [[0, 1], [1, 1]]^n; return a[1][2]; 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
#PL.2FM
PL/M
To run: Start up. Show the factors of 11. Show the factors of 21. Show the factors of 519. Wait for the escape key. Shut down.   To show the factors of a number: Write "The factors of " then the number then ":" on the console. Find a square root of the number. Loop. If a counter is past the square root, write "" on the console; exit. Divide the number by the counter giving a quotient and a remainder. If the remainder is 0, show the counter and the quotient. Repeat.   A factor is a number.   To show a factor and another factor: If the factor is not the other factor, write "" then the factor then " " then the other factor then " " on the console without advancing; exit. Write "" then the factor on the console without advancing.
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#8080_Assembly
8080 Assembly
putch: equ 2 ; Write character puts: equ 9 ; Write string fopen: equ 15 ; Open file fread: equ 20 ; Read record setdma: equ 26 ; Set DMA address fcb: equ 5Ch ; FCB for first file on command line org 100h ;;; Open source file given on command line lxi d,fcb mvi c,fopen call 5 ; Open file inr a ; A=FF = error lxi d,efile jz s_out ; If error, print error message and stop lxi d,src ; Start reading file at src ;;; Load the entire source file into memory block: push d ; Set DMA address to next free location mvi c,setdma call 5 lxi d,fcb ; Read 128-byte record mvi c,fread call 5 pop d ; Advance pointer by 128 bytes lxi h,128 dad d xchg dcr a ; A=1 = end of file jz block ; If not EOF, read next block xchg mvi m,26 ; Terminate last block with EOF byte to be sure lxi b,src ; BC = source pointer ins: ldax b ; Get current instruction cpi 26 ; If EOF, stop rz ori 32 ; Make lowercase push b ; Keep source pointer cpi 'h' ; H=hello cz hello cpi 'q' ; Q=quine cz quine cpi '9' ; 9=bottles cz botls cpi '+' ; +=increment cz incr pop b ; Restore source pointer inx b ; Next instruction jmp ins ;;; Increment accumulator incr: lxi h,accum inr m ret ;;; Print "Hello, World" hello: lxi d,histr jmp s_out ;;; Print the source quine: lxi h,src ; Pointer to source qloop: mov a,m ; Load byte cpi 26 ; Reached the end? rz ; If so, stop push h ; Otherwise, keep pointer mov e,a mvi c,putch ; Print character call 5 pop h ; Restore pointer inx h ; Next byte jmp qloop ;;; 99 bottles of beer botls: mvi e,99 ; 99 bottles bverse: call nbeer ; _ bottle(s) of beer lxi h,otw ; on the wall call bstr call nbeer ; _ bottle(s) of beer lxi h,nl ; \r\n call bstr lxi h,tod ; Take one down and pass it around call bstr dcr e ; Decrement counter push psw ; Keep status call nbeer ; _ bottle(s) of beer lxi h,otw call bstr ; on the wall lxi h,nl ; \r\n call bstr pop psw ; restore status jnz bverse ; If not at 0, next verse ret nbeer: push d ; keep counter call btlstr ; _ bottle(s) lxi d,ofbeer call s_out ; of beer pop d ret bstr: push d ; keep counter xchg ; print string in HL call s_out pop d ; restore counter ret ;;; Print "N bottle(s)" btlstr: push d ; Keep counter mov a,e ; Print number call num lxi d,bottle call s_out ; Print " bottle" pop d ; Restore counter dcr e ; If counter is 1, rz ; then stop, mvi e,'s' ; otherwise, print S mvi c,putch jmp 5 ;;; Print number (0-99) in A num: ana a ; If 0, print "no more" lxi d,nomore jz s_out mvi b,'0'-1 ; Tens digit nloop: inr b ; Increment tens digit sui 10 ; Subtract 10 jnc nloop adi '0'+10 ; Ones digit lxi d,snum-1 stax d ; Store ones digit mov a,b ; Tens digit zero? cpi '0' jz s_out ; If so, only print ones digit dcx d ; Otherwise, store tens digit stax d s_out: mvi c,puts ; Print result jmp 5 efile: db 'File error.$' histr: db 'Hello, world!',13,10,'$' db '..' snum: db '$' nomore: db 'No more$' bottle: db ' bottle$' ofbeer: db ' of beer$' otw: db ' on the wall',13,10,'$' tod: db 'Take one down and pass it around' nl: db 13,10,'$' accum: db 0 ; Accumulator src: equ $ ; Program source
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Action.21
Action!
PROC Run(CHAR ARRAY code) BYTE i,a CHAR c   PrintF("Run ""%S""%E%E",code) a=0 FOR i=1 TO code(0) DO c=code(i) IF c='q OR c='Q THEN PrintE(code) ELSEIF c='h OR c='H THEN PrintE("Hello, world!") ELSEIF c='9 THEN PrintE("99 bottles here...") ELSEIF c='+ THEN a==+1 ELSE PrintF("Unrecognized character '%C'%E",c) Break() FI OD PrintF("%EAccumulator=%B%E",a) RETURN   PROC Main() Run("9++hQ+q9H+") 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
#11l
11l
F my_pow(base, exp) -> Float I exp < 0 R 1 / my_pow(base, -exp) I exp == 0 R 1 V ans = base L 0 .< exp - 1 ans *= base R ans   print(‘2 ^ 3 = ’my_pow(2, 3)) print(‘1 ^ -10 = ’my_pow(1, -10)) print(‘-1 ^ -3 = ’my_pow(-1, -3)) print() print(‘2.0 ^ -3 = ’my_pow(2.0, -3)) print(‘1.5 ^ 0 = ’my_pow(1.5, 0)) print(‘4.5 ^ 2 = ’my_pow(4.5, 2))
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.   For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it. Bonus Points Run all 5 sample programs at the aforementioned website and output their results.
#Z80_Assembly
Z80 Assembly
org &1000 PrintChar equ &BB5A   ;reg usage: ;DE = VM'S Program Counter ;IXL = VM's Accumulator main: ld ixl,0 ld de,Computer_Zero_RAM_2_plus_2 call Computer_Zero_VM ld a,ixl call ShowHex ;output to Amstrad CPC's screen call NewLine   ld ixl,0 ld de,Computer_Zero_RAM_7x8 call Computer_Zero_VM ld a,ixl jp ShowHex ;output and return to basic.   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;these two functions are related to displaying the output ; and have nothing to do with the virtual machine itself. ShowHex: push af and %11110000 rrca rrca rrca rrca call PrintHexChar pop af and %00001111 ;call PrintHexChar ;execution flows into it naturally. PrintHexChar: ;converts hex to ascii or a ;Clear Carry Flag daa add a,&F0 adc a,&40 jp PrintChar   NewLine: push af ld a,13 call PrintChar ld a,10 call PrintChar pop af ret   ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;   Computer_Zero_VM: ld a,(de) ;opcode fetch call UnpackOpcode ;stores opcode in B, operand in C push de ld de,Opcode_Table ld a,b rlca ;index times 2 for word data   ld e,a ld a,(de) ld L,a inc de ld a,(de) ld h,a ;LD HL,(DE)   pop de jp (hl) ;register state after this jump: ;DE = program counter ;HL = address of instruction implementation ;C = operand of the instruction we're about to execute ;IXL = accumulator       overhead: ld a,e inc a and %00011111 ;ensures we stay within the 32 byte address space. ld e,a jp Computer_Zero_VM     UnpackOpcode: push af and %11100000 rlca rlca rlca ld b,a ;opcode in B pop af and %00011111 ld c,a ;operand in C dummy: ret       align 256 ;ensures the following table is page-aligned ;this lets us index it much faster. Opcode_Table: dw vmNOP dw vmLDA dw vmSTA dw vmADD dw vmSUB dw vmBRZ dw vmJMP dw vmSTP   vmNOP: jp overhead ;do nothing vmLDA: push de ld e,c ;offset DE by the operand ld a,(de) ;load from that address ld ixl,a ;and store it in the accumulator pop de jp overhead vmSTA: push de ld e,c ;offset DE by the operand ld a,ixl ;get the accumulator ld (de),a ;store it into (DE) pop de jp overhead vmADD: push de ld e,c ;offset DE by the operand ld a,(de) ;load from that address add ixl ;and add that value to the accumulator ld ixl,a ;then set the new accumulator pop de jp overhead vmSUB: push de ld e,c ;offset DE by the operand ld a,(de) ld b,a ld a,ixl sub b ld ixl,a pop de noBRZ: jp overhead vmBRZ: ld a,ixl or a jr nz, noBRZ vmJMP: ld e,c jp Computer_Zero_VM vmSTP: ret ;return to main   align 256 Computer_Zero_RAM_2_plus_2: db %00100011,%01100100 db %11100000,%00000010 db %00000010,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 align 256 Computer_Zero_RAM_7x8: db %00101100,%01101010 db %01001100,%00101011 db %10001101,%01001011 db %10101000,%11000000 db %00101100,%11100000 db %00001000,%00000111 db %00000000,%00000001 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000 db %00000000,%00000000
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
#Nim
Nim
echo 1e234 * 1e234 # inf echo 1e234 * -1e234 # -inf echo 1 / Inf # 0 echo Inf + -Inf # nan echo NaN # nan   echo NaN == NaN # false echo 0.0 == -0.0 # true echo 0.0 * NaN # nan echo NaN * 0.0 # nan echo 0.0 * Inf # nan echo Inf * 0.0 # nan
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
#OCaml
OCaml
# infinity;; - : float = infinity # neg_infinity;; - : float = neg_infinity # nan;; - : float = nan # -0.;; - : float = -0. # -. 0.;; - : float = -0. # 1. /. 0.;; - : float = infinity # -1. /. 0.;; - : float = neg_infinity # -. infinity;; - : float = neg_infinity # infinity +. neg_infinity;; - : float = nan # 0. /. 0.;; - : float = nan # infinity /. infinity;; - : float = nan # nan = nan;; - : bool = false # nan == nan;; - : bool = true # 0. *. infinity;; - : float = nan # 0. = -0.;; - : bool = true # 0. == -0.;; - : bool = false
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.
#C.2B.2B
C++
# # snusp.icn, A Modular SNUSP interpreter #   $define VERSION 0.6   # allow a couple of cli options link options   # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4   record position(row, col) global dir, ip, ram   procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug   opts := options(argv, "-h! -v! -d!", errorproc) \opts["v"] & verbose := 1 \opts["h"] & show_help(verbose) \opts["d"] & debug := 1   ip := position(1,1)   # initial direction dir := DRIGHT   # prepare initial memory ram := list(1, 0)   # prepare code field codespace := []   fn := open(argv[1], "r") | &input if (fn === &input) & \opts["h"] then return   while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) # track starting indicator if /col := find("$", codespace[row]) then { ip.row := row ip.col := col } row +:= 1 }   if \verbose then { write("Starting at ", ip.row, ", ", ip.col, " with codespace:") every write(!codespace) }   dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]", " row: ", ip.row, " col: ", ip.col, " dp: ", dp, " ram[dp]: ", ram[dp]) } case ch of { # six of the bf instructions "+": ram[dp] +:= 1 "-": ram[dp] -:= 1 ">": resize(dp +:= 1) "<": dp -:= 1 ".": writes(char(ram[dp]) | char(0)) ",": ram[dp] := getche() # direction change, LURD, RULD, SKIP, SKIPZ "\\": { # LURD case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } "/": { # RULD case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } "!": step() "?": { # skipz if ram[dp] = 0 then { step() } } # modular SNUSP "@": { # Enter push(dirs, dir) push(ips, copy(ip)) } "#": { # Leave if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end   # advance the ip depending on direction procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end   # enlarge memory when needed procedure resize(elements) until *ram >= elements do put(ram, 0) end   # quick help or verbose help procedure show_help(verbose) write("SNUSP interpeter in Unicon, version ", VERSION) write("CORE and MODULAR, not yet BLOATED") write() write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]") write(" -h, help") write(" -v, verbose (and verbose help") write(" -d, debug (step tracer)") if \verbose then { write() write("Instructions:") write(" + INCR, Increment current memory location") write(" - DECR, Decrement current memory location") write(" > RIGHT, Advance memory pointer") write(" < LEFT, Retreat memory pointer") write(" . WRITE, Output contents of current memory cell, in ASCII") write(" , READ, Accept key and place byte value in current memory cell") write(" \\ LURD, If going:") write(" left, go up") write(" up, go left") write(" right, go down") write(" down, go right") write(" / RULD, If going:") write(" right, go up") write(" up, go right") write(" left, go down") write(" down, go left") write(" !, SKIP, Move forward one step in current direction") write(" ?, SKIPZ, If current memory cell is zero then SKIP") write("Modular SNUSP adds:") write(" @, ENTER, Push direction and instruction pointer") write(" #, LEAVE, Pop direction and instruction pointer and SKIP") write() write("All other characters are NOOP, explicitly includes =,|,spc") write(" $, can set the starting location; first one found") write() write("Hello world examples:") write() write("CORE SNUSP:") write("/++++!/===========?\\>++.>+.+++++++..+++\\") write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./") write("$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\") write(" \\==-<<<<+>+++/ /=.>.+>.--------.-/") write() write("Modular SNUSP:") write(" /@@@@++++# #+++@@\ #-----@@@\\n") write("$@\\H.@/e.+++++++l.l.+++o.>>++++.< .<@/w.@\\o.+++r.++@\\l.@\\d.>+.@/.#") write(" \\@@@@=>++++>+++++<<@+++++# #---@@/!=========/!==/") write() } end
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.
#Delphi
Delphi
  procedure Check(Condition1: Boolean; Condition2: Boolean) begin if Condition1 = True then begin if Condition2 = True then BothConditionsAreTrue else FirstConditionIsTrue; end else if Condition2 = True then SecondConditionIsTrue else NoConditionIsTrue; 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
#EchoLisp
EchoLisp
  ;; the standard and secure way is to use the (expt a b) function (expt 5 (expt 3 2)) ;; 5 ** ( 3 ** 2) → 1953125 (expt (expt 5 3) 2) ;; (5 ** 3) ** 2 → 15625   ;; infix EchoLisp may use the ** operator, which right associates (lib 'match) (load 'infix.glisp)   (5 ** 3 ** 2) → 1953125 ((5 ** 3) ** 2) → 15625 (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
#Factor
Factor
USING: formatting math.functions ;   5 3 2 ^ ^ "5 3 2 ^ ^  %d\n" printf   5 3 ^ 2 ^ "5 3 ^ 2 ^  %d\n" printf
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
#Fortran
Fortran
write(*, "(a, i0)") "5**3**2 = ", 5**3**2 write(*, "(a, i0)") "(5**3)**2 = ", (5**3)**2 write(*, "(a, i0)") "5**(3**2) = ", 5**(3**2)
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Scala
Scala
object Factorion extends App { private def is_factorion(i: Int, b: Int): Boolean = { var sum = 0L var j = i while (j > 0) { sum += f(j % b) j /= b } sum == i }   private val f = Array.ofDim[Long](12) f(0) = 1L (1 until 12).foreach(n => f(n) = f(n - 1) * n) (9 to 12).foreach(b => { print(s"factorions for base $b:") (1 to 1500000).filter(is_factorion(_, b)).foreach(i => print(s" $i")) println }) }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Sidef
Sidef
func max_power(b = 10) { var m = 1 var f = (b-1)! while (m*f >= b**(m-1)) { m += 1 } return m-1 }   func factorions(b = 10) {   var result = [] var digits = @^b var fact = digits.map { _! }   for k in (1 .. max_power(b)) { digits.combinations_with_repetition(k, {|*comb| var n = comb.sum_by { fact[_] } if (n.digits(b).sort == comb) { result << n } }) }   return result }   for b in (2..12) { var r = factorions(b) say "Base #{'%2d' % b} factorions: #{r}" }
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.
#VBScript
VBScript
  test_arr_1 = Array(1,2,3,4,5,6,7,8,9,10) test_arr_2 = Array(1,2,3,4,5,6,7,8,9,10)   WScript.StdOut.Write "Scenario 1: Create a new array" WScript.StdOut.WriteLine WScript.StdOut.Write "Input: " & Join(test_arr_1,",") WScript.StdOut.WriteLine WScript.StdOut.Write "Output: " & filter_create(test_arr_1) WScript.StdOut.WriteBlankLines(2)   WScript.StdOut.Write "Scenario 2: Destructive approach" WScript.StdOut.WriteLine WScript.StdOut.Write "Input: " & Join(test_arr_2,",") WScript.StdOut.WriteLine WScript.StdOut.Write "Output: " & filter_destruct(test_arr_2) WScript.StdOut.WriteBlankLines(2)   Function filter_create(arr) ReDim arr_new(0) For i = 0 To UBound(arr) If arr(i) Mod 2 = 0 Then If arr_new(0) = "" Then arr_new(0) = arr(i) Else ReDim Preserve arr_new(UBound(arr_new)+1) arr_new(UBound(arr_new)) = arr(i) End If End If Next filter_create = Join(arr_new,",") End Function   Function filter_destruct(arr) count = 0 For i = 0 To UBound(arr) If arr(i) Mod 2 <> 0 Then count = count + 1 For j = i To UBound(arr) If j + 1 <= UBound(arr) Then arr(j) = arr(j+1) End If Next End If Next ReDim Preserve arr(UBound(arr)-count) filter_destruct = Join(arr,",") End Function
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
#Processing
Processing
for (int i = 0; i < width; i++) { if (i % 3 == 0 && i % 5 == 0) { stroke(255, 255, 0); println("FizzBuzz!"); } else if (i % 5 == 0) { stroke(0, 255, 0); println("Buzz"); } else if (i % 3 == 0) { stroke(255, 0, 0); println("Fizz"); } else { stroke(0, 0, 255); println(i); } line(i, 0, i, height); }
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.
#Delphi
Delphi
  ; the first twenty primes (primes 20) → { 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 }   ; a stream to generate primes from a (define (primes-from a) (let ((p (next-prime a))) (stream-cons p (primes-from p))))   ; primes between 100,150 (for/list ((p (primes-from 100))) #:break (> p 150) p) → (101 103 107 109 113 127 131 137 139 149)   ; the built-in function (primes-pi )counts the number of primes < a ; count in [7700 ... 8000] (- (primes-pi 8000) (primes-pi 7700) → 30   ; nth-prime (nth-prime 10000) → 104729   ;; big ones (lib 'bigint) (define (p-digits n) (printf "(next-prime  %d ! ) has %d digits" n (number-length (next-prime (factorial n )))))   (next-prime 0! ) has 1 digits (next-prime 10! ) has 7 digits (next-prime 100! ) has 158 digits (next-prime 200! ) has 375 digits (next-prime 300! ) has 615 digits (next-prime 400! ) has 869 digits ;; 9400 msec (FireFox)   ; is prime (1 + 116!) ? (prime? (1+ (factorial 116))) → #t    
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
#GAP
GAP
fib := function(n) local a; a := [[0, 1], [1, 1]]^n; return a[1][2]; 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
#Plain_English
Plain English
To run: Start up. Show the factors of 11. Show the factors of 21. Show the factors of 519. Wait for the escape key. Shut down.   To show the factors of a number: Write "The factors of " then the number then ":" on the console. Find a square root of the number. Loop. If a counter is past the square root, write "" on the console; exit. Divide the number by the counter giving a quotient and a remainder. If the remainder is 0, show the counter and the quotient. Repeat.   A factor is a number.   To show a factor and another factor: If the factor is not the other factor, write "" then the factor then " " then the other factor then " " on the console without advancing; exit. Write "" then the factor on the console without advancing.
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Ada
Ada
# HQ9+ interpreter   # execute an HQ9+ program in the code string - code is not case sensitive hq9 := proc( code :: string ) is local hq9Accumulator := 0; # the HQ9+ accumulator local hq9Operations  := # table of HQ9+ operations and their implemntations [ "q" ~ proc() is print( code ) end , "h" ~ proc() is print( "Hello, world!" ) end , "9" ~ proc() is local writeBottles := proc( bottleCount :: number, message :: string ) is print( bottleCount & " bottle" & if bottleCount <> 1 then "s " else " " fi & message ) end;   for bottles from 99 to 1 by -1 do writeBottles( bottles, "of beer on the wall" ); writeBottles( bottles, "of beer" ); print( "Take one down, pass it around," ); if bottles > 1 then writeBottles( bottles - 1, "of beer on the wall." ) fi; print() od; print( "No more bottles of beer on the wall." ) end , "+" ~ proc() is inc hq9Accumulator, 1 end ]; for op in lower( code ) do if hq9Operations[ op ] <> null then hq9Operations[ op ]() else print( '"' & op & '" not implemented' ) fi od end;   # prompt for HQ9+ code and execute it, repeating until an empty code string is entered scope local code; do write( "HQ9+> " ); code := io.read(); hq9( code ) until code = "" epocs;
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Agena
Agena
# HQ9+ interpreter   # execute an HQ9+ program in the code string - code is not case sensitive hq9 := proc( code :: string ) is local hq9Accumulator := 0; # the HQ9+ accumulator local hq9Operations  := # table of HQ9+ operations and their implemntations [ "q" ~ proc() is print( code ) end , "h" ~ proc() is print( "Hello, world!" ) end , "9" ~ proc() is local writeBottles := proc( bottleCount :: number, message :: string ) is print( bottleCount & " bottle" & if bottleCount <> 1 then "s " else " " fi & message ) end;   for bottles from 99 to 1 by -1 do writeBottles( bottles, "of beer on the wall" ); writeBottles( bottles, "of beer" ); print( "Take one down, pass it around," ); if bottles > 1 then writeBottles( bottles - 1, "of beer on the wall." ) fi; print() od; print( "No more bottles of beer on the wall." ) end , "+" ~ proc() is inc hq9Accumulator, 1 end ]; for op in lower( code ) do if hq9Operations[ op ] <> null then hq9Operations[ op ]() else print( '"' & op & '" not implemented' ) fi od end;   # prompt for HQ9+ code and execute it, repeating until an empty code string is entered scope local code; do write( "HQ9+> " ); code := io.read(); hq9( code ) until code = "" epocs;
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
#68000_Assembly
68000 Assembly
ExponentUnsigned: ;input: D0.W = BASE ; D1.W = EXPONENT ; OUTPUTS TO D0 ; NO OVERFLOW PROTECTION - USE AT YOUR OWN RISK! ;HIGH WORDS OF D0 AND D1 ARE CLEARED. ;clobbers D1   MOVE.L D2,-(SP)   ;using DBRAs lets us simultaneously subtract and compare DBRA D1,.test_if_one MOVEQ.L #1,D0 ;executes only if D1 was 0 to start with .test_if_one: DBRA D1,.go bra .done ;executes only if D1 was 1 to start with .go: ;else, multiply D0 by its ORIGINAL self repeatedly. MOVE.L D0,D2 .loop: MULU D0,D2 DBRA D1,.loop   MOVE.L D2,D0 .done: MOVE.L (SP)+,D2 RTS
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
#Oforth
Oforth
>10.0 1000.0 powf PInf == println 1 ok >10.0 1000.0 powf neg NInf == println 1 ok
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
#Ol
Ol
(import (scheme inexact))   (print "infinity: " (/ 1 0)) (print "minus infinity: " (log 0))   ; note: (sqrt -1) function will produce 0+i complex number ; so we need to use simpler function "fsqrt"   (import (owl math fp)) (print "not-a-number: " (fsqrt -1))   ; note: your must use equal? or eqv? but not eq? for comparison (print "is this is not a number? " (equal? (fsqrt -1) +nan.0))  
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.
#COBOL
COBOL
# # snusp.icn, A Modular SNUSP interpreter #   $define VERSION 0.6   # allow a couple of cli options link options   # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4   record position(row, col) global dir, ip, ram   procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug   opts := options(argv, "-h! -v! -d!", errorproc) \opts["v"] & verbose := 1 \opts["h"] & show_help(verbose) \opts["d"] & debug := 1   ip := position(1,1)   # initial direction dir := DRIGHT   # prepare initial memory ram := list(1, 0)   # prepare code field codespace := []   fn := open(argv[1], "r") | &input if (fn === &input) & \opts["h"] then return   while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) # track starting indicator if /col := find("$", codespace[row]) then { ip.row := row ip.col := col } row +:= 1 }   if \verbose then { write("Starting at ", ip.row, ", ", ip.col, " with codespace:") every write(!codespace) }   dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]", " row: ", ip.row, " col: ", ip.col, " dp: ", dp, " ram[dp]: ", ram[dp]) } case ch of { # six of the bf instructions "+": ram[dp] +:= 1 "-": ram[dp] -:= 1 ">": resize(dp +:= 1) "<": dp -:= 1 ".": writes(char(ram[dp]) | char(0)) ",": ram[dp] := getche() # direction change, LURD, RULD, SKIP, SKIPZ "\\": { # LURD case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } "/": { # RULD case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } "!": step() "?": { # skipz if ram[dp] = 0 then { step() } } # modular SNUSP "@": { # Enter push(dirs, dir) push(ips, copy(ip)) } "#": { # Leave if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end   # advance the ip depending on direction procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end   # enlarge memory when needed procedure resize(elements) until *ram >= elements do put(ram, 0) end   # quick help or verbose help procedure show_help(verbose) write("SNUSP interpeter in Unicon, version ", VERSION) write("CORE and MODULAR, not yet BLOATED") write() write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]") write(" -h, help") write(" -v, verbose (and verbose help") write(" -d, debug (step tracer)") if \verbose then { write() write("Instructions:") write(" + INCR, Increment current memory location") write(" - DECR, Decrement current memory location") write(" > RIGHT, Advance memory pointer") write(" < LEFT, Retreat memory pointer") write(" . WRITE, Output contents of current memory cell, in ASCII") write(" , READ, Accept key and place byte value in current memory cell") write(" \\ LURD, If going:") write(" left, go up") write(" up, go left") write(" right, go down") write(" down, go right") write(" / RULD, If going:") write(" right, go up") write(" up, go right") write(" left, go down") write(" down, go left") write(" !, SKIP, Move forward one step in current direction") write(" ?, SKIPZ, If current memory cell is zero then SKIP") write("Modular SNUSP adds:") write(" @, ENTER, Push direction and instruction pointer") write(" #, LEAVE, Pop direction and instruction pointer and SKIP") write() write("All other characters are NOOP, explicitly includes =,|,spc") write(" $, can set the starting location; first one found") write() write("Hello world examples:") write() write("CORE SNUSP:") write("/++++!/===========?\\>++.>+.+++++++..+++\\") write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./") write("$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\") write(" \\==-<<<<+>+++/ /=.>.+>.--------.-/") write() write("Modular SNUSP:") write(" /@@@@++++# #+++@@\ #-----@@@\\n") write("$@\\H.@/e.+++++++l.l.+++o.>>++++.< .<@/w.@\\o.+++r.++@\\l.@\\d.>+.@/.#") write(" \\@@@@=>++++>+++++<<@+++++# #---@@/!=========/!==/") write() } end
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.
#DUP
DUP
{two-conditional if operator implementation} { [ top cond. = true ][ top cond. = false ]} { [ 2nd = true ][2nd = false ] [ 2nd = true ][ 2nd = false] } [(((([[)))!)))%%%%%][)))))!)%%%%%]?][[))))!))%%%%%][))))))!%%%%%]?]?]⇒¿  
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.
#E
E
pragma.enable("lambda-args") # The feature is still experimental syntax   def makeIf2Control(evalFn, tf, ft, ff) { return def if2Control { to only1__control_0(tf) { return makeIf2Control(evalFn, tf, ft, ff) } to only2__control_0(ft) { return makeIf2Control(evalFn, tf, ft, ff) } to else__control_0 (ff) { return makeIf2Control(evalFn, tf, ft, ff) } to run__control() { def [[a :boolean, b :boolean], # Main parameters evaluated tt # First block ("then" case) ] := evalFn() return ( if (a) { if (b) {tt} else {tf} } \ else { if (b) {ft} else {ff} } )() } } }   def if2 { # The verb here is composed from the keyword before the brace, the number of # parameters in the parentheses, and the number of parameters after the # keyword. to then__control_2_0(evalFn) { # evalFn, when called, evaluates the expressions in parentheses, then # returns a pair of those expressions and the first { block } as a # closure. return makeIf2Control(evalFn, fn {}, fn {}, fn {}) } }   for a in [false,true] { for b in [false,true] { if2 (a, b) then { println("both") } only1 { println("a true") } only2 { println("b true") } else { println("neither") } } }
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
#FreeBASIC
FreeBASIC
' FB 1.05.0   ' The exponentation operator in FB is ^ rather than **. ' In the absence of parenthesis this operator is ' left-associative. So the first example ' will have the same value as the second example.   Print "5^3^2 =>"; 5^3^2 Print "(5^3)^2 =>"; (5^3)^2 Print "5^(3^2) =>"; 5^(3^2) Sleep
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
#Frink
Frink
println["5^3^2 = " + 5^3^2] println["(5^3)^2 = " + (5^3)^2] println["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
#Go
Go
package main   import "fmt" import "math"   func main() { var a, b, c float64 a = math.Pow(5, math.Pow(3, 2)) b = math.Pow(math.Pow(5, 3), 2) c = math.Pow(5, math.Pow(3, 2)) fmt.Printf("5^3^2 = %.0f\n", a) fmt.Printf("(5^3)^2 = %.0f\n", b) fmt.Printf("5^(3^2) = %.0f\n", c) }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Swift
Swift
var fact = Array(repeating: 0, count: 12)   fact[0] = 1   for n in 1..<12 { fact[n] = fact[n - 1] * n }   for b in 9...12 { print("The factorions for base \(b) are:")   for i in 1..<1500000 { var sum = 0 var j = i   while j > 0 { sum += fact[j % b] j /= b }   if sum == i { print("\(i)", terminator: " ") fflush(stdout) } }   print("\n") }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Vlang
Vlang
import strconv   fn main() { // cache factorials from 0 to 11 mut fact := [12]u64{} fact[0] = 1 for n := u64(1); n < 12; n++ { fact[n] = fact[n-1] * n }   for b := 9; b <= 12; b++ { println("The factorions for base $b are:") for i := u64(1); i < 1500000; i++ { digits := strconv.format_uint(i, b) mut sum := u64(0) for digit in digits { if digit < `a` { sum += fact[digit-`0`] } else { sum += fact[digit+10-`a`] } } if sum == i { print("$i ") } } println("\n") } }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Wren
Wren
// cache factorials from 0 to 11 var fact = List.filled(12, 0) fact[0] = 1 for (n in 1..11) fact[n] = fact[n-1] * n   for (b in 9..12) { System.print("The factorions for base %(b) are:") for (i in 1...1500000) { var sum = 0 var j = i while (j > 0) { var d = j % b sum = sum + fact[d] j = (j/b).floor } if (sum == i) System.write("%(i) ") } System.print("\n") }
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.
#Visual_Basic_.NET
Visual Basic .NET
Module Filter   Sub Main() Dim array() As Integer = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10} Dim newEvenArray() As Integer   Console.WriteLine("Current Array:") For Each i As Integer In array Console.WriteLine(i) Next   newEvenArray = filterArrayIntoNewArray(array)   Console.WriteLine("New Filtered Array:") For Each i As Integer In newEvenArray Console.WriteLine(i) Next   array = changeExistingArray(array)   Console.WriteLine("Orginal Array After Filtering:") For Each i As Integer In array Console.WriteLine(i) Next End Sub   Private Function changeExistingArray(array() As Integer) As Integer() Return filterArrayIntoNewArray(array) End Function   Private Function filterArrayIntoNewArray(array() As Integer) As Integer() Dim result As New List(Of Integer) For Each element As Integer In array If element Mod 2 = 0 Then result.Add(element) End If Next Return result.ToArray End Function   End Module  
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
#Prolog
Prolog
fizzbuzz :- foreach(between(1, 100, X), print_item(X)).   print_item(X) :- ( 0 is X mod 15 -> print('FizzBuzz') ; 0 is X mod 3 -> print('Fizz') ; 0 is X mod 5 -> print('Buzz') ; print(X) ), nl.
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.
#EchoLisp
EchoLisp
  ; the first twenty primes (primes 20) → { 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 }   ; a stream to generate primes from a (define (primes-from a) (let ((p (next-prime a))) (stream-cons p (primes-from p))))   ; primes between 100,150 (for/list ((p (primes-from 100))) #:break (> p 150) p) → (101 103 107 109 113 127 131 137 139 149)   ; the built-in function (primes-pi )counts the number of primes < a ; count in [7700 ... 8000] (- (primes-pi 8000) (primes-pi 7700) → 30   ; nth-prime (nth-prime 10000) → 104729   ;; big ones (lib 'bigint) (define (p-digits n) (printf "(next-prime  %d ! ) has %d digits" n (number-length (next-prime (factorial n )))))   (next-prime 0! ) has 1 digits (next-prime 10! ) has 7 digits (next-prime 100! ) has 158 digits (next-prime 200! ) has 375 digits (next-prime 300! ) has 615 digits (next-prime 400! ) has 869 digits ;; 9400 msec (FireFox)   ; is prime (1 + 116!) ? (prime? (1+ (factorial 116))) → #t    
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
#Gecho
Gecho
0 1 dup wover + dup wover + dup wover + dup wover +
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
#Polyglot:PL.2FI_and_PL.2FM
Polyglot:PL/I and PL/M
factors_100H: procedure options (main);   /* PL/I DEFINITIONS */ %include 'pg.inc'; /* PL/M DEFINITIONS: CP/M BDOS SYSTEM CALL AND CONSOLE I/O ROUTINES, ETC. */ /* DECLARE BINARY LITERALLY 'ADDRESS', CHARACTER LITERALLY 'BYTE'; DECLARE SADDR LITERALLY '.', BIT LITERALLY 'BYTE'; DECLARE FIXED LITERALLY ' '; BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; PRSTRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END; PRCHAR: PROCEDURE( C ); DECLARE C CHARACTER; CALL BDOS( 2, C ); END; PRNL: PROCEDURE; CALL PRCHAR( 0DH ); CALL PRCHAR( 0AH ); END; PRNUMBER: PROCEDURE( N ); DECLARE N ADDRESS; DECLARE V ADDRESS, N$STR( 6 ) BYTE, W BYTE; N$STR( W := LAST( N$STR ) ) = '$'; N$STR( W := W - 1 ) = '0' + ( ( V := N ) MOD 10 ); DO WHILE( ( V := V / 10 ) > 0 ); N$STR( W := W - 1 ) = '0' + ( V MOD 10 ); END; CALL BDOS( 9, .N$STR( W ) ); END PRNUMBER; MODF: PROCEDURE( A, B )ADDRESS; DECLARE ( A, B )ADDRESS; RETURN( A MOD B ); END MODF; /* END LANGUAGE DEFINITIONS */   /* TASK */ DECLARE ( I, N ) FIXED BINARY; DO N = 90 TO 100; CALL PRSTRING( SADDR( 'FACTORS OF: $' ) ); CALL PRNUMBER( N ); CALL PRCHAR( ':' ); DO I = 1 TO N; IF MODF( N, I ) = 0 THEN DO; CALL PRCHAR( ' ' ); CALL PRNUMBER( I ); END; END; CALL PRNL; END; EOF: end factors_100H;
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#ALGOL_68
ALGOL 68
# the increment-only accumulator # INT hq9accumulator := 0;   # interpret a HQ9+ code string # PROC hq9 = ( STRING code )VOID: FOR i TO UPB code DO CHAR op = code[ i ]; IF op = "Q" OR op = "q" THEN # display the program # print( ( code, newline ) ) ELIF op = "H" OR op = "h" THEN print( ( "Hello, world!", newline ) ) ELIF op = "9" THEN # 99 bottles of beer # FOR bottles FROM 99 BY -1 TO 1 DO STRING bottle count = whole( bottles, 0 ) + IF bottles > 1 THEN " bottles" ELSE " bottle" FI; print( ( bottle count, " of beer on the wall", newline ) ); print( ( bottle count, " bottles of beer.", newline ) ); print( ( "Take one down, pass it around,", newline ) ); IF bottles > 1 THEN print( ( whole( bottles - 1, 0 ), " bottles of beer on the wall.", newline, newline ) ) FI OD; print( ( "No more bottles of beer on the wall.", newline ) ) ELIF op = "+" THEN # increment the accumulator # hq9accumulator +:= 1 ELSE # unimplemented operation # print( ( """", op, """ not implemented", newline ) ) FI OD;     # test the interpreter # BEGIN STRING code; print( ( "HQ9+> " ) ); read( ( code, newline ) ); hq9( code ) END
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
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   INT FUNC PowerI(INT base,exp) INT res,i   IF exp<0 THEN Break() FI   res=1 FOR i=1 TO exp DO res==*base OD RETURN (res)   PROC PowerR(REAL POINTER base INT exp REAL POINTER res) INT i REAL tmp   IF exp<0 THEN Break() FI   IntToReal(1,res) FOR i=1 TO exp DO RealMult(res,base,tmp) RealAssign(tmp,res) OD RETURN   PROC TestI(INT base,exp) INT res   res=PowerI(base,exp) PrintF("%I^%I=%I%E",base,exp,res) RETURN   PROC TestR(REAL POINTER base INT exp) REAL res   PowerR(base,exp,res) PrintR(base) PrintF("^%I=",exp) PrintRE(res) RETURN   PROC Main() REAL base   Put(125) PutE() ;clear screen   TestI(27,3) TestI(2,12) TestI(-3,9) TestI(1,1000) TestI(20000,0)   ValR("3.141592654",base) TestR(base,10) ValR("-1.11",base) TestR(base,99) ValR("0.123456789",base) TestR(base,1) ValR("987654.321",base) TestR(base,0) 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
#Ada
Ada
package Integer_Exponentiation is -- int^int procedure Exponentiate (Argument : in Integer; Exponent : in Natural; Result  : out Integer); function "**" (Left  : Integer; Right : Natural) return Integer;   -- real^int procedure Exponentiate (Argument : in Float; Exponent : in Integer; Result  : out Float); function "**" (Left  : Float; Right : Integer) return Float; end Integer_Exponentiation;
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
#Oz
Oz
declare Inf = 1.0e234 * 1.0e234 MinusInf = 1.0e234 * ~1.0e234 Zero = 1.0 / Inf MinusZero = 1.0 / MinusInf NaN = 0.0 / 0.0   {System.showInfo "infinite: "#Inf} {System.showInfo "-infinite: "#MinusInf} {System.showInfo "0: "#Zero} {System.showInfo "-0: "#MinusZero} %% seems to be identical to Zero {System.showInfo "NaN: "#NaN}   {System.showInfo "inf + -inf: "#Inf+MinusInf} {System.showInfo "NaN * 0: "#NaN*0.0} {System.showInfo "0 * NaN: "#0.0*NaN} {System.showInfo "inf * 0: "#Inf*0.0} {System.showInfo "0 * inf: "#0.0*Inf}   {Show NaN == NaN} %% shows 'true' ! {Show Zero == MinusZero}   {Show 1.0/0.0 == Inf} %% true {Show 1.0/~0.0 == MinusInf} %% true
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.
#D
D
# # snusp.icn, A Modular SNUSP interpreter #   $define VERSION 0.6   # allow a couple of cli options link options   # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4   record position(row, col) global dir, ip, ram   procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug   opts := options(argv, "-h! -v! -d!", errorproc) \opts["v"] & verbose := 1 \opts["h"] & show_help(verbose) \opts["d"] & debug := 1   ip := position(1,1)   # initial direction dir := DRIGHT   # prepare initial memory ram := list(1, 0)   # prepare code field codespace := []   fn := open(argv[1], "r") | &input if (fn === &input) & \opts["h"] then return   while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) # track starting indicator if /col := find("$", codespace[row]) then { ip.row := row ip.col := col } row +:= 1 }   if \verbose then { write("Starting at ", ip.row, ", ", ip.col, " with codespace:") every write(!codespace) }   dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]", " row: ", ip.row, " col: ", ip.col, " dp: ", dp, " ram[dp]: ", ram[dp]) } case ch of { # six of the bf instructions "+": ram[dp] +:= 1 "-": ram[dp] -:= 1 ">": resize(dp +:= 1) "<": dp -:= 1 ".": writes(char(ram[dp]) | char(0)) ",": ram[dp] := getche() # direction change, LURD, RULD, SKIP, SKIPZ "\\": { # LURD case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } "/": { # RULD case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } "!": step() "?": { # skipz if ram[dp] = 0 then { step() } } # modular SNUSP "@": { # Enter push(dirs, dir) push(ips, copy(ip)) } "#": { # Leave if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end   # advance the ip depending on direction procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end   # enlarge memory when needed procedure resize(elements) until *ram >= elements do put(ram, 0) end   # quick help or verbose help procedure show_help(verbose) write("SNUSP interpeter in Unicon, version ", VERSION) write("CORE and MODULAR, not yet BLOATED") write() write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]") write(" -h, help") write(" -v, verbose (and verbose help") write(" -d, debug (step tracer)") if \verbose then { write() write("Instructions:") write(" + INCR, Increment current memory location") write(" - DECR, Decrement current memory location") write(" > RIGHT, Advance memory pointer") write(" < LEFT, Retreat memory pointer") write(" . WRITE, Output contents of current memory cell, in ASCII") write(" , READ, Accept key and place byte value in current memory cell") write(" \\ LURD, If going:") write(" left, go up") write(" up, go left") write(" right, go down") write(" down, go right") write(" / RULD, If going:") write(" right, go up") write(" up, go right") write(" left, go down") write(" down, go left") write(" !, SKIP, Move forward one step in current direction") write(" ?, SKIPZ, If current memory cell is zero then SKIP") write("Modular SNUSP adds:") write(" @, ENTER, Push direction and instruction pointer") write(" #, LEAVE, Pop direction and instruction pointer and SKIP") write() write("All other characters are NOOP, explicitly includes =,|,spc") write(" $, can set the starting location; first one found") write() write("Hello world examples:") write() write("CORE SNUSP:") write("/++++!/===========?\\>++.>+.+++++++..+++\\") write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./") write("$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\") write(" \\==-<<<<+>+++/ /=.>.+>.--------.-/") write() write("Modular SNUSP:") write(" /@@@@++++# #+++@@\ #-----@@@\\n") write("$@\\H.@/e.+++++++l.l.+++o.>>++++.< .<@/w.@\\o.+++r.++@\\l.@\\d.>+.@/.#") write(" \\@@@@=>++++>+++++<<@+++++# #---@@/!=========/!==/") write() } end
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.
#EchoLisp
EchoLisp
  (define-syntax-rule (if2 cond1 cond2 both cond1-only cond2-only none) ;; new syntax ;; will expand to : (if cond1 (if cond2 both cond1-only) (if cond2 cond2-only none))) → #syntax:if2   (define (num-test n) (if2 (positive? n) (exact? n) "positive and exact" "positive and inexact" "negative and exact" "negative and inexact"))   (num-test 3/4) → "positive and exact" (num-test -666) → "negative and exact" (num-test -666.42) → "negative and inexact" (num-test PI) → "positive and inexact"    
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
#Groovy
Groovy
println(" 5 ** 3 ** 2 == " + 5**3**2) println("(5 ** 3)** 2 == " + (5**3)**2) println(" 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
#Haskell
Haskell
λ> :i (^) (^) :: (Num a, Integral b) => a -> b -> a -- Defined in ‘GHC.Real’ infixr 8 ^ λ> :i (**) class Fractional a => Floating a where ... (**) :: a -> a -> a ... -- Defined in ‘GHC.Float’ infixr 8 ** λ> :i (^^) (^^) :: (Fractional a, Integral b) => a -> b -> a -- Defined in ‘GHC.Real’ infixr 8 ^^
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
#Io
Io
Io> 5**3**2 ==> 15625 Io> (5**3)**2 ==> 15625 Io> 5**(3**2) ==> 1953125 Io> 5 pow(3) pow(2) ==> 15625 Io> 5 **(3) **(2) ==> 15625 Io> Number getSlot("**") == Number getSlot("pow") ==> true Io>
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#VBScript
VBScript
' Factorions - VBScript - PG - 26/04/2020 Dim fact() nn1=9 : nn2=12 lim=1499999 ReDim fact(nn2) fact(0)=1 For i=1 To nn2 fact(i)=fact(i-1)*i Next For base=nn1 To nn2 list="" For i=1 To lim s=0 t=i Do While t<>0 d=t Mod base s=s+fact(d) t=t\base Loop If s=i Then list=list &" "& i Next Wscript.Echo "the factorions for base "& right(" "& base,2) &" are: "& list Next
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#zkl
zkl
var facts=[0..12].pump(List,fcn(n){ (1).reduce(n,fcn(N,n){ N*n },1) }); #(1,1,2,6....) fcn factorions(base){ fs:=List(); foreach n in ([1..1_499_999]){ sum,j := 0,n; while(j){ sum+=facts[j%base]; j/=base; } if(sum==n) fs.append(n); } fs }
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.
#Vlang
Vlang
fn reduce(mut a []int){ mut last := 0 for e in a { if e%2==0 { a[last] = e last++ } } a = a[..last] } fn main() { mut nums := [5,4,8,2,4,6,5,6,34,12,21] even := nums.filter(it%2==0) println('orig: $nums') println('even: $even') reduce(mut nums) println('dest: $nums') }
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
#PureBasic
PureBasic
fun fizzbuzz(n :: NumPositive) -> String: doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'. For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.``` ask: | num-modulo(n, 15) == 0 then: "FizzBuzz" | num-modulo(n, 3) == 0 then: "Fizz" | num-modulo(n, 5) == 0 then: "Buzz" | otherwise: num-to-string(n) end where: fizzbuzz(1) is "1" fizzbuzz(101) is "101" fizzbuzz(45) is "FizzBuzz" fizzbuzz(33) is "Fizz" fizzbuzz(25) is "Buzz" end   range(1, 101).map(fizzbuzz).each(print)
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.
#Elixir
Elixir
defmodule PrimesSoEMap do @typep stt :: {integer, integer, integer, Enumerable.integer, %{integer => integer}}   @spec advance(stt) :: stt defp advance {n, bp, q, bps?, map} do bps = if bps? === nil do Stream.drop(oddprms(), 1) else bps? end nn = n + 2 if nn >= q do inc = bp + bp nbps = bps |> Stream.drop(1) [nbp] = nbps |> Enum.take(1) advance {nn, nbp, nbp * nbp, nbps, map |> Map.put(nn + inc, inc)} else if Map.has_key?(map, nn) do {inc, rmap} = Map.pop(map, nn) [next] = Stream.iterate(nn + inc, &(&1 + inc)) |> Stream.drop_while(&(Map.has_key?(rmap, &1))) |> Enum.take(1) advance {nn, bp, q, bps, Map.put(rmap, next, inc)} else {nn, bp, q, bps, map} end end end   @spec oddprms() :: Enumerable.integer defp oddprms do # put first base prime cull seq in Map so never empty # advance base odd primes to 5 when initialized init = {7, 5, 25, nil, %{9 => 6}} [3, 5] # to avoid race, preseed with the first 2 elements... |> Stream.concat( Stream.iterate(init, &(advance &1)) |> Stream.map(fn {p,_,_,_,_} -> p end)) end   @spec primes() :: Enumerable.integer def primes do Stream.concat([2], oddprms()) end   end   IO.write "The first 20 primes are:\n( " PrimesSoEMap.primes() |> Stream.take(20) |> Enum.each(&(IO.write "#{&1} ")) IO.puts ")" IO.write "The primes between 100 to 150 are:\n( " PrimesSoEMap.primes() |> Stream.drop_while(&(&1<100)) |> Stream.take_while(&(&1<150)) |> Enum.each(&(IO.write "#{&1} ")) IO.puts ")" IO.write "The number of primes between 7700 and 8000 is: " PrimesSoEMap.primes() |> Stream.drop_while(&(&1<7700)) |> Stream.take_while(&(&1<8000)) |> Enum.count |> IO.puts IO.write "The 10,000th prime is: " PrimesSoEMap.primes() |> Stream.drop(9999) |> Enum.take(1) |> List.first |>IO.puts IO.write "The sum of all the priems to two million is: " testfunc = fn () -> ans = PrimesSoEMap.primes() |> Stream.take_while(&(&1<=2000000)) |> Enum.sum() |> IO.puts ans end :timer.tc(testfunc) |> (fn {t,_} -> IO.puts "This test bench took #{t} microseconds." end).()
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
#GFA_Basic
GFA Basic
  ' ' Compute nth Fibonacci number ' ' open a window for display OPENW 1 CLEARW 1 ' Display some fibonacci numbers ' Fib(46) is the largest number GFA Basic can reach ' (long integers are 4 bytes) FOR i%=0 TO 46 PRINT "fib(";i%;")=";@fib(i%) NEXT i% ' wait for a key press and tidy up ~INP(2) CLOSEW 1 ' ' Function to compute nth fibonacci number ' n must be in range 0 to 46, inclusive ' FUNCTION fib(n%) LOCAL n0%,n1%,nn%,i% n0%=0 n1%=1 SELECT n% CASE 0 RETURN n0% CASE 1 RETURN n1% DEFAULT FOR i%=2 TO n% nn%=n0%+n1% n0%=n1% n1%=nn% NEXT i% RETURN nn% ENDSELECT ENDFUNC  
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
#PowerShell
PowerShell
function Get-Factor ($a) { 1..$a | Where-Object { $a % $_ -eq 0 } }
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#ALGOL_W
ALGOL W
begin   procedure writeBottles( integer value bottleCount ) ; begin write( bottleCount, " bottle" ); if bottleCount not = 1 then writeon( "s " ) else writeon( " " ); end writeBottles ;   procedure hq9 ( string(32) value code  % code to execute %  ; integer value length % length of code  % ) ; for i := 0 until length - 1 do begin string(1) op;    % the increment-only accumulator % integer hq9accumulator;   hq9accumulator := 0; op  := code(i//1);   if op = "Q" or op = "q" then write( code ) else if op = "H" OR op = "h" then write( "Hello, World!" ) else if op = "9" then begin  % 99 bottles of beer % i_w := 1; s_w := 0; for bottles := 99 step -1 until 1 do begin writeBottles( bottles ); writeon( "of beer on the wall" ); writeBottles( bottles ); writeon( "of beer" );; write( "Take one down, pass it around," ); if bottles > 1 then begin writeBottles( bottles - 1 ); writeon( "of beer on the wall." ) end; write() end; write( "No more bottles of beer on the wall." ) end else if op = "+" then hq9accumulator := hq9accumulator + 1 else write( """", op, """ not implemented" ) end hq9 ;      % test the interpreter % begin string(32) code; integer codeLength; write( "HQ9+> " ); read( code ); codeLength := 31; while codeLength >= 0 and code(codeLength//1) = " " do codeLength := codeLength - 1; hq9( code, codeLength + 1 ) end end.
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Applesoft_BASIC
Applesoft BASIC
100 INPUT "HQ9+ : "; I$ 110 LET J$ = I$ + CHR$(13) 120 LET H$ = "HELLO, WORLD!" 130 LET B$ = "BOTTLES OF BEER" 140 LET W$ = " ON THE WALL" 150 LET W$ = W$ + CHR$(13) 160 FOR I = 1 TO LEN(I$) 170 LET C$ = MID$(J$, I, 1) 180 IF C$ = "H" THEN PRINT H$ 190 IF C$ = "Q" THEN PRINT I$ 200 LET A = A + (C$ = "+") 210 IF C$ <> "9" THEN 280 220 FOR B = 99 TO 1 STEP -1 230 PRINT B " " B$ W$ B " " B$ 240 PRINT "TAKE ONE DOWN, "; 250 PRINT "PASS IT AROUND" 260 PRINT B - 1 " " B$ W$ 270 NEXT B 280 NEXT I
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
#ALGOL_68
ALGOL 68
main:( INT two=2, thirty=30; # test constants # PROC VOID undefined;   # First implement exponentiation using a rather slow but sure FOR loop # PROC int pow = (INT base, exponent)INT: ( # PROC cannot be over loaded # IF exponent<0 THEN undefined FI; INT out:=( exponent=0 | 1 | base ); FROM 2 TO exponent DO out*:=base OD; out );   printf(($" One Gibi-unit is: int pow("g(0)","g(0)")="g(0)" - (cost: "g(0) " INT multiplications)"l$,two, thirty, int pow(two,thirty),thirty-1));   # implement exponentiation using a faster binary technique and WHILE LOOP # OP ** = (INT base, exponent)INT: ( BITS binary exponent:=BIN exponent ; # do exponent arithmetic in binary # INT out := IF bits width ELEM binary exponent THEN base ELSE 1 FI; INT sq := IF exponent < 0 THEN undefined; ~ ELSE base FI;   WHILE binary exponent := binary exponent SHR 1; binary exponent /= BIN 0 DO sq *:= sq; IF bits width ELEM binary exponent THEN out *:= sq FI OD; out );   printf(($" One Gibi-unit is: "g(0)"**"g(0)"="g(0)" - (cost: "g(0) " INT multiplications)"l$,two, thirty, two ** thirty,8));   OP ** = (REAL in base, INT in exponent)REAL: ( # ** INT Operator can be overloaded # REAL base := ( in exponent<0 | 1/in base | in base); INT exponent := ABS in exponent; BITS binary exponent:=BIN exponent ; # do exponent arithmetic in binary # REAL out := IF bits width ELEM binary exponent THEN base ELSE 1 FI; REAL sq := base;   WHILE binary exponent := binary exponent SHR 1; binary exponent /= BIN 0 DO sq *:= sq; IF bits width ELEM binary exponent THEN out *:= sq FI OD; out );   printf(($" One Gibi-unit is: "g(0,1)"**"g(0)"="g(0,1)" - (cost: "g(0) " REAL multiplications)"l$, 2.0, thirty, 2.0 ** thirty,8));   OP ** = (REAL base, REAL exponent)REAL: ( # ** REAL Operator can be overloaded # exp(ln(base)*exponent) );   printf(($" One Gibi-unit is: "g(0,1)"**"g(0,1)"="g(0,1)" - (cost: " "depends on precision)"l$, 2.0, 30.0, 2.0 ** 30.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
#PARI.2FGP
PARI/GP
#!/usr/bin/perl use strict; use warnings;   my $nzero = -0.0; my $nan = 0 + "nan"; my $pinf = +"inf"; my $ninf = -"inf";   printf "\$nzero = %.1f\n", $nzero; print "\$nan = $nan\n"; print "\$pinf = $pinf\n"; print "\$ninf = $ninf\n\n";   printf "atan2(0, 0) = %g\n", atan2(0, 0); printf "atan2(0, \$nzero) = %g\n", atan2(0, $nzero); printf "sin(\$pinf) = %g\n", sin($pinf); printf "\$pinf / -1 = %g\n", $pinf / -1; printf "\$ninf + 1e100 = %g\n\n", $ninf + 1e100;   printf "nan test: %g\n", (1 + 2 * 3 - 4) / (-5.6e7 * $nan); printf "nan == nan? %s\n", ($nan == $nan) ? "yes" : "no"; printf "nan == 42? %s\n", ($nan == 42) ? "yes" : "no";
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.
#F.23
F#
# # snusp.icn, A Modular SNUSP interpreter #   $define VERSION 0.6   # allow a couple of cli options link options   # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4   record position(row, col) global dir, ip, ram   procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug   opts := options(argv, "-h! -v! -d!", errorproc) \opts["v"] & verbose := 1 \opts["h"] & show_help(verbose) \opts["d"] & debug := 1   ip := position(1,1)   # initial direction dir := DRIGHT   # prepare initial memory ram := list(1, 0)   # prepare code field codespace := []   fn := open(argv[1], "r") | &input if (fn === &input) & \opts["h"] then return   while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) # track starting indicator if /col := find("$", codespace[row]) then { ip.row := row ip.col := col } row +:= 1 }   if \verbose then { write("Starting at ", ip.row, ", ", ip.col, " with codespace:") every write(!codespace) }   dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]", " row: ", ip.row, " col: ", ip.col, " dp: ", dp, " ram[dp]: ", ram[dp]) } case ch of { # six of the bf instructions "+": ram[dp] +:= 1 "-": ram[dp] -:= 1 ">": resize(dp +:= 1) "<": dp -:= 1 ".": writes(char(ram[dp]) | char(0)) ",": ram[dp] := getche() # direction change, LURD, RULD, SKIP, SKIPZ "\\": { # LURD case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } "/": { # RULD case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } "!": step() "?": { # skipz if ram[dp] = 0 then { step() } } # modular SNUSP "@": { # Enter push(dirs, dir) push(ips, copy(ip)) } "#": { # Leave if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end   # advance the ip depending on direction procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end   # enlarge memory when needed procedure resize(elements) until *ram >= elements do put(ram, 0) end   # quick help or verbose help procedure show_help(verbose) write("SNUSP interpeter in Unicon, version ", VERSION) write("CORE and MODULAR, not yet BLOATED") write() write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]") write(" -h, help") write(" -v, verbose (and verbose help") write(" -d, debug (step tracer)") if \verbose then { write() write("Instructions:") write(" + INCR, Increment current memory location") write(" - DECR, Decrement current memory location") write(" > RIGHT, Advance memory pointer") write(" < LEFT, Retreat memory pointer") write(" . WRITE, Output contents of current memory cell, in ASCII") write(" , READ, Accept key and place byte value in current memory cell") write(" \\ LURD, If going:") write(" left, go up") write(" up, go left") write(" right, go down") write(" down, go right") write(" / RULD, If going:") write(" right, go up") write(" up, go right") write(" left, go down") write(" down, go left") write(" !, SKIP, Move forward one step in current direction") write(" ?, SKIPZ, If current memory cell is zero then SKIP") write("Modular SNUSP adds:") write(" @, ENTER, Push direction and instruction pointer") write(" #, LEAVE, Pop direction and instruction pointer and SKIP") write() write("All other characters are NOOP, explicitly includes =,|,spc") write(" $, can set the starting location; first one found") write() write("Hello world examples:") write() write("CORE SNUSP:") write("/++++!/===========?\\>++.>+.+++++++..+++\\") write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./") write("$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\") write(" \\==-<<<<+>+++/ /=.>.+>.--------.-/") write() write("Modular SNUSP:") write(" /@@@@++++# #+++@@\ #-----@@@\\n") write("$@\\H.@/e.+++++++l.l.+++o.>>++++.< .<@/w.@\\o.+++r.++@\\l.@\\d.>+.@/.#") write(" \\@@@@=>++++>+++++<<@+++++# #---@@/!=========/!==/") write() } end
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.
#Emacs_Lisp
Emacs Lisp
  (defmacro if2 (cond1 cond2 both first second &rest neither) (let ((res1 (gensym)) (res2 (gensym))) `(let ((,res1 ,cond1) (,res2 ,cond2)) (cond ((and ,res1 ,res2) ,both) (,res1 ,first) (,res2 ,second) (t ,@neither)))))  
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
#J
J
5^3^2 1.95312e6 (5^3)^2 15625 5^(3^2) 1.95312e6
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
#Java
Java
jq -n 'pow(pow(5;3);2)' 15625
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
#jq
jq
jq -n 'pow(pow(5;3);2)' 15625
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
#Julia
Julia
@show 5 ^ 3 ^ 2 # default: power operator is read right-to-left @show (5 ^ 3) ^ 2 @show 5 ^ (3 ^ 2) @show reduce(^, [5, 3, 2]) @show foldl(^, [5, 3, 2]) # guarantees left associativity @show foldr(^, [5, 3, 2]) # guarantees right associativity
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.
#WDTE
WDTE
let a => import 'arrays'; let s => import 'stream';   a.stream [1; 2; 3; 4; 5; 6; 7; 8; 9; 10] -> s.filter (@ even n => % n 2 -> == 0) -> s.collect -- io.writeln io.stdout ;
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
#Pyret
Pyret
fun fizzbuzz(n :: NumPositive) -> String: doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'. For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.``` ask: | num-modulo(n, 15) == 0 then: "FizzBuzz" | num-modulo(n, 3) == 0 then: "Fizz" | num-modulo(n, 5) == 0 then: "Buzz" | otherwise: num-to-string(n) end where: fizzbuzz(1) is "1" fizzbuzz(101) is "101" fizzbuzz(45) is "FizzBuzz" fizzbuzz(33) is "Fizz" fizzbuzz(25) is "Buzz" end   range(1, 101).map(fizzbuzz).each(print)
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.
#F.23
F#
  let primeZ fN =primes()|>Seq.unfold(fun g-> Some(fN(g()), g)) let primesI() =primeZ bigint let primes64() =primeZ int64 let primes32() =primeZ int32 let pCache =Seq.cache(primes32()) let isPrime g=if g<2 then false else let mx=int(sqrt(float g)) in pCache|>Seq.takeWhile(fun n->n<=mx)|>Seq.forall(fun n->g%n>0) let isPrime64 g=if g<2L then false else let mx=int(sqrt(float g)) in pCache|>Seq.takeWhile(fun n->n<=mx)|>Seq.forall(fun n->g%(int64 n)>0L)  
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
#GML
GML
///fibonacci(n) //Returns the nth fibonacci number   var n, numb; n = argument0;   if (n == 0) { numb = 0; } else { var fm2, fm1; fm2 = 0; fm1 = 1; numb = 1; repeat(n-1) { numb = fm2+fm1; fm2 = fm1; fm1 = numb; } }   return numb;
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
#ProDOS
ProDOS
editvar /newvar /value=a /userinput=1 /title=Enter an integer: do /delimspaces %% -a- >b printline Factors of -a-: -b-
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#Arturo
Arturo
hq9: function [source][ acc: 0 loop split source 'ch [ case [(lower ch)=] when? ["h"]-> print "Hello, world!" when? ["q"]-> print source when? ["9"]-> print "99 bottles here ..." when? ["+"]-> acc: acc+1 else []   ] return acc ]   acc: hq9 {+qhp;+9Q} print ["accumulator:" acc]
http://rosettacode.org/wiki/Execute_HQ9%2B
Execute HQ9+
Task Implement a   HQ9+   interpreter or compiler.
#AutoHotkey
AutoHotkey
; http://www.autohotkey.com/forum/viewtopic.php?p=356268#356268   testCode := "hq9+HqQ+Qq"   MsgBox % RunHQ9Plus(testCode)   ;---------------------------------   RunHQ9Plus(input) { Loop, Parse, input If ( A_LoopField = "+" ) acc++ Else If ( A_LoopField = "H" ) output .= "Hello, world!`n" Else If ( A_LoopField = "Q" ) output .= input "`n" Else If ( A_LoopField = "9" ) Loop, 99 { ; following 4 lines could be only 1 long line output .= (99+1-A_Index) " bottles of beer on the wall`n" output .= (99+1-A_Index) " bottles of beer`n" output .= "Take one down, pass it around`n" output .= (99-A_Index) " bottles of beer on the wall`n`n" } Return output }
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
#AppleScript
AppleScript
on exponentiationOperatorTask(n, power) set power to power as integer set operatorResult to (n ^ power) set handlerResult to exponentiate(n, power)   return {operator:operatorResult, |handler|:handlerResult} end exponentiationOperatorTask   on exponentiate(n, power) -- AppleScript's ^ operator returns a real (ie. float) result. This handler does the same. set n to n as real set out to 1.0 if (power < 0) then repeat -power times set out to out / n end repeat else repeat power times set out to out * n end repeat end if   return out end exponentiate   exponentiationOperatorTask(3, 3) --> {operator:27.0, |handler|:27.0} exponentiationOperatorTask(2, 16) --> {operator:6.5536E+4, |handler|:6.5536E+4} exponentiationOperatorTask(2.5, 10) --> {operator:9536.7431640625, |handler|:9536.7431640625} exponentiationOperatorTask(2.5, -10) --> {operator:1.048576E-4, |handler|:1.048576E-4}
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
#Pascal
Pascal
#!/usr/bin/perl use strict; use warnings;   my $nzero = -0.0; my $nan = 0 + "nan"; my $pinf = +"inf"; my $ninf = -"inf";   printf "\$nzero = %.1f\n", $nzero; print "\$nan = $nan\n"; print "\$pinf = $pinf\n"; print "\$ninf = $ninf\n\n";   printf "atan2(0, 0) = %g\n", atan2(0, 0); printf "atan2(0, \$nzero) = %g\n", atan2(0, $nzero); printf "sin(\$pinf) = %g\n", sin($pinf); printf "\$pinf / -1 = %g\n", $pinf / -1; printf "\$ninf + 1e100 = %g\n\n", $ninf + 1e100;   printf "nan test: %g\n", (1 + 2 * 3 - 4) / (-5.6e7 * $nan); printf "nan == nan? %s\n", ($nan == $nan) ? "yes" : "no"; printf "nan == 42? %s\n", ($nan == 42) ? "yes" : "no";
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.
#Factor
Factor
# # snusp.icn, A Modular SNUSP interpreter #   $define VERSION 0.6   # allow a couple of cli options link options   # directions $define DRIGHT 1 $define DLEFT 2 $define DUP 3 $define DDOWN 4   record position(row, col) global dir, ip, ram   procedure main(argv) local ch, codespace, col, dp, fn, line local row := 1 local wid := 0 local dirs := [] local ips := [] local opts, verbose, debug   opts := options(argv, "-h! -v! -d!", errorproc) \opts["v"] & verbose := 1 \opts["h"] & show_help(verbose) \opts["d"] & debug := 1   ip := position(1,1)   # initial direction dir := DRIGHT   # prepare initial memory ram := list(1, 0)   # prepare code field codespace := []   fn := open(argv[1], "r") | &input if (fn === &input) & \opts["h"] then return   while line := read(fn) do { put(codespace, line) wid := max(*line, wid) } if *codespace = 0 then return every line := !codespace do { codespace[row] := left(codespace[row], wid) # track starting indicator if /col := find("$", codespace[row]) then { ip.row := row ip.col := col } row +:= 1 }   if \verbose then { write("Starting at ", ip.row, ", ", ip.col, " with codespace:") every write(!codespace) }   dp := 1 repeat { if not (ch := codespace[ip.row][ip.col]) then break if \debug then { write(&errout, "dir: ", dir, " ch: ", ch, " [", ord(ch), "]", " row: ", ip.row, " col: ", ip.col, " dp: ", dp, " ram[dp]: ", ram[dp]) } case ch of { # six of the bf instructions "+": ram[dp] +:= 1 "-": ram[dp] -:= 1 ">": resize(dp +:= 1) "<": dp -:= 1 ".": writes(char(ram[dp]) | char(0)) ",": ram[dp] := getche() # direction change, LURD, RULD, SKIP, SKIPZ "\\": { # LURD case dir of { DRIGHT: dir := DDOWN DLEFT: dir := DUP DUP: dir := DLEFT DDOWN: dir := DRIGHT } } "/": { # RULD case dir of { DRIGHT: dir := DUP DLEFT: dir := DDOWN DUP: dir := DRIGHT DDOWN: dir := DLEFT } } "!": step() "?": { # skipz if ram[dp] = 0 then { step() } } # modular SNUSP "@": { # Enter push(dirs, dir) push(ips, copy(ip)) } "#": { # Leave if *dirs < 1 then break dir := pop(dirs) ip := pop(ips) step() } } step() } end   # advance the ip depending on direction procedure step() case dir of { DRIGHT: ip.col +:= 1 DLEFT: ip.col -:= 1 DUP: ip.row -:= 1 DDOWN: ip.row +:= 1 } end   # enlarge memory when needed procedure resize(elements) until *ram >= elements do put(ram, 0) end   # quick help or verbose help procedure show_help(verbose) write("SNUSP interpeter in Unicon, version ", VERSION) write("CORE and MODULAR, not yet BLOATED") write() write("Usage: unicon snusp.icn -x [filename] [-h|-v|-d]") write(" -h, help") write(" -v, verbose (and verbose help") write(" -d, debug (step tracer)") if \verbose then { write() write("Instructions:") write(" + INCR, Increment current memory location") write(" - DECR, Decrement current memory location") write(" > RIGHT, Advance memory pointer") write(" < LEFT, Retreat memory pointer") write(" . WRITE, Output contents of current memory cell, in ASCII") write(" , READ, Accept key and place byte value in current memory cell") write(" \\ LURD, If going:") write(" left, go up") write(" up, go left") write(" right, go down") write(" down, go right") write(" / RULD, If going:") write(" right, go up") write(" up, go right") write(" left, go down") write(" down, go left") write(" !, SKIP, Move forward one step in current direction") write(" ?, SKIPZ, If current memory cell is zero then SKIP") write("Modular SNUSP adds:") write(" @, ENTER, Push direction and instruction pointer") write(" #, LEAVE, Pop direction and instruction pointer and SKIP") write() write("All other characters are NOOP, explicitly includes =,|,spc") write(" $, can set the starting location; first one found") write() write("Hello world examples:") write() write("CORE SNUSP:") write("/++++!/===========?\\>++.>+.+++++++..+++\\") write("\\+++\\ | /+>+++++++>/ /++++++++++<<.++>./") write("$+++/ | \\+++++++++>\\ \\+++++.>.+++.-----\\") write(" \\==-<<<<+>+++/ /=.>.+>.--------.-/") write() write("Modular SNUSP:") write(" /@@@@++++# #+++@@\ #-----@@@\\n") write("$@\\H.@/e.+++++++l.l.+++o.>>++++.< .<@/w.@\\o.+++r.++@\\l.@\\d.>+.@/.#") write(" \\@@@@=>++++>+++++<<@+++++# #---@@/!=========/!==/") write() } end
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.
#F.23
F#
  // Extend your language. Nigel Galloway: September 14th., 2021 type elsetf=TF type elseft=FT type elseff=FF let elsetf,elseft,elseff=TF,FT,FF let if2 n g tt (TF:elsetf)tf (FT:elseft)ft (FF:elseff)ff=match(n,g) with (true,true)->tt() |(true,false)->tf() |(false,true)->ft() |_->ff() if2 (13<23) (23<42) (fun()->printfn "tt") elsetf (fun()->printfn "tf") elseft (fun()->printfn "ft") elseff (fun()->printfn "ff") if2 (13<23) (42<23) (fun()->printfn "tt") elsetf (fun()->printfn "tf") elseft (fun()->printfn "ft") elseff (fun()->printfn "ff") if2 (23<23) (23<42) (fun()->printfn "tt") elsetf (fun()->printfn "tf") elseft (fun()->printfn "ft") elseff (fun()->printfn "ff") if2 (23<13) (42<23) (fun()->printfn "tt") elsetf (fun()->printfn "tf") elseft (fun()->printfn "ft") elseff (fun()->printfn "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
#Kotlin
Kotlin
// version 1.0.5-2   infix fun Int.ipow(exp: Int): Int = when { exp < 0 -> throw IllegalArgumentException("negative exponents not allowed") exp == 0 -> 1 else -> { var ans = 1 var base = this var e = exp while(e != 0) { if (e and 1 == 1) ans *= base e = e shr 1 base *= base } ans } }   fun main(args: Array<String>) { println("5**3**2 = ${5 ipow 3 ipow 2}") println("(5**3)**2 = ${(5 ipow 3) ipow 2}") println("5**(3**2) = ${5 ipow (3 ipow 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
#Lambdatalk
Lambdatalk
  '{pow {pow 5 3} 2} -> {pow {pow 5 3} 2} '{pow 5 {pow 3 2}} -> {pow 5 {pow 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
#Latitude
Latitude
5 ^ 3 ^ 2.  ;; 1953125 (5 ^ 3) ^ 2. ;; 15625 5 ^ (3 ^ 2). ;; 1953125
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.
#Wrapl
Wrapl
VAR a <- ALL 1:to(10);
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
#Python
Python
for i in xrange(1, 101): if i % 15 == 0: print "FizzBuzz" elif i % 3 == 0: print "Fizz" elif i % 5 == 0: print "Buzz" else: print 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.
#Factor
Factor
USING: io math.primes prettyprint sequences ;   "First 20 primes: " write 20 nprimes .   "Primes between 100 and 150: " write 100 150 primes-between .   "Number of primes between 7,700 and 8,000: " write 7,700 8,000 primes-between length .   "10,000th prime: " write 10,000 nprimes last .
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
#Go
Go
func fib(a int) int { if a < 2 { return a } return fib(a - 1) + fib(a - 2) }
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
#Prolog
Prolog
  brute_force_factors( N , Fs ) :- integer(N) , N > 0 , setof( F , ( between(1,N,F) , N mod F =:= 0 ) , Fs ) .