task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #BASIC256 | BASIC256 |
# Intérprete de HQ9+
global codigo
codigo = ""
function HQ9plus(codigo)
acumulador = 0
HQ9plus1 = ""
for cont = 1 to length(codigo)
op = upper(mid(codigo, cont, 1))
begin case
case op = "H"
HQ9plus1 = HQ9plus1 + "Hello, world!"
case op = "Q"
HQ9plus1 = HQ9plus1 + codigo
case op = "9"
for botellas = 99 to 1 step -1
HQ9plus1 = HQ9plus1 + string(botellas) + " bottle"
if (botellas > 1) then HQ9plus1 = HQ9plus1 + "s"
HQ9plus1 = HQ9plus1 + " of beer on the wall, " + string(botellas) + " bottle"
if (botellas > 1) then HQ9plus1 = HQ9plus1 + "s"
HQ9plus1 = HQ9plus1 + " of beer," + chr(13) + chr(10) + "Take one down, pass it around, " + string(botellas - 1) + " bottle"
if (botellas > 2) then HQ9plus1 = HQ9plus1 + "s"
HQ9plus1 = HQ9plus1 + " of beer on the wall." + chr(13) + chr(10) + chr(10)
next botellas
HQ9plus1 = HQ9plus1 + "No more bottles of beer on the wall, no more bottles of beer." + chr(13) + chr(10) + "Go to the store and buy some more, 99 bottles of beer on the wall."
case op = "+"
acumulador = (acumulador + 1)
case op = "E"
end
end case
if mid(codigo, cont, 1) <> "+" then
HQ9plus1 = HQ9plus1 + chr(13) + chr(10)
end if
next cont
HQ9plus = left(HQ9plus1, (length(HQ9plus1) - 2))
end function
cls
do
input codigo
print HQ9plus(codigo): print
until false
end
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #BBC_BASIC | BBC BASIC | PROChq9plus("hq9+HqQ+Qq")
END
DEF PROChq9plus(code$)
LOCAL accumulator%, i%, bottles%
FOR i% = 1 TO LEN(code$)
CASE MID$(code$, i%, 1) OF
WHEN "h","H": PRINT "Hello, world!"
WHEN "q","Q": PRINT code$
WHEN "9":
bottles% = 99
WHILE bottles%
PRINT ;bottles% " bottles of beer on the wall, ";
PRINT ;bottles% " bottles of beer,"
bottles% -= 1
PRINT "Take one down, pass it around, ";
PRINT ;bottles% " bottles of beer on the wall."
ENDWHILE
WHEN "+": accumulator% += 1
ENDCASE
NEXT i%
ENDPROC |
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
| #AutoHotkey | AutoHotkey | MsgBox % Pow(5,3)
MsgBox % Pow(2.5,4)
Pow(x, n){
r:=1
loop %n%
r *= x
return r
} |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #AWK | AWK | $ awk 'function pow(x,n){r=1;for(i=0;i<n;i++)r=r*x;return r}{print pow($1,$2)}'
|
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
| #Perl | Perl | #!/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.
| #Go | Go | #
# 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.
| #Factor | Factor | ( scratchpad ) : 2ifte ( ..a ?0 ?1 quot0: ( ..a -- ..b ) quot1: ( ..a -- ..b ) quot2: ( ..a -- ..b ) quot3: ( ..a -- ..b ) -- ..b )
[ [ if ] curry curry ] 2bi@ if ; inline
( scratchpad ) 3 [ 0 > ] [ even? ] bi [ 0 ] [ 1 ] [ 2 ] [ 3 ] 2ifte .
2 |
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.
| #Fennel | Fennel | ;; Fennel, being a Lisp, provides a way to define macros for new syntax.
;; The "`" and "," characters are used to construct a template for the macro.
(macro if2 [cond1 cond2 both first second none]
`(if ,cond1
(if ,cond2 ,both ,first)
(if ,cond2 ,second ,none)))
(fn test-if2 [x y]
(if2 x y
(print "both")
(print "first")
(print "second")
(print "none")))
(test-if2 true true) ;"both"
(test-if2 true false) ;"first"
(test-if2 false true) ;"second"
(test-if2 false false) ;"none" |
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
| #Lua | Lua | print("5^3^2 = " .. 5^3^2)
print("(5^3)^2 = " .. (5^3)^2)
print("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
| #Maple | Maple | 5^3^2;
(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
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | a = "5^3^2";
Print[a <> " = " <> ToString[ToExpression[a]]]
b = "(5^3)^2";
Print[b <> " = " <> ToString[ToExpression[b]]]
c = "5^(3^2)";
Print[c <> " = " <> ToString[ToExpression[c]]] |
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
| #min | min | 5 3 2 pow pow
"5 3 2 ^ ^ " print! puts!
5 3 pow 2 pow
"5 3 ^ 2 ^ " print! puts! |
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.
| #Wren | Wren | var a = [1, 4, 17, 8, -21, 6, -11, -2, 18, 31]
System.print("The original array is : %(a)")
System.print("\nFiltering to a new array :-")
var evens = a.where { |e| e%2 == 0 }.toList
System.print("The even numbers are : %(evens)")
System.print("The original array is still : %(a)")
// Destructive filter, permanently remove even numbers.
evens.clear()
for (i in a.count-1..0) {
if (a[i]%2 == 0) {
evens.add(a[i])
a.removeAt(i)
}
}
evens = evens[-1..0]
System.print("\nAfter a destructive filter :-")
System.print("The even numbers are : %(evens)")
System.print("The original array is now : %(a)") |
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
| #Q | Q |
q){(sum 1 2*0=x mod/:3 5)'[`$string x;`fizz;`buzz;`fizzbuzz]}1+til 20
`1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz |
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.
| #Fortran | Fortran | DO WHILE(F*F <= LST) !But, F*F might overflow the integer limit so instead,
DO WHILE(F <= LST/F) !Except, LST might also overflow the integer limit, so
DO WHILE(F <= (IST + 2*(SBITS - 1))/F) !Which becomes...
DO WHILE(F <= IST/F + (MOD(IST,F) + 2*(SBITS - 1))/F) !Preserving the remainder from IST/F. |
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
| #Groovy | Groovy | def rFib
rFib = {
it == 0 ? 0
: it == 1 ? 1
: it > 1 ? rFib(it-1) + rFib(it-2)
/*it < 0*/: rFib(it+2) - rFib(it+1)
} |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #PureBasic | PureBasic | Procedure PrintFactors(n)
Protected i, lim=Round(sqr(n),#PB_Round_Up)
NewList F.i()
For i=1 To lim
If n%i=0
AddElement(F()): F()=i
AddElement(F()): F()=n/i
EndIf
Next
;- Present the result
SortList(F(),#PB_Sort_Ascending)
ForEach F()
Print(str(F())+" ")
Next
EndProcedure
If OpenConsole()
Print("Enter integer to factorize: ")
PrintFactors(Val(Input()))
Print(#CRLF$+#CRLF$+"Press ENTER to quit."): Input()
EndIf |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #BQN | BQN | Pl ← {(𝕩≠1)/"s"}
Lwr ← +⟜(32×1="A["⊸⍋)
nn ← {(•Fmt 𝕨)∾" "∾𝕩}´¨∾{
⟨
⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer on the wall"⟩
⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer"⟩
⟨"Take one down, pass it around"⟩
⟨𝕩-1,"bottle"∾(Pl 𝕩-1)∾" of beer on the wall"⟩
⟩
}¨⌽1+↕99
HQ9 ← {
out ← ⟨⟨"Hello, World!"⟩, ⟨𝕩⟩, nn⟩
acc ← +´'+'=𝕩
∾out⊏˜3⊸≠⊸/"hq9"⊐Lwr 𝕩
}
•Out¨HQ9 •GetLine@ |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #C | C | void runCode(const char *code)
{
int c_len = strlen(code);
int i, bottles;
unsigned accumulator=0;
for(i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
printf("%s\n", code);
break;
case 'H':
printf("Hello, world!\n");
break;
case '9':
//Nice bottles song alg. from RC :)
bottles = 99;
do {
printf("%d bottles of beer on the wall\n", bottles);
printf("%d bottles of beer\n", bottles);
printf("Take one down, pass it around\n");
printf("%d bottles of beer on the wall\n\n", --bottles);
} while( bottles > 0 );
break;
case '+':
//Am I the only one finding this one weird? :o
accumulator++;
break;
}
}
}; |
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
| #BASIC | BASIC | DECLARE FUNCTION powL& (x AS INTEGER, y AS INTEGER)
DECLARE FUNCTION powS# (x AS SINGLE, y AS INTEGER)
DIM x AS INTEGER, y AS INTEGER
DIM a AS SINGLE
RANDOMIZE TIMER
a = RND * 10
x = INT(RND * 10)
y = INT(RND * 10)
PRINT x, y, powL&(x, y)
PRINT a, y, powS#(a, y)
FUNCTION powL& (x AS INTEGER, y AS INTEGER)
DIM n AS INTEGER, m AS LONG
IF x <> 0 THEN
m = 1
IF SGN(y) > 0 THEN
FOR n = 1 TO y
m = m * x
NEXT
END IF
END IF
powL& = m
END FUNCTION
FUNCTION powS# (x AS SINGLE, y AS INTEGER)
DIM n AS INTEGER, m AS DOUBLE
IF x <> 0 THEN
m = 1
IF y <> 0 THEN
FOR n = 1 TO y
m = m * x
NEXT
IF y < 0 THEN m = 1# / m
END IF
END IF
powS# = m
END FUNCTION |
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
| #Phix | Phix | with javascript_semantics
constant inf = 1e300*1e300, -- (works on both 32 and 64 bit)
ninf = -inf,
nan = -(inf/inf),
nzero = -1/inf -- (not supported)
printf(1," inf: %f\n",{inf})
printf(1," ninf: %f\n",{ninf})
printf(1," nan: %f\n",{nan})
printf(1,"*nzero: %f\n",{nzero})
printf(1," inf+2: %f\n",{inf+2})
printf(1," inf+ninf: %f\n",{inf+ninf})
printf(1," 0*inf: %f\n",{0*inf})
printf(1," nan+1: %f\n",{nan+1})
printf(1," nan+nan: %f\n",{nan+nan})
printf(1," inf>1e300: %d\n",{inf>1e300})
printf(1," ninf<1e300: %d\n",{ninf<-1e300})
printf(1,"*nan=nan: %d\n",{nan=nan})
printf(1," nan=42: %d\n",{nan=42})
printf(1,"*nan<0: %d\n",{nan<0})
printf(1," nan>0: %d\n",{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.
| #Haskell | Haskell | #
# 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.
| #Forth | Forth | \ in this construct, either of the ELSE clauses may be omitted, just like IF-THEN.
: BOTH postpone IF postpone IF ; immediate
: ORELSE postpone THEN postpone ELSE postpone IF ; immediate
: NEITHER postpone THEN postpone THEN ; immediate
: fb ( n -- )
dup 5 mod 0= over 3 mod 0=
BOTH ." FizzBuzz "
ELSE ." Fizz "
ORELSE ." Buzz "
ELSE dup .
NEITHER drop ;
: fizzbuzz ( n -- ) 0 do i 1+ fb loop ;
|
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
| #Nanoquery | Nanoquery | % println 5^3^2
15625
% println (5^3)^2
15625
% println 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
| #Nim | Nim | import math, sequtils
echo "5^3^2 = ", 5^3^2
echo "(5^3)^2 = ", (5^3)^2
echo "5^(3^2) = ", 5^(3^2)
echo "foldl([5, 3, 2], a^b) = ", foldl([5, 3, 2], a^b)
echo "foldr([5, 3, 2], a^b) = ", foldr([5, 3, 2], a^b) |
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
| #OCaml | OCaml | - : float = 1953125.
- : float = 1953125.
- : float = 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
| #PARI.2FGP | PARI/GP | f(s)=print(s" = "eval(s));
apply(f, ["5^3^2", "(5^3)^2", "5^(3^2)"]); |
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.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc Filter(A, B, Option); \Select all even numbers from array A
int A, B, Option; \ and return them in B, unless Option = true
int I, J;
[J:= 0;
for I:= 1 to A(0) do
if (A(I)&1) = 0 then
[J:= J+1;
if Option then
A(J):= A(I)
else B(J):= A(I);
];
if Option then A(0):= J else B(0):= J;
];
int Array, Evens(11), I;
[Array:= [10, 3, 1, 4, 1, 5, 9, 2, 6, 5, 4];
Filter(Array, Evens, false);
for I:= 1 to Evens(0) do
[IntOut(0, Evens(I)); ChOut(0, ^ )];
CrLf(0);
Filter(Array, Evens \not used\, true);
for I:= 1 to Array(0) do
[IntOut(0, Array(I)); ChOut(0, ^ )];
CrLf(0);
] |
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
| #QB64 | QB64 | For n = 1 To 100
If n Mod 15 = 0 Then
Print "FizzBuzz"
ElseIf n Mod 5 = 0 Then
Print "Buzz"
ElseIf n Mod 3 = 0 Then
Print "Fizz"
Else
Print n
End If
Next |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0
Enum SieveLimitType
number
between
countBetween
End Enum
Sub printPrimes(low As Integer, high As Integer, slt As SieveLimitType)
If high < low OrElse low < 1 Then Return ' too small
If slt <> number AndAlso slt <> between AndAlso slt <> countBetween Then Return
If slt <> number AndAlso (low < 2 OrElse high < 2) Then Return
If slt <> number AndAlso high > 1000000000 Then Return ' too big
If slt = number AndAlso high > 50000000 Then Return ' too big
Dim As Integer n
If slt = number Then
n = 20 * high '' big enough to accomodate 50 million primes to which this procedure is limited
Else
n = high
End If
Dim a(2 To n) As Boolean '' only uses 1 byte per element
For i As Integer = 2 To n : a(i) = True : Next '' set all elements to True to start with
Dim As Integer p = 2, q
' mark non-prime numbers by setting the corresponding array element to False
Do
For j As Integer = p * p To n Step p
a(j) = False
Next j
' look for next True element in array after 'p'
q = 0
For j As Integer = p + 1 To Sqr(n)
If a(j) Then
q = j
Exit For
End If
Next j
If q = 0 Then Exit Do
p = q
Loop
Select Case As Const slt
Case number
Dim count As Integer = 0
For i As Integer = 2 To n
If a(i) Then
count += 1
If count >= low AndAlso count <= high Then
Print i; " ";
End If
If count = high Then Exit Select
End If
Next
Case between
For i As Integer = low To high
If a(i) Then
Print i; " ";
End if
Next
Case countBetween
Dim count As Integer = 0
For i As Integer = low To high
If a(i) Then count += 1
Next
Print count;
End Select
Print
End Sub
Print "The first 20 primes are :"
Print
printPrimes(1, 20, number)
Print
Print "The primes between 100 and 150 are :"
Print
printPrimes(100, 150, between)
Print
Print "The number of primes between 7700 and 8000 is :";
printPrimes(7700, 8000, countBetween)
Print
Print "The 10000th prime is :";
Dim t As Double = timer
printPrimes(10000, 10000, number)
Print "Computed in "; CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "The 1000000th prime is :";
t = timer
printPrimes(1000000, 1000000, number)
Print "Computed in ";CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "The 50000000th prime is :";
t = timer
printPrimes(50000000, 50000000, number)
Print "Computed in ";CInt((timer - t) * 1000 + 0.5); " ms"
Print
Print "Press any key to quit"
Sleep |
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
| #Harbour | Harbour |
#include "harbour.ch"
Function fibb(a,b,n)
return(if(--n>0,fibb(b,a+b,n),a))
|
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
| #Python | Python | >>> def factors(n):
return [i for i in range(1, n + 1) if not n%i] |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #C.23 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void RunCode(string code)
{
int accumulator = 0;
var opcodes = new Dictionary<char, Action>
{
{'H', () => Console.WriteLine("Hello, World!"))},
{'Q', () => Console.WriteLine(code) },
{'9', () => Console.WriteLine(Enumerable.Range(1,100).Reverse().Select(n => string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around\n{1} bottles of beer on the wall\n", n, n-1)).Aggregate((a,b) => a + "\n" + b))},
{'+', () => accumulator++ }
}
foreach(var c in code)
opcodes[c]();
}
}
|
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #0815 | 0815 | }:r: Start reader loop.
|~ Read n,
#:end: if n is 0 terminates
>= enqueue it as the initial product, reposition.
}:f: Start factorial loop.
x<:1:x- Decrement n.
{=*> Dequeue product, position n, multiply, update product.
^:f:
{+% Dequeue incidental 0, add to get Y into Z, output fac(n).
<:a:~$ Output a newline.
^:r: |
http://rosettacode.org/wiki/Exponentiation_operator | Exponentiation operator | Most programming languages have a built-in implementation of exponentiation.
Task
Re-implement integer exponentiation for both intint and floatint as both a procedure, and an operator (if your language supports operator definition).
If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both intint and floatint variants.
Related tasks
Exponentiation order
arbitrary-precision integers (included)
Exponentiation with infix operators in (or operating on) the base
| #Befunge | Befunge | v v \<
>&:32p&1-\>32g*\1-:|
$
.
@ |
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
| #Brat | Brat | #Procedure
exp = { base, exp |
1.to(exp).reduce 1, { m, n | m = m * base }
}
#Numbers are weird
1.parent.^ = { rhs |
num = my
1.to(rhs).reduce 1 { m, n | m = m * num }
}
p exp 2 5 #Prints 32
p 2 ^ 5 #Prints 32 |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Ada | Ada | package Parameter is
X: Natural := 0;
Y: Natural;
end Parameter; |
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
| #PicoLisp | PicoLisp | (load "@lib/math.l")
: (exp 1000.0) # Too large for IEEE floats
-> T
: (+ 1 2 NIL 3) # NaN propagates
-> NIL |
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
| #PureBasic | PureBasic | Define.f
If OpenConsole()
inf = Infinity() ; or 1/None ;None represents a variable of value = 0
minus_inf = -Infinity() ; or -1/None
minus_zero = -1/inf
nan = NaN() ; or None/None
PrintN("positive infinity: "+StrF(inf))
PrintN("negative infinity: "+StrF(minus_inf))
PrintN("positive zero: "+StrF(None))
PrintN("negative zero: "+StrF(minus_zero)) ; handles as 0.0
PrintN("not a number: "+StrF(nan))
PrintN("Arithmetics")
PrintN("+inf + 2.0 = "+StrF(inf + 2.0))
PrintN("+inf - 10.1 = "+StrF(inf - 10.1))
PrintN("+inf + -inf = "+StrF(inf + minus_inf))
PrintN("0.0 * +inf = "+StrF(0.0 * inf))
PrintN("1.0/-0.0 = "+StrF(1.0/minus_zero))
PrintN("NaN + 1.0 = "+StrF(nan + 1.0))
PrintN("NaN + NaN = "+StrF(nan + nan))
PrintN("Logics")
If IsInfinity(inf): PrintN("Variable 'Infinity' is infinite"): EndIf
If IsNAN(nan): PrintN("Variable 'nan' is not a number"): EndIf
Print(#CRLF$+"Press ENTER to EXIT"): Input()
EndIf |
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.
| #Icon_and_Unicon | Icon and Unicon | #
# 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.
| #Fortran | Fortran | LOGICAL A,B !These are allocated the same storage
INTEGER IA,IB !As the default integer size.
EQUIVALENCE (IA,A),(IB,B) !So, this will cause no overlaps.
WRITE (6,*) "Boolean tests via integers..."
DO 199 IA = 0,1 !Two states for A.
DO 199 IB = 0,1 !Two states for B.
IF (IA) 666,99,109 !Not four ways, just three.
99 IF (IB) 666,100,101 !Negative values are surely wrong.
100 WRITE (6,*) "FF",IA,IB
GO TO 199
101 WRITE (6,*) "FT",IA,IB
GO TO 199
109 IF (IB) 666,110,111 !A second test.
110 WRITE (6,*) "TF",IA,IB
GO TO 199
111 WRITE (6,*) "TT",IA,IB
199 CONTINUE !Both loops finish here.
WRITE (6,*) "Boolean tests via integers and computed GO TO..."
DO 299 IA = 0,1 !Two states for A.
DO 299 IB = 0,1 !Two states for B.
GO TO (200,201,210,211) 1 + IA*2 + IB !Counting starts with one.
200 WRITE (6,*) "FF",IA,IB
GO TO 299
201 WRITE (6,*) "FT",IA,IB
GO TO 299
210 WRITE (6,*) "TF",IA,IB
GO TO 299
211 WRITE (6,*) "TT",IA,IB
299 CONTINUE !Both loops finish here.
300 WRITE (6,301)
301 FORMAT (/,"Boolean tests via LOGICAL variables...",/
1 " AB IA IB (IA*2 + IB)")
A = .TRUE. !Syncopation.
B = .TRUE. !Via the .NOT., the first pair will be FF.
DO I = 0,1 !Step through two states.
A = .NOT.A !Thus generate F then T.
DO J = 0,1 !Step through the second two states.
B = .NOT.B !Thus generate FF, FT, TF, TT.
WRITE (6,302) A,B,IA,IB,IA*2 + IB !But with strange values.
302 FORMAT (1X,2L1,2I6,I8) !Show both types.
END DO !Next value for B.
END DO !Next value for A.
GO TO 999
666 WRITE (6,*) "Huh?"
999 CONTINUE
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
| #Perl | Perl | say "$_ = " . eval($_) for qw/5**3**2 (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
| #Phix | Phix | ?power(power(5,3),2)
?power(5,power(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
| #PicoLisp | PicoLisp | : (** (** 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
| #PL.2FI | PL/I | exponentiation: procedure options(main);
put skip edit('5**3**2 = ', 5**3**2) (A,F(7));
put skip edit('(5**3)**2 = ', (5**3)**2) (A,F(7));
put skip edit('5**(3**2) = ', 5**(3**2)) (A,F(7));
end exponentiation; |
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.
| #XQuery | XQuery |
(: Sequence of numbers from 1 to 10 :)
let $array := (1 to 10)
(: Short version :)
let $short := $array[. mod 2 = 0]
(: Long version with a FLWOR expression :)
let $long := for $value in $array
where $value mod 2 = 0
return $value
(: Show the results :)
return
<result>
<short>{$short}</short>
<long>{$long}</long>
</result>
|
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
| #Quackery | Quackery | [ times
[ i^ 1+
' echo
over 3 mod 0 = if
[ say "Fizz"
drop ' drop ]
over 5 mod 0 = if
[ say "Buzz"
drop ' drop ]
do
sp ]
cr ] is fizzbuzz ( n --> )
say 'First 100 turns in the game of fizzbuzz:' cr cr
100 fizzbuzz cr |
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.
| #Frink | Frink | println["The first 20 primes are: " + first[primes[], 20]]
println["The primes between 100 and 150 are: " + primes[100,150]]
println["The number of primes between 7700 and 8000 are: " + length[primes[7700,8000]]]
println["The 10,000th prime is: " + nth[primes[], 10000-1]] // nth is zero-based |
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
| #Haskell | Haskell |
import Data.CReal
phi = (1 + sqrt 5) / 2
fib :: (Integral b) => b -> CReal 0
fib n = (phi^^n - (-phi)^^(-n))/sqrt 5
|
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
| #Quackery | Quackery | [ 1
[ 2dup < not while
2 << again ]
0
[ over 1 > while
dip [ 2 >> 2dup - ]
dup 1 >> unrot -
dup 0 < iff drop
else
[ 2swap nip
rot over + ]
again ] nip swap ] is isqrt ( n --> n n )
[ [] swap
dup isqrt 0 = dip
[ times
[ dup i^ 1+ /mod iff
drop done
rot join
i^ 1+ join swap ]
drop
dup size 2 / split ]
if [ -1 split drop ]
swap join ] is factors ( n --> [ )
20 times
[ i^ 1+ dup
dup 10 < if sp
echo
say ": "
factors witheach
[ echo i if say ", " ]
cr ] |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #C.2B.2B | C++ | void runCode(string code)
{
int c_len = code.length();
unsigned accumulator=0;
int bottles;
for(int i=0;i<c_len;i++)
{
switch(code[i])
{
case 'Q':
cout << code << endl;
break;
case 'H':
cout << "Hello, world!" << endl;
break;
case '9':
//Nice bottles song alg. from RC :)
bottles = 99;
do {
cout << bottles << " bottles of beer on the wall" << endl;
cout << bottles << " bottles of beer" << endl;
cout << "Take one down, pass it around" << endl;
cout << --bottles << " bottles of beer on the wall" << endl << endl;
} while( bottles > 0 );
break;
case '+':
//Am I the only one finding this one weird? :o
accumulator++;
break;
}
}
}; |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #11l | 11l | F factorial(n)
V result = 1
L(i) 2..n
result *= i
R result
L(n) 0..5
print(n‘ ’factorial(n)) |
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
| #C | C | #include <stdio.h>
#include <assert.h>
int ipow(int base, int exp)
{
int pow = base;
int v = 1;
if (exp < 0) {
assert (base != 0); /* divide by zero */
return (base*base != 1)? 0: (exp&1)? base : 1;
}
while(exp > 0 )
{
if (exp & 1) v *= pow;
pow *= pow;
exp >>= 1;
}
return v;
}
double dpow(double base, int exp)
{
double v=1.0;
double pow = (exp <0)? 1.0/base : base;
if (exp < 0) exp = - exp;
while(exp > 0 )
{
if (exp & 1) v *= pow;
pow *= pow;
exp >>= 1;
}
return v;
}
int main()
{
printf("2^6 = %d\n", ipow(2,6));
printf("2^-6 = %d\n", ipow(2,-6));
printf("2.71^6 = %lf\n", dpow(2.71,6));
printf("2.71^-6 = %lf\n", dpow(2.71,-6));
} |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #AutoHotkey | AutoHotkey | #NoEnv
SetBatchLines, -1
; Check if we're executed directly:
If (A_LineFile = A_ScriptFullPath){
h27 := hailstone(27)
MsgBox % "Length of hailstone 27: " (m := h27.MaxIndex()) "`nStarts with "
. h27[1] ", " h27[2] ", " h27[3] ", " h27[4]
. "`nEnds with "
. h27[m-3] ", " h27[m-2] ", " h27[m-1] ", " h27[m]
Loop 100000
{
h := hailstone(A_Index)
If (h.MaxIndex() > m)
m := h.MaxIndex(), longest := A_Index
}
MsgBox % "Longest hailstone is that of " longest " with a length of " m "!"
}
hailstone(n){
out := [n]
Loop
n := n & 1 ? n*3+1 : n//2, out.insert(n)
until n=1
return out
} |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #BBC_BASIC | BBC BASIC | seqlen% = FNhailstone(27)
PRINT "Sequence length for 27 is "; seqlen%
maxlen% = 0
FOR number% = 2 TO 100000
seqlen% = FNhailstone(number%)
IF seqlen% > maxlen% THEN
maxlen% = seqlen%
maxnum% = number%
ENDIF
NEXT
PRINT "The number with the longest hailstone sequence is " ; maxnum%
PRINT "Its sequence length is " ; maxlen%
END
DEF FNhailstone(N%)
LOCAL L%
WHILE N% <> 1
IF N% AND 1 THEN N% = 3 * N% + 1 ELSE N% DIV= 2
L% += 1
ENDWHILE
= L% + 1 |
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
| #Python | Python | >>> # Extreme values from expressions
>>> inf = 1e234 * 1e234
>>> _inf = 1e234 * -1e234
>>> _zero = 1 / _inf
>>> nan = inf + _inf
>>> inf, _inf, _zero, nan
(inf, -inf, -0.0, nan)
>>> # Print
>>> for value in (inf, _inf, _zero, nan): print (value)
inf
-inf
-0.0
nan
>>> # Extreme values from other means
>>> float('nan')
nan
>>> float('inf')
inf
>>> float('-inf')
-inf
>>> -0.
-0.0
>>> # Some arithmetic
>>> nan == nan
False
>>> nan is nan
True
>>> 0. == -0.
True
>>> 0. is -0.
False
>>> inf + _inf
nan
>>> 0.0 * nan
nan
>>> nan * 0.0
nan
>>> 0.0 * inf
nan
>>> 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
| #R | R | # 0 and -0 are recognized but are both printed as simply 0.
1/c(0, -0, Inf, -Inf, NaN)
# Inf -Inf 0 0 NaN |
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.
| #J | J |
Note 'snusp'
Without $ character the program counter starts at top left (0 0) moving to the right (0 1)
> increment the pointer (to point to the next cell to the right).
< decrement the pointer (to point to the next cell to the left).
+ increment (increase by one) the cell at the pointer.
- decrement (decrease by one) the cell at the pointer.
. output the value of the cell at the pointer as a character.
, accept one character of input, storing its value in the cell at the pointer.
\/ mirrors
? skip if memory pointer is 0
! skip
$ optional start program here (also heading to the right)
)
smoutput 'Toroidal programs run forever. Use ^C to interrupt.'
main =: 3 : 0 NB. use: main 'program.snusp'
PROGRAM =: [;._2 LF ,~ 1!:1 boxopen y
SHAPE =: $PROGRAM
PC =: SHAPE#:(,PROGRAM) i.'$'
PCSTEP =: 0 1
CELL =: 0
CELLS =: ,0
while. 1 do. NB. for_i. i.400 do.
INSTRUCTION =: (<PC) { PROGRAM
STEP =: PCSTEP
select. INSTRUCTION
case. '<' do.
CELL =: <: CELL
if. CELL < 0 do.
CELL =: 0
CELLS =: 0 , CELLS
end.
case. '>' do.
CELL =: >: CELL
if. CELL >: # CELLS do.
CELLS =: CELLS , 0
end.
case. ;/'-+' do. CELLS =: CELL ((<:'- +'i.INSTRUCTION)+{)`[`]} CELLS
case. '.' do. 1!:2&4 (CELL{CELLS){a.
case. ',' do. CELLS =: (1!:1<1) CELL } CELLS
fcase. '/' do. STEP =: - STEP
case. '\' do. STEP =: PCSTEP =: |. STEP
case. '?' do. STEP =: +:^:(0 = CELL{CELLS) STEP
case. '!' do. STEP =: +: STEP
end.
PC =: (| (PC + STEP + ])) SHAPE NB. toroidal
NB. smoutput PC;CELL;CELLS NB. debug
end.
)
|
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #Java | Java | const echo2 = raw"""
/==!/======ECHO==,==.==#
| |
$==>==@/==@/==<==#"""
@enum Direction left up right down
function snusp(datalength, progstring)
stack = Vector{Tuple{Int, Int, Direction}}()
data = zeros(datalength)
dp = ipx = ipy = 1
direction = right # default to go to right at beginning
lines = split(progstring, "\n")
lmax = maximum(map(length, lines))
lines = map(x -> rpad(x, lmax), lines)
for (y, li) in enumerate(lines)
if (x = findfirst("\$", li)) != nothing
(ipx, ipy) = (x[1], y)
end
end
instruction = Dict([('>', ()-> dp += 1),
('<', ()-> (dp -= 1; if dp < 0 running = false end)), ('+', ()-> data[dp] += 1),
('-', ()-> data[dp] -= 1), (',', ()-> (data[dp] = read(stdin, UInt8))),
('.', ()->print(Char(data[dp]))),
('/', ()-> (d = Int(direction); d += (iseven(d) ? 3 : 5); direction = Direction(d % 4))),
('\\', ()-> (d = Int(direction); d += (iseven(d) ? 1 : -1); direction = Direction(d))),
('!', () -> ipnext()), ('?', ()-> if data[dp] == 0 ipnext() end),
('@', ()-> push!(stack, (ipx, ipy, direction))),
('#', ()-> if length(stack) > 0 (ipx, ipy, direction) = pop!(stack) end),
('\n', ()-> (running = false))])
inboundsx(plus) = (plus ? (ipx < lmax) : (ipx > 1)) ? true : exit(data[dp])
inboundsy(plus) = (plus ? (ipy < length(lines)) : (ipy > 1)) ? true : exit(data[dp])
function ipnext()
if direction == right && inboundsx(true) ipx += 1
elseif direction == left && inboundsx(false) ipx -= 1
elseif direction == down && inboundsy(true) ipy += 1
elseif direction == up && inboundsy(false) ipy -= 1
end
end
running = true
while running
cmdcode = lines[ipy][ipx]
if haskey(instruction, cmdcode)
instruction[cmdcode]()
end
ipnext()
end
exit(data[dp])
end
snusp(100, echo2) |
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.
| #JavaScript | JavaScript | const echo2 = raw"""
/==!/======ECHO==,==.==#
| |
$==>==@/==@/==<==#"""
@enum Direction left up right down
function snusp(datalength, progstring)
stack = Vector{Tuple{Int, Int, Direction}}()
data = zeros(datalength)
dp = ipx = ipy = 1
direction = right # default to go to right at beginning
lines = split(progstring, "\n")
lmax = maximum(map(length, lines))
lines = map(x -> rpad(x, lmax), lines)
for (y, li) in enumerate(lines)
if (x = findfirst("\$", li)) != nothing
(ipx, ipy) = (x[1], y)
end
end
instruction = Dict([('>', ()-> dp += 1),
('<', ()-> (dp -= 1; if dp < 0 running = false end)), ('+', ()-> data[dp] += 1),
('-', ()-> data[dp] -= 1), (',', ()-> (data[dp] = read(stdin, UInt8))),
('.', ()->print(Char(data[dp]))),
('/', ()-> (d = Int(direction); d += (iseven(d) ? 3 : 5); direction = Direction(d % 4))),
('\\', ()-> (d = Int(direction); d += (iseven(d) ? 1 : -1); direction = Direction(d))),
('!', () -> ipnext()), ('?', ()-> if data[dp] == 0 ipnext() end),
('@', ()-> push!(stack, (ipx, ipy, direction))),
('#', ()-> if length(stack) > 0 (ipx, ipy, direction) = pop!(stack) end),
('\n', ()-> (running = false))])
inboundsx(plus) = (plus ? (ipx < lmax) : (ipx > 1)) ? true : exit(data[dp])
inboundsy(plus) = (plus ? (ipy < length(lines)) : (ipy > 1)) ? true : exit(data[dp])
function ipnext()
if direction == right && inboundsx(true) ipx += 1
elseif direction == left && inboundsx(false) ipx -= 1
elseif direction == down && inboundsy(true) ipy += 1
elseif direction == up && inboundsy(false) ipy -= 1
end
end
running = true
while running
cmdcode = lines[ipy][ipx]
if haskey(instruction, cmdcode)
instruction[cmdcode]()
end
ipnext()
end
exit(data[dp])
end
snusp(100, echo2) |
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.
| #Free_Pascal | Free Pascal | program fourWay(input, output, stdErr);
var
tuple: record
A: boolean;
B: char;
end;
begin
tuple.A := true;
tuple.B := 'Z';
case tuple of
(A: false; B: 'R'):
begin
writeLn('R is not good');
end;
(A: true; B: 'Z'):
begin
writeLn('Z is great');
end;
else
begin
writeLn('No');
end;
end;
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
| #Python | Python | >>> 5**3**2
1953125
>>> (5**3)**2
15625
>>> 5**(3**2)
1953125
>>> # The following is not normally done
>>> try: from functools import reduce # Py3K
except: pass
>>> reduce(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
| #Quackery | Quackery | Welcome to Quackery.
Enter "leave" to leave the shell.
/O> $ "5 3 2 ** **" dup echo$ say " returns " quackery echo cr
... $ "5 3 ** 2 **" dup echo$ say " returns " quackery echo cr
...
5 3 2 ** ** returns 1953125
5 3 ** 2 ** returns 15625
Stack empty. |
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
| #R | R | print(quote(5**3))
print(quote(5^3)) |
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.
| #XSLT | XSLT | <xsl:for-each select="nodes[@value mod 2 = 0]">
<xsl:value-of select="@value" />
</xsl:for-each> |
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
| #R | R | xx <- x <- 1:100
xx[x %% 3 == 0] <- "Fizz"
xx[x %% 5 == 0] <- "Buzz"
xx[x %% 15 == 0] <- "FizzBuzz"
xx |
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.
| #Go | Go | package main
import (
"container/heap"
"fmt"
)
func main() {
p := newP()
fmt.Print("First twenty: ")
for i := 0; i < 20; i++ {
fmt.Print(p(), " ")
}
fmt.Print("\nBetween 100 and 150: ")
n := p()
for n <= 100 {
n = p()
}
for ; n < 150; n = p() {
fmt.Print(n, " ")
}
for n <= 7700 {
n = p()
}
c := 0
for ; n < 8000; n = p() {
c++
}
fmt.Println("\nNumber beween 7,700 and 8,000:", c)
p = newP()
for i := 1; i < 10000; i++ {
p()
}
fmt.Println("10,000th prime:", p())
}
func newP() func() int {
n := 1
var pq pQueue
top := &pMult{2, 4, 0}
return func() int {
for {
n++
if n < top.pMult { // n is a new prime
heap.Push(&pq, &pMult{prime: n, pMult: n * n})
top = pq[0]
return n
}
// n was next on the queue, it's a composite
for top.pMult == n {
top.pMult += top.prime
heap.Fix(&pq, 0)
top = pq[0]
}
}
}
}
type pMult struct {
prime int
pMult int
index int
}
type pQueue []*pMult
func (q pQueue) Len() int { return len(q) }
func (q pQueue) Less(i, j int) bool { return q[i].pMult < q[j].pMult }
func (q pQueue) Swap(i, j int) {
q[i], q[j] = q[j], q[i]
q[i].index = i
q[j].index = j
}
func (p *pQueue) Push(x interface{}) {
q := *p
e := x.(*pMult)
e.index = len(q)
*p = append(q, e)
}
func (p *pQueue) Pop() interface{} {
q := *p
last := len(q) - 1
e := q[last]
*p = q[:last]
return e
} |
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
| #Haxe | Haxe | static function fib(steps:Int, handler:Int->Void)
{
var current = 0;
var next = 1;
for (i in 1...steps)
{
handler(current);
var temp = current + next;
current = next;
next = temp;
}
handler(current);
} |
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
| #R | R | factors <- function(n)
{
if(length(n) > 1)
{
lapply(as.list(n), factors)
} else
{
one.to.n <- seq_len(n)
one.to.n[(n %% one.to.n) == 0]
}
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Ceylon | Ceylon | shared void run() {
void eval(String code) {
variable value accumulator = 0;
for(c in code.trimmed.lowercased) {
switch(c)
case('h') {
print("Hello, world!");
}
case('q') {
print(code);
}
case('9') {
function bottles(Integer i) =>
switch(i)
case(0) "No bottles"
case(1) "One bottle"
else "``i`` bottles";
for(i in 99..1) {
print("``bottles(i)`` of beer on the wall,
``bottles(i)`` of beer,
take one down and pass it around,
``bottles(i - 1)`` of beer on the wall!");
}
}
case('+') {
accumulator++;
}
else {
print("syntax error");
}
}
}
eval("hq9+");
} |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #Clojure | Clojure | (ns anthony.random.hq9plus
(:require [clojure.string :as str]))
(defn bottles []
(loop [bottle 99]
(if (== bottle 0)
()
(do
(println (str bottle " bottles of beer on the wall"))
(println (str bottle " bottles of beer"))
(println "Take one down, pass it around")
(println (str bottle " bottles of beer on the wall"))
(recur (dec bottle))))))
(defn execute-hq9plus [& commands]
(let [accumulator (atom 0)]
(loop [pointer 0]
(condp = (nth commands pointer)
\H (println "Hello, world!")
\Q (println (str/join commands))
\9 (bottles)
\+ (reset! accumulator (inc @accumulator)))
(if-not (= (inc pointer) (count commands)) (recur (inc pointer)))))) |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #11l | 11l | T U0 {}
T U1 {}
F baz(i)
I i == 0
X U0()
E
X U1()
F bar(i)
baz(i)
F foo()
L(i) 0..1
X.try
bar(i)
X.catch U0
print(‘Function foo caught exception U0’)
foo() |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #360_Assembly | 360 Assembly | FACTO CSECT
USING FACTO,R13
SAVEAREA B STM-SAVEAREA(R15)
DC 17F'0'
DC CL8'FACTO'
STM STM R14,R12,12(R13)
ST R13,4(R15)
ST R15,8(R13)
LR R13,R15 base register and savearea pointer
ZAP N,=P'1' n=1
LOOPN CP N,NN if n>nn
BH ENDLOOPN then goto endloop
LA R1,PARMLIST
L R15,=A(FACT)
BALR R14,R15 call fact(n)
ZAP F,0(L'R,R1) f=fact(n)
DUMP EQU *
MVC S,MASK
ED S,N
MVC WTOBUF+5(2),S+30
MVC S,MASK
ED S,F
MVC WTOBUF+9(32),S
WTO MF=(E,WTOMSG)
AP N,=P'1' n=n+1
B LOOPN
ENDLOOPN EQU *
RETURN EQU *
L R13,4(0,R13)
LM R14,R12,12(R13)
XR R15,R15
BR R14
FACT EQU * function FACT(l)
L R2,0(R1)
L R3,12(R2)
ZAP L,0(L'N,R2) l=n
ZAP R,=P'1' r=1
ZAP I,=P'2' i=2
LOOP CP I,L if i>l
BH ENDLOOP then goto endloop
MP R,I r=r*i
AP I,=P'1' i=i+1
B LOOP
ENDLOOP EQU *
LA R1,R return r
BR R14 end function FACT
DS 0D
NN DC PL16'29'
N DS PL16
F DS PL16
C DS CL16
II DS PL16
PARMLIST DC A(N)
S DS CL33
MASK DC X'40',29X'20',X'212060' CL33
WTOMSG DS 0F
DC H'80',XL2'0000'
WTOBUF DC CL80'FACT(..)=................................ '
L DS PL16
R DS PL16
I DS PL16
LTORG
YREGS
END FACTO |
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
| #C.23 | C# |
static void Main(string[] args)
{
Console.WriteLine("5^5 = " + Expon(5, 5));
Console.WriteLine("5.5^5 = " + Expon(5.5, 5));
Console.ReadLine();
}
static double Expon(int Val, int Pow)
{
return Math.Pow(Val, Pow);
}
static double Expon(double Val, int Pow)
{
return Math.Pow(Val, Pow);
}
|
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #C | C | #ifndef HAILSTONE
#define HAILSTONE
long hailstone(long, long**);
void free_sequence(long *);
#endif/*HAILSTONE*/ |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Clojure | Clojure | .
├── clojure.jar
└── rosetta_code
├── frequent_hailstone_lengths.clj
└── hailstone_sequence.clj
|
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #D.C3.A9j.C3.A0_Vu | Déjà Vu | local hailstone:
swap [ over ]
while < 1 dup:
if % over 2:
#odd
++ * 3
else:
#even
/ swap 2
swap push-through rot dup
drop
if = (name) :(main):
local :h27 hailstone 27
!. = 112 len h27
!. = 27 h27! 0
!. = 82 h27! 1
!. = 41 h27! 2
!. = 124 h27! 3
!. = 8 h27! 108
!. = 4 h27! 109
!. = 2 h27! 110
!. = 1 h27! 111
local :max 0
local :maxlen 0
for i range 1 99999:
dup len hailstone i
if < maxlen:
set :maxlen
set :max i
else:
drop
!print( "number: " to-str max ", length: " to-str maxlen )
else:
@hailstone |
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
| #Racket | Racket | #lang racket
(define division-by-zero (/ 1.0 0.0)) ;+inf.0
(define negative-inf (- (/ 1.0 0.0))) ;-inf.0
(define zero 0.0) ;0.0
(define negative-zero (- 0.0)) ;-0.0
(define nan (/ 0.0 0.0)) ;+nan.0
(displayln division-by-zero)
(displayln negative-inf)
(displayln zero)
(displayln negative-zero)
(displayln nan)
(+ zero negative-zero) ;0.0
(- negative-inf division-by-zero) ; +nan.0
(+ zero nan) ; +nan.0
(= nan +nan.0) ;#f
|
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
| #Raku | Raku | print qq:to 'END'
positive infinity: {1.8e308}
negative infinity: {-1.8e308}
negative zero: {0e0 * -1}
not a number: {0 * 1e309}
+Inf + 2.0 = {Inf + 2}
+Inf - 10.1 = {Inf - 10.1}
0 * +Inf = {0 * Inf}
+Inf + -Inf = {Inf + -Inf}
+Inf == -Inf = {+Inf == -Inf}
(-Inf+0i)**.5 = {(-Inf+0i)**.5}
NaN + 1.0 = {NaN + 1.0}
NaN + NaN = {NaN + NaN}
NaN == NaN = {NaN == NaN}
0.0 == -0.0 = {0e0 == -0e0}
END |
http://rosettacode.org/wiki/Execute_SNUSP | Execute SNUSP | Execute SNUSP is an implementation of SNUSP.
Other implementations of SNUSP.
RCSNUSP
SNUSP
An implementation need only properly implement the Core SNUSP instructions ('$', '\', '/', '+', '-', '<', '>', ',', '.', '!', and '?'). Modular SNUSP ('#', '@') and Bloated SNUSP (':', ';', '%', and '&') are also allowed, but not required. Any extra characters that you implement should be noted in the description of your implementation. Any cell size is allowed, EOF support is optional, as is whether you have bounded or unbounded memory.
| #Julia | Julia | const echo2 = raw"""
/==!/======ECHO==,==.==#
| |
$==>==@/==@/==<==#"""
@enum Direction left up right down
function snusp(datalength, progstring)
stack = Vector{Tuple{Int, Int, Direction}}()
data = zeros(datalength)
dp = ipx = ipy = 1
direction = right # default to go to right at beginning
lines = split(progstring, "\n")
lmax = maximum(map(length, lines))
lines = map(x -> rpad(x, lmax), lines)
for (y, li) in enumerate(lines)
if (x = findfirst("\$", li)) != nothing
(ipx, ipy) = (x[1], y)
end
end
instruction = Dict([('>', ()-> dp += 1),
('<', ()-> (dp -= 1; if dp < 0 running = false end)), ('+', ()-> data[dp] += 1),
('-', ()-> data[dp] -= 1), (',', ()-> (data[dp] = read(stdin, UInt8))),
('.', ()->print(Char(data[dp]))),
('/', ()-> (d = Int(direction); d += (iseven(d) ? 3 : 5); direction = Direction(d % 4))),
('\\', ()-> (d = Int(direction); d += (iseven(d) ? 1 : -1); direction = Direction(d))),
('!', () -> ipnext()), ('?', ()-> if data[dp] == 0 ipnext() end),
('@', ()-> push!(stack, (ipx, ipy, direction))),
('#', ()-> if length(stack) > 0 (ipx, ipy, direction) = pop!(stack) end),
('\n', ()-> (running = false))])
inboundsx(plus) = (plus ? (ipx < lmax) : (ipx > 1)) ? true : exit(data[dp])
inboundsy(plus) = (plus ? (ipy < length(lines)) : (ipy > 1)) ? true : exit(data[dp])
function ipnext()
if direction == right && inboundsx(true) ipx += 1
elseif direction == left && inboundsx(false) ipx -= 1
elseif direction == down && inboundsy(true) ipy += 1
elseif direction == up && inboundsy(false) ipy -= 1
end
end
running = true
while running
cmdcode = lines[ipy][ipx]
if haskey(instruction, cmdcode)
instruction[cmdcode]()
end
ipnext()
end
exit(data[dp])
end
snusp(100, echo2) |
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.
| #Kotlin | Kotlin | // version 1.1.2
// requires 5 chars (10 bytes) of data store
const val hw = """
/++++!/===========?\>++.>+.+++++++..+++\
\+++\ | /+>+++++++>/ /++++++++++<<.++>./
$+++/ | \+++++++++>\ \+++++.>.+++.-----\
\==-<<<<+>+++/ /=.>.+>.--------.-/"""
// input is a multi-line string.
fun snusp(dlen: Int, raw: String) {
val ds = CharArray(dlen) // data store
var dp = 0 // data pointer
var s = raw
// remove leading '\n' from string if present
s = s.trimStart('\n')
// make 2 dimensional instruction store and declare instruction pointers
val cs = s.split('\n')
var ipr = 0
var ipc = 0
// look for starting instruction
findStart@ for ((r, row) in cs.withIndex()) {
for ((i, c) in row.withIndex()) {
if (c == '$') {
ipr = r
ipc = i
break@findStart
}
}
}
var id = 0
val step = fun() {
if (id and 1 == 0)
ipc += 1 - (id and 2)
else
ipr += 1 - (id and 2)
}
// execute
while ((ipr in 0 until cs.size) && (ipc in 0 until cs[ipr].length)) {
when (cs[ipr][ipc]) {
'>' -> dp++
'<' -> dp--
'+' -> ds[dp]++
'-' -> ds[dp]--
'.' -> print(ds[dp])
',' -> ds[dp] = readLine()!![0]
'/' -> id = id.inv()
'\\' -> id = id xor 1
'!' -> step()
'?' -> if (ds[dp] == '\u0000') step()
}
step()
}
}
fun main(args: Array<String>) {
snusp(5, hw)
} |
http://rosettacode.org/wiki/Extend_your_language | Extend your language | Control Structures
These are examples of control structures. You may also be interested in:
Conditional structures
Exceptions
Flow-control structures
Loops
Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements.
If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch:
Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following:
if (condition1isTrue) {
if (condition2isTrue)
bothConditionsAreTrue();
else
firstConditionIsTrue();
}
else if (condition2isTrue)
secondConditionIsTrue();
else
noConditionIsTrue();
Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large.
This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be:
if2 (condition1isTrue) (condition2isTrue)
bothConditionsAreTrue();
else1
firstConditionIsTrue();
else2
secondConditionIsTrue();
else
noConditionIsTrue();
Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
#Macro If2(condition1, condition2)
#Define Else1 ElseIf CBool(condition1) Then
#Define Else2 ElseIf CBool(condition2) Then
If CBool(condition1) AndAlso CBool(condition2) Then
#Endmacro
Sub test(a As Integer, b As Integer)
If2(a > 0, b > 0)
print "both positive"
Else1
print "first positive"
Else2
print "second positive"
Else
print "neither positive"
End If
End Sub
Dim As Integer a, b
Print "a = 1, b = 1 => ";
test(1, 1)
Print "a = 1, b = 0 => ";
test(1, 0)
Print "a = 0, b = 1 => ";
test(0, 1)
Print "a = 0, b = 0 => ";
test(0, 0)
Print
Print "Press any key to quit"
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
| #Racket | Racket | #lang racket
;; 5**3**2 depends on associativity of ** : Racket's (scheme's) prefix function
;; calling syntax only allows for pairs of arguments for expt.
;; So no can do for 5**3**2
;; (5**3)**2
(displayln "prefix")
(expt (expt 5 3) 2)
;; (5**3)**2
(expt 5 (expt 3 2))
;; There is also a less-used infix operation (for all functions, not just expt)... which I suppose
;; might do with an airing. But fundamentally nothing changes.
(displayln "\"in\"fix")
((5 . expt . 3) . expt . 2)
(5 . expt . (3 . expt . 2))
;; everyone's doing a reduction, it seems
(displayln "reduction")
(require (only-in srfi/1 reduce reduce-right))
(reduce expt 1 '(5 3 2))
(reduce-right expt 1 '(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
| #Raku | Raku | use MONKEY-SEE-NO-EVAL;
sub demo($x) { say " $x\t───► ", EVAL $x }
demo '5**3**2'; # show ** is right associative
demo '(5**3)**2';
demo '5**(3**2)';
demo '[**] 5,3,2'; # reduction form, show only final result
demo '[\**] 5,3,2'; # triangle reduction, show growing results
# Unicode postfix exponents are supported as well:
demo '(5³)²';
demo '5³²';
|
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
| #Red | Red | Red["Exponentiation order"]
exprs: [
[5 ** 3 ** 2]
[(5 ** 3) ** 2]
[5 ** (3 ** 2)]
[power power 5 3 2] ;-- functions too
[power 5 power 3 2]
]
foreach expr exprs [
print [mold/only expr "=" do expr]
if find expr '** [
print [mold/only expr "=" math expr "using math"]
]
] |
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.
| #Z80_Assembly | Z80 Assembly | TestArray_Metadata:
byte 4,4 ;4 rows, 4 columns.
TestArray:
byte 0,1,2,3
byte 4,5,6,7
byte 8,9,10,11
byte 12,13,14,15
OutputArray_Metadata:
byte 2,4
OutputArray:
ds 8,0 ;16 bytes each equaling zero
FilterEvenValues:
ld hl,TestArray_Metadata
ld a,(hl)
inc hl
ld b,(hl)
inc hl ;LD HL,TestArray
call mul_A_times_B ;unimplemented multiplication routine, multiplies A by B and returns product in A.
ld b,a ;we'll use this product as a loop counter.
ld de,OutputArray
loop_filterEvenValues:
ld a,(hl)
ld c,a
rrc c ;destructively test if odd or even. (That's why it was copied into C first.)
jr c,skipThis
ld (de),a
inc de
skipThis:
inc hl
djnz loop_filterEvenValues
ret ;return to basic |
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
| #Racket | Racket | #lang racket
(for ([n (in-range 1 101)])
(displayln
(match (gcd n 15)
[15 "fizzbuzz"]
[3 "fizz"]
[5 "buzz"]
[_ n]))) |
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.
| #Haskell | Haskell | #!/usr/bin/env runghc
import Data.List
import Data.Numbers.Primes
import System.IO
firstNPrimes :: Integer -> [Integer]
firstNPrimes n = genericTake n primes
primesBetweenInclusive :: Integer -> Integer -> [Integer]
primesBetweenInclusive lo hi =
dropWhile (< lo) $ takeWhile (<= hi) primes
nthPrime :: Integer -> Integer
nthPrime n = genericIndex primes (n - 1) -- beware 0-based indexing
main = do
hSetBuffering stdout NoBuffering
putStr "First 20 primes: "
print $ firstNPrimes 20
putStr "Primes between 100 and 150: "
print $ primesBetweenInclusive 100 150
putStr "Number of primes between 7700 and 8000: "
print $ genericLength $ primesBetweenInclusive 7700 8000
putStr "The 10000th prime: "
print $ nthPrime 10000 |
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
| #HicEst | HicEst | REAL :: Fibonacci(10)
Fibonacci = ($==2) + Fibonacci($-1) + Fibonacci($-2)
WRITE(ClipBoard) Fibonacci ! 0 1 1 2 3 5 8 13 21 34 |
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
| #Racket | Racket |
#lang racket
;; a naive version
(define (naive-factors n)
(for/list ([i (in-range 1 (add1 n))] #:when (zero? (modulo n i))) i))
(naive-factors 120) ; -> '(1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120)
;; much better: use `factorize' to get prime factors and construct the
;; list of results from that
(require math)
(define (factors n)
(sort (for/fold ([l '(1)]) ([p (factorize n)])
(append (for*/list ([e (in-range 1 (add1 (cadr p)))] [x l])
(* x (expt (car p) e)))
l))
<))
(naive-factors 120) ; -> same
;; to see how fast it is:
(define huge 1200034005600070000008900000000000000000)
(time (length (factors huge)))
;; I get 42ms for getting a list of 7776 numbers
;; but actually the math library comes with a `divisors' function that
;; does the same, except even faster
(divisors 120) ; -> same
(time (length (divisors huge)))
;; And this one clocks at 17ms
|
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #CLU | CLU | % This program uses the "get_argv" function from PCLU's "useful.lib"
hq9plus = cluster is load, run
rep = string
own po: stream := stream$primary_output()
bottles = proc (n: int) returns (string)
if n=0 then return("No more bottles ")
elseif n=1 then return("1 bottle ")
else return(int$unparse(n) || " bottles ")
end
end bottles
beer = proc ()
for i: int in int$from_to_by(99,1,-1) do
stream$putl(po, bottles(i) || "of beer on the wall,")
stream$putl(po, bottles(i) || "of beer,")
stream$puts(po, "Take ")
if i=1
then stream$puts(po, "it")
else stream$puts(po, "one")
end
stream$putl(po, " down and pass it around,")
stream$putl(po, bottles(i-1) || "of beer on the wall!\n")
end
end beer
quine = proc (c: rep) stream$puts(po, c) end quine
hello = proc () stream$putl(po, "Hello, world!") end hello
load = proc (fn: file_name) returns (cvt) signals (not_possible(string))
prog: array[char] := array[char]$[]
s: stream := stream$open(fn, "read") resignal not_possible
while true do
array[char]$addh(prog, stream$getc(s))
except when end_of_file: break end
end
stream$close(s)
return(rep$ac2s(prog))
end load
run = proc (prog: cvt) returns (int)
acc: int := 0
for c: char in rep$chars(prog) do
if c='h' | c='H' then hello()
elseif c='q' | c='Q' then quine(prog)
elseif c='9' then beer()
elseif c='+' then acc := acc + 1
end
end
return(acc)
end run
end hq9plus
start_up = proc ()
fn: file_name := file_name$parse(sequence[string]$bottom(get_argv()))
hq9plus$run(hq9plus$load(fn))
end start_up |
http://rosettacode.org/wiki/Execute_HQ9%2B | Execute HQ9+ | Task
Implement a HQ9+ interpreter or compiler.
| #COBOL | COBOL | IDENTIFICATION DIVISION.
PROGRAM-ID. Exec-Hq9.
DATA DIVISION.
LOCAL-STORAGE SECTION.
78 Code-Length VALUE 256.
01 i PIC 999.
01 accumulator PIC 999.
01 bottles PIC 999.
LINKAGE SECTION.
01 hq9-code PIC X(Code-Length).
PROCEDURE DIVISION USING BY VALUE hq9-code.
PERFORM VARYING i FROM 1 BY 1 UNTIL Code-Length < i
EVALUATE hq9-code (i:1)
WHEN "Q"
DISPLAY FUNCTION TRIM(hq9-code)
WHEN "H"
DISPLAY "Hello, World!"
WHEN "9"
MOVE 99 TO bottles
PERFORM UNTIL bottles = ZERO
DISPLAY
bottles " bottles of beer on the wall"
DISPLAY bottles " bottles of beer"
DISPLAY "Take one down, pass it around"
SUBTRACT 1 FROM bottles
DISPLAY
bottles " bottles of beer on the wall"
DISPLAY SPACE
END-PERFORM
WHEN "+"
ADD 1 TO accumulator
END-EVALUATE
END-PERFORM
GOBACK
. |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Ada | Ada | with Ada.Text_Io; use Ada.Text_Io;
procedure Exceptions_From_Nested_Calls is
U0 : exception;
U1 : exception;
Baz_Count : Natural := 0;
procedure Baz is
begin
Baz_Count := Baz_Count + 1;
if Baz_Count = 1 then
raise U0;
else
raise U1;
end if;
end Baz;
procedure Bar is
begin
Baz;
end Bar;
procedure Foo is
begin
Bar;
exception
when U0 =>
Put_Line("Procedure Foo caught exception U0");
end Foo;
begin
for I in 1..2 loop
Foo;
end loop;
end Exceptions_From_Nested_Calls; |
http://rosettacode.org/wiki/Exceptions/Catch_an_exception_thrown_in_a_nested_call | Exceptions/Catch an exception thrown in a nested call | Show how to create a user-defined exception and show how to catch an exception raised from several nested calls away.
Create two user-defined exceptions, U0 and U1.
Have function foo call function bar twice.
Have function bar call function baz.
Arrange for function baz to raise, or throw exception U0 on its first call, then exception U1 on its second.
Function foo should catch only exception U0, not U1.
Show/describe what happens when the program is run.
| #Aime | Aime | void
baz(integer i)
{
error(cat("U", itoa(i)));
}
void
bar(integer i)
{
baz(i);
}
void
foo(void)
{
integer i;
i = 0;
while (i < 2) {
text e;
if (trap_d(e, bar, i)) {
o_form("Exception `~' thrown\n", e);
if (e != "U0") {
o_text("will not catch exception\n");
error(e);
}
}
i += 1;
}
o_text("Never reached.\n");
}
integer
main(void)
{
foo();
return 0;
} |
http://rosettacode.org/wiki/Execute_a_system_command | Execute a system command | Task
Run either the ls system command (dir on Windows), or the pause system command.
Related task
Get system command output
| #11l | 11l | os:(‘pause’) |
http://rosettacode.org/wiki/Factorial | Factorial | Definitions
The factorial of 0 (zero) is defined as being 1 (unity).
The Factorial Function of a positive integer, n, is defined as the product of the sequence:
n, n-1, n-2, ... 1
Task
Write a function to return the factorial of a number.
Solutions can be iterative or recursive.
Support for trapping negative n errors is optional.
Related task
Primorial numbers
| #68000_Assembly | 68000 Assembly | Factorial:
;input: D0.W: number you wish to get the factorial of.
;output: D0.L
CMP.W #0,D0
BEQ .isZero
CMP.W #1,D0
BEQ .isOne
MOVEM.L D4-D5,-(SP)
MOVE.W D0,D4
MOVE.W D0,D5
SUBQ.W #2,D5 ;D2 = LOOP COUNTER.
;Since DBRA stops at FFFF we can't use it as our multiplier.
;If we did, we'd always return 0!
.loop:
SUBQ.L #1,D4
MOVE.L D1,-(SP)
MOVE.L D4,D1
JSR MULU_48 ;multiplies D0.L by D1.W
EXG D0,D1 ;output is in D1 so we need to put it in D0
MOVE.L (SP)+,D1
DBRA D5,.loop
MOVEM.L (SP)+,D4-D5
RTS
.isZero:
.isOne:
MOVEQ #1,D0
RTS
MULU_48:
;"48-BIT" MULTIPLICATION.
;OUTPUTS HIGH LONG IN D0, LOW LONG IN D1
;INPUT: D0.L, D1.W = FACTORS
MOVEM.L D2-D7,-(SP)
SWAP D1
CLR.W D1
SWAP D1 ;CLEAR THE TOP WORD OF D1.
MOVE.L D1,D2
EXG D0,D1 ;D1 IS OUR BASE VALUE, WE'LL USE BIT SHIFTS TO REPEATEDLY MULTIPLY.
MOVEQ #0,D0 ;CLEAR UPPER LONG OF PRODUCT
MOVE.L D1,D3 ;BACKUP OF "D1" (WHICH USED TO BE D0)
;EXAMPLE: $40000000*$225 = ($40000000 << 9) + ($40000000 << 5) + ($40000000 << 2) + $40000000
;FACTOR OUT AS MANY POWERS OF 2 AS POSSIBLE.
MOVEQ #0,D0
LSR.L #1,D2
BCS .wasOdd ;if odd, leave D1 alone. Otherwise, clear it. This is our +1 for an odd second operand.
MOVEQ #0,D1
.wasOdd:
MOVEQ #31-1,D6 ;30 BITS TO CHECK
MOVEQ #1-1,D7 ;START AT BIT 1, MINUS 1 IS FOR DBRA CORRECTION FACTOR
.shiftloop:
LSR.L #1,D2
BCC .noShift
MOVE.W D7,-(SP)
MOVEQ #0,D4
MOVE.L D3,D5
.innershiftloop:
ANDI #%00001111,CCR ;clear extend flag
ROXL.L D5
ROXL.L D4
DBRA D7,.innershiftloop
ANDI #%00001111,CCR
ADDX.L D5,D1
ADDX.L D4,D0
MOVE.W (SP)+,D7
.noShift:
addq.l #1,d7
dbra d6,.shiftloop
MOVEM.L (SP)+,D2-D7
RTS
|
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
| #C.2B.2B | C++ | template<typename Number>
Number power(Number base, int exponent)
{
int zerodir;
Number factor;
if (exponent < 0)
{
zerodir = 1;
factor = Number(1)/base;
}
else
{
zerodir = -1;
factor = base;
}
Number result(1);
while (exponent != 0)
{
if (exponent % 2 != 0)
{
result *= factor;
exponent += zerodir;
}
else
{
factor *= factor;
exponent /= 2;
}
}
return result;
} |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Factor | Factor | ! rosetta/hailstone/hailstone.factor
USING: arrays io kernel math math.ranges prettyprint sequences vectors ;
IN: rosetta.hailstone
: hailstone ( n -- seq )
[ 1vector ] keep
[ dup 1 number= ]
[
dup even? [ 2 / ] [ 3 * 1 + ] if
2dup swap push
] until
drop ;
<PRIVATE
: main ( -- )
27 hailstone dup dup
"The hailstone sequence from 27:" print
" has length " write length .
" starts with " write 4 head [ unparse ] map ", " join print
" ends with " write 4 tail* [ unparse ] map ", " join print
! Maps n => { length n }, and reduces to longest Hailstone sequence.
1 100000 [a,b)
[ [ hailstone length ] keep 2array ]
[ [ [ first ] bi@ > ] most ] map-reduce
first2
"The hailstone sequence from " write pprint
" has length " write pprint "." print ;
PRIVATE>
MAIN: main |
http://rosettacode.org/wiki/Executable_library | Executable library | The general idea behind an executable library is to create a library
that when used as a library does one thing;
but has the ability to be run directly via command line.
Thus the API comes with a CLI in the very same source code file.
Task detail
Create a library/module/dll/shared object/... for a programming language that contains a function/method called hailstone that is a function taking a positive integer and returns the Hailstone sequence for that number.
The library, when executed directly should satisfy the remaining requirements of the Hailstone sequence task:
2. Use the routine to show that the hailstone sequence for the number 27 has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
3. Show the number less than 100,000 which has the longest hailstone sequence together with that sequence's length.
Create a second executable to calculate the following:
Use the library's hailstone function, in the standard manner, (or document how this use deviates from standard use of a library), together with extra code in this executable, to find the hailstone length returned most often for 1 ≤ n < 100,000.
Explain any extra setup/run steps needed to complete the task.
Notes:
It is assumed that for a language that overwhelmingly ships in a compiled form, such as C, the library must also be an executable and the compiled user of that library is to do so without changing the compiled library. I.e. the compile tool-chain is assumed not to be present in the runtime environment.
Interpreters are present in the runtime environment. | #Go | Go | // modulino.go
package main
import "fmt"
// Function borrowed from Hailstone sequence task.
// 1st arg is the number to generate the sequence for.
// 2nd arg is a slice to recycle, to reduce garbage.
func hailstone(n int, recycle []int) []int {
s := append(recycle[:0], n)
for n > 1 {
if n&1 == 0 {
n = n / 2
} else {
n = 3*n + 1
}
s = append(s, n)
}
return s
}
func libMain() {
seq := hailstone(27, nil)
fmt.Println("\nHailstone sequence for the number 27:")
fmt.Println(" has", len(seq), "elements")
fmt.Println(" starts with", seq[0:4])
fmt.Println(" ends with", seq[len(seq)-4:])
var longest, length int
for i := 1; i < 100000; i++ {
if le := len(hailstone(i, nil)); le > length {
longest = i
length = le
}
}
fmt.Printf("\n%d has the longest Hailstone sequence, its length being %d.\n", longest, length)
} |
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
| #REXX | REXX | /*REXX pgm shows smallest & largest positive numbers that can be expressed, compares 0's*/
parse version v; say 'version=' v; say
zero= '0.0' /*a (positive) value for zero. */
negZero= '-0.0' /*" negative " " " */
say 'value of zero equals negZero: ' word('no yes', 1 + (zero = negZero) )
say 'value of zero exactly equals negZero: ' word('no yes', 1 + (zero == negZero) )
say
do digs=20 by 20 to 100; numeric digits digs /*use a range of digits. */
say center(' number of decimal digits being used:' digs" ", 79, '═')
say 'tiny=' tiny()
say 'huge=' huge()
end /*j*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
tiny: return $xnum('1e-')
huge: return $xnum('.'copies(9, digits() )"e+")
/*──────────────────────────────────────────────────────────────────────────────────────*/
$xnum: procedure; parse arg $ /*use the given mantissa value.*/
!=10 /*use starting exponent value.*/
do forever; _=$ || ! /*construct a REXX decimal num.*/
if \datatype(_, 'N') then leave /*Not numeric? Then leave. */
p=!; !=! * 10 /*save number; magnify mantissa*/
end /*forever*/
j=! % 2 /*halve the exponent (power). */
do forever; _=$ || ! /* [+] Not numeric? Halve it.*/
if \datatype(_, 'N') then do; !=p; j=j % 2
if j==0 then leave
end
p=!; !=! + j /*save number; bump mantissa. */
end /*forever*/
return $ || ! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.