task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Perl
Perl
sub factors { my($n) = @_; return grep { $n % $_ == 0 }(1 .. $n); } print join ' ',factors(64), "\n";
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
#Go
Go
package main   import ( "fmt" "math" )   func main() { // compute "extreme values" from non-extreme values var zero float64 // zero is handy. var negZero, posInf, negInf, nan float64 // values to compute. negZero = zero * -1 posInf = 1 / zero negInf = -1 / zero nan = zero / zero   // print extreme values stored in variables fmt.Println(negZero, posInf, negInf, nan)   // directly obtain extreme values fmt.Println(math.Float64frombits(1<<63), math.Inf(1), math.Inf(-1), math.NaN())   // validate some arithmetic on extreme values fmt.Println() validateNaN(negInf+posInf, "-Inf + Inf") validateNaN(0*posInf, "0 * Inf") validateNaN(posInf/posInf, "Inf / Inf") // mod is specifically named in "What every computer scientist..." // Go math package doc lists many special cases for other package functions. validateNaN(math.Mod(posInf, 1), "Inf % 1") validateNaN(1+nan, "1 + NaN") validateZero(1/posInf, "1 / Inf") validateGT(posInf, math.MaxFloat64, "Inf > max value") validateGT(-math.MaxFloat64, negInf, "-Inf < max neg value") validateNE(nan, nan, "NaN != NaN") validateEQ(negZero, 0, "-0 == 0") }   func validateNaN(n float64, op string) { if math.IsNaN(n) { fmt.Println(op, "-> NaN") } else { fmt.Println("!!! Expected NaN from", op, " Found", n) } }   func validateZero(n float64, op string) { if n == 0 { fmt.Println(op, "-> 0") } else { fmt.Println("!!! Expected 0 from", op, " Found", n) } }   func validateGT(a, b float64, op string) { if a > b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }   func validateNE(a, b float64, op string) { if a == b { fmt.Println("!!! Expected", op, " Found not true.") } else { fmt.Println(op) } }   func validateEQ(a, b float64, op string) { if a == b { fmt.Println(op) } else { fmt.Println("!!! Expected", op, " Found not true.") } }
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.
#Agda
Agda
    data Bool : Set where true : Bool false : Bool   if_then_else : ∀ {l} {A : Set l} -> Bool -> A -> A -> A if true then t else e = t if false then t else e = e   if2_,_then_else1_else2_else_ : ∀ {l} {A : Set l} -> (b1 b2 : Bool) -> (t e1 e2 e : A) -> A if2 true , true then t else1 e1 else2 e2 else e = t if2 true , false then t else1 e1 else2 e2 else e = e1 if2 false , true then t else1 e1 else2 e2 else e = e2 if2 false , false then t else1 e1 else2 e2 else e = e   example : Bool example = if2 true , false then true else1 false else2 true else false  
http://rosettacode.org/wiki/Extend_your_language
Extend your language
Control Structures These are examples of control structures. You may also be interested in: Conditional structures Exceptions Flow-control structures Loops Some programming languages allow you to extend the language. While this can be done to a certain degree in most languages (e.g. by using macros), other languages go much further. Most notably in the Forth and Lisp families, programming per se is done by extending the language without any formal distinction between built-in and user-defined elements. If your language supports it, show how to introduce a new flow control mechanism. A practical and useful example is a four-way branch: Occasionally, code must be written that depends on two conditions, resulting in up to four branches (depending on whether both, only the first, only the second, or none of the conditions are "true"). In a C-like language this could look like the following: if (condition1isTrue) { if (condition2isTrue) bothConditionsAreTrue(); else firstConditionIsTrue(); } else if (condition2isTrue) secondConditionIsTrue(); else noConditionIsTrue(); Besides being rather cluttered, the statement(s) for 'condition2isTrue' must be written down twice. If 'condition2isTrue' were a lengthy and involved expression, it would be quite unreadable, and the code generated by the compiler might be unnecessarily large. This can be improved by introducing a new keyword if2. It is similar to if, but takes two conditional statements instead of one, and up to three 'else' statements. One proposal (in pseudo-C syntax) might be: if2 (condition1isTrue) (condition2isTrue) bothConditionsAreTrue(); else1 firstConditionIsTrue(); else2 secondConditionIsTrue(); else noConditionIsTrue(); Pick the syntax which suits your language. The keywords 'else1' and 'else2' are just examples. The new conditional expression should look, nest and behave analogously to the language's built-in 'if' statement.
#ALGOL_68
ALGOL 68
# operator to turn two boolean values into an integer - name inspired by the COBOL sample # PRIO ALSO = 1; OP ALSO = ( BOOL a, b )INT: IF a AND b THEN 1 ELIF a THEN 2 ELIF b THEN 3 ELSE 4 FI;   # using the above operator, we can use the standard CASE construct to provide the # # required construct, e.g.: # BOOL a := TRUE, b := FALSE; CASE a ALSO b IN print( ( "both: a and b are TRUE", newline ) ) , print( ( "first: only a is TRUE", newline ) ) , print( ( "second: only b is TRUE", newline ) ) , print( ( "neither: a and b are FALSE", newline ) ) ESAC
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection
Factorial base numbers indexing permutations of a collection
You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0 Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2. I want to produce a 1 to 1 mapping between these numbers and permutations:- 0.0.0 -> 0123 0.0.1 -> 0132 0.1.0 -> 0213 0.1.1 -> 0231 0.2.0 -> 0312 0.2.1 -> 0321 1.0.0 -> 1023 1.0.1 -> 1032 1.1.0 -> 1203 1.1.1 -> 1230 1.2.0 -> 1302 1.2.1 -> 1320 2.0.0 -> 2013 2.0.1 -> 2031 2.1.0 -> 2103 2.1.1 -> 2130 2.2.0 -> 2301 2.2.1 -> 2310 3.0.0 -> 3012 3.0.1 -> 3021 3.1.0 -> 3102 3.1.1 -> 3120 3.2.0 -> 3201 3.2.1 -> 3210 The following psudo-code will do this: Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number. If g is greater than zero, rotate the elements from m to m+g in Ω (see example) Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted. For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element. Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3 Step 2: m=1 g=0; No action. Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1 Let me work 2.0.1 and 0123 step 1 n=0 g=2 Ω=2013 step 2 n=1 g=0 so no action step 3 n=2 g=1 Ω=2031 The task: First use your function to recreate the above table. Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with methods in rc's permutations task. Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier: 39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0 51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1 use your function to crate the corresponding permutation of the following shoe of cards: A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣ Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
#Wren
Wren
import "random" for Random import "/math" for Int import "/fmt" for Fmt   var genFactBaseNums = Fn.new { |size, countOnly| var results = [] var count = 0 var n = 0 while (true) { var radix = 2 var res = null if (!countOnly) res = List.filled(size, 0) var k = n while (k > 0) { var div = (k/radix).floor var rem = k % radix if (!countOnly) { if (radix <= size + 1) res[size-radix+1] = rem } k = div radix = radix + 1 } if (radix > size+2) break count = count + 1 if (!countOnly) results.add(res) n = n + 1 } return [results, count] }   var mapToPerms = Fn.new { |factNums| var perms = [] var psize = factNums[0].count + 1 var start = List.filled(psize, 0) for (i in 0...psize) start[i] = i for (fn in factNums) { var perm = start.toList for (m in 0...fn.count) { var g = fn[m] if (g != 0) { var first = m var last = m + g for (i in 1..g) { var temp = perm[first] for (j in first+1..last) perm[j-1] = perm[j] perm[last] = temp } } } perms.add(perm) } return perms }   var join = Fn.new { |ints, sep| ints.map { |i| i.toString }.join(sep) }   var undot = Fn.new { |s| s.split(".").map { |ss| Num.fromString(ss) }.toList }   var rand = Random.new()   // Recreate the table. var factNums = genFactBaseNums.call(3, false)[0] var perms = mapToPerms.call(factNums) var i = 0 for (fn in factNums) { Fmt.print("$s -> $s", join.call(fn, "."), join.call(perms[i], "")) i = i + 1 }   // Check that the number of perms generated is equal to 11! (this takes a while). var count = genFactBaseNums.call(10, true)[1] Fmt.print("\nPermutations generated = $,d", count) Fmt.print("compared to 11! which = $,d", Int.factorial(11)) System.print()   // Generate shuffles for the 2 given 51 digit factorial base numbers. var fbn51s = [ "39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0", "51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1" ] factNums = [undot.call(fbn51s[0]), undot.call(fbn51s[1])] perms = mapToPerms.call(factNums) var shoe = "A♠K♠Q♠J♠T♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥T♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦T♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣T♣9♣8♣7♣6♣5♣4♣3♣2♣".toList var cards = List.filled(52, null) for (i in 0..51) { cards[i] = shoe[2*i..2*i+1].join() if (cards[i][0] == "T") cards[i] = "10" + cards[i][1..-1] } i = 0 for (fbn51 in fbn51s) { System.print(fbn51) for (d in perms[i]) System.write(cards[d]) System.print("\n") i = i + 1 }   // Create a random 51 digit factorial base number and produce a shuffle from that. var fbn51 = List.filled(51, 0) for (i in 0..50) fbn51[i] = rand.int(52-i) System.print(join.call(fbn51, ".")) perms = mapToPerms.call([fbn51]) for (d in perms[0]) System.write(cards[d]) System.print()
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Go
Go
package main   import ( "fmt" "strconv" )   func main() { // cache factorials from 0 to 11 var fact [12]uint64 fact[0] = 1 for n := uint64(1); n < 12; n++ { fact[n] = fact[n-1] * n }   for b := 9; b <= 12; b++ { fmt.Printf("The factorions for base %d are:\n", b) for i := uint64(1); i < 1500000; i++ { digits := strconv.FormatUint(i, b) sum := uint64(0) for _, digit := range digits { if digit < 'a' { sum += fact[digit-'0'] } else { sum += fact[digit+10-'a'] } } if sum == i { fmt.Printf("%d ", i) } } fmt.Println("\n") } }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Haskell
Haskell
import Text.Printf (printf) import Data.List (unfoldr) import Control.Monad (guard)   factorion :: Int -> Int -> Bool factorion b n = f b n == n where f b = sum . map (product . enumFromTo 1) . unfoldr (\x -> guard (x > 0) >> pure (x `mod` b, x `div` b))   main :: IO () main = mapM_ (uncurry (printf "Factorions for base %2d: %s\n") . (\(a, b) -> (b, result a b))) [(3,9), (4,10), (5,11), (2,12)] where factorions b = filter (factorion b) [1..] result n = show . take n . factorions
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.
#Tcl
Tcl
set l {56 21 71 27 39 62 87 76 82 94 45 83 65 45 28 90 52 44 1 89}   puts [lmap x $l {if {$x % 2} continue; set x}]
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
#PL.2FI
PL/I
do i = 1 to 100; select; when (mod(i,15) = 0) put skip list ('FizzBuzz'); when (mod(i,3) = 0) put skip list ('Fizz'); when (mod(i,5) = 0) put skip list ('Buzz'); otherwise put skip list (i); end; end;
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.
#AutoHotkey
AutoHotkey
SetBatchLines, -1 p := 1 ;p functions as the counter Loop, 10000 { p := NextPrime(p) if (A_Index < 21) a .= p ", " if (p < 151 && p > 99) b .= p ", " if (p < 8001 && p > 7699) c++ } MsgBox, % "First twenty primes: " RTrim(a, ", ") . "`nPrimes between 100 and 150: " RTrim(b, ", ") . "`nNumber of primes between 7,700 and 8,000: " RTrim(c, ", ") . "`nThe 10,000th prime: " p   NextPrime(n) { Loop if (IsPrime(++n)) return n }   IsPrime(n) { if (n < 2) return, 0 else if (n < 4) return, 1 else if (!Mod(n, 2)) return, 0 else if (n < 9) return 1 else if (!Mod(n, 3)) return, 0 else { r := Floor(Sqrt(n)) f := 5 while (f <= r) { if (!Mod(n, f)) return, 0 if (!Mod(n, (f + 2))) return, 0 f += 6 } return, 1 } }
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
#Free_Pascal
Free Pascal
type /// domain for Fibonacci function /// where result is within nativeUInt // You can not name it fibonacciDomain, // since the Fibonacci function itself // is defined for all whole numbers // but the result beyond F(n) exceeds high(nativeUInt). fibonacciLeftInverseRange = {$ifdef CPU64} 0..93 {$else} 0..47 {$endif};   {** implements Fibonacci sequence iteratively   \param n the index of the Fibonacci number to calculate \returns the Fibonacci value at n } function fibonacci(const n: fibonacciLeftInverseRange): nativeUInt; type /// more meaningful identifiers than simple integers relativePosition = (previous, current, next); var /// temporary iterator variable i: longword; /// holds preceding fibonacci values f: array[relativePosition] of nativeUInt; begin f[previous] := 0; f[current] := 1;   // note, in Pascal for-loop-limits are inclusive for i := 1 to n do begin f[next] := f[previous] + f[current]; f[previous] := f[current]; f[current] := f[next]; end;   // assign to previous, bc f[current] = f[next] for next iteration fibonacci := f[previous]; end;
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Phix
Phix
?factors(12345,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
#Groovy
Groovy
def negInf = -1.0d / 0.0d; //also Double.NEGATIVE_INFINITY def inf = 1.0d / 0.0d; //also Double.POSITIVE_INFINITY def nan = 0.0d / 0.0d; //also Double.NaN def negZero = -2.0d / inf;   println(" Negative inf: " + negInf); println(" Positive inf: " + inf); println(" NaN: " + nan); println(" Negative 0: " + negZero); println(" inf + -inf: " + (inf + negInf)); println(" 0 * NaN: " + (0 * nan)); println(" NaN == NaN: " + (nan == nan)); println("NaN equals NaN: " + (nan.equals(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
#haskell
haskell
  main = do let inf = 1/0 let minus_inf = -1/0 let minus_zero = -1/inf let nan = 0/0   putStrLn ("Positive infinity = "++(show inf)) putStrLn ("Negative infinity = "++(show minus_inf)) putStrLn ("Negative zero = "++(show minus_zero)) putStrLn ("Not a number = "++(show nan))   --Some Arithmetic   putStrLn ("inf + 2.0 = "++(show (inf+2.0))) putStrLn ("inf - 10 = "++(show (inf-10))) putStrLn ("inf - inf = "++(show (inf-inf))) putStrLn ("inf * 0 = "++(show (inf * 0))) putStrLn ("nan + 1.0= "++(show (nan+1.0))) putStrLn ("nan + nan = "++(show (nan + nan)))   --Some Comparisons   putStrLn ("nan == nan = "++(show (nan == nan))) putStrLn ("0.0 == - 0.0 = "++(show (0.0 == minus_zero))) putStrLn ("inf == inf = "++(show (inf == inf)))  
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.
#ALGOL_W
ALGOL W
begin  % executes pBoth, p1, p2 or pNeither  %  % depending on whether c1 and c2 are true, c1 is true, c2 is true  %  % neither c1 nor c2 are true  % procedure if2 ( logical value c1, c2  ; procedure pBoth, p1, p2, pNeither ); if c1 and c2 then pBoth else if c1 then p1 else if c2 then p2 else pNeither  ; begin logical a, b; a := true; b := false; if2( a, b , write( "both: a and b are TRUE" ) , write( "first: only a is TRUE" ) , write( "second: only b is TRUE" ) , write( "neither: a and b are FALSE" ) ) end 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.
#Arturo
Arturo
if2: function [cond1 cond2 both one two none][ case [] when? [and? cond1 cond2] -> do both when? [cond1] -> do one when? [cond2] -> do two else -> do none ]   if2 false true [print "both"] [print "only first"] [print "only second"] [print "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
#11l
11l
print(5 ^ 3 ^ 2) print((5 ^ 3) ^ 2) print(5 ^ (3 ^ 2))
http://rosettacode.org/wiki/Factorial_base_numbers_indexing_permutations_of_a_collection
Factorial base numbers indexing permutations of a collection
You need a random arrangement of a deck of cards, you are sick of lame ways of doing this. This task is a super-cool way of doing this using factorial base numbers. The first 25 factorial base numbers in increasing order are: 0.0.0, 0.0.1, 0.1.0, 0.1.1, 0.2.0, 0.2.1, 1.0.0, 1.0.1, 1.1.0, 1.1.1,1.2.0, 1.2.1, 2.0.0, 2.0.1, 2.1.0, 2.1.1, 2.2.0, 2.2.1, 3.0.0, 3.0.1, 3.1.0, 3.1.1, 3.2.0, 3.2.1, 1.0.0.0 Observe that the least significant digit is base 2 the next base 3, in general an n-digit factorial base number has digits n..1 in base n+1..2. I want to produce a 1 to 1 mapping between these numbers and permutations:- 0.0.0 -> 0123 0.0.1 -> 0132 0.1.0 -> 0213 0.1.1 -> 0231 0.2.0 -> 0312 0.2.1 -> 0321 1.0.0 -> 1023 1.0.1 -> 1032 1.1.0 -> 1203 1.1.1 -> 1230 1.2.0 -> 1302 1.2.1 -> 1320 2.0.0 -> 2013 2.0.1 -> 2031 2.1.0 -> 2103 2.1.1 -> 2130 2.2.0 -> 2301 2.2.1 -> 2310 3.0.0 -> 3012 3.0.1 -> 3021 3.1.0 -> 3102 3.1.1 -> 3120 3.2.0 -> 3201 3.2.1 -> 3210 The following psudo-code will do this: Starting with m=0 and Ω, an array of elements to be permutated, for each digit g starting with the most significant digit in the factorial base number. If g is greater than zero, rotate the elements from m to m+g in Ω (see example) Increment m and repeat the first step using the next most significant digit until the factorial base number is exhausted. For example: using the factorial base number 2.0.1 and Ω = 0 1 2 3 where place 0 in both is the most significant (left-most) digit/element. Step 1: m=0 g=2; Rotate places 0 through 2. 0 1 2 3 becomes 2 0 1 3 Step 2: m=1 g=0; No action. Step 3: m=2 g=1; Rotate places 2 through 3. 2 0 1 3 becomes 2 0 3 1 Let me work 2.0.1 and 0123 step 1 n=0 g=2 Ω=2013 step 2 n=1 g=0 so no action step 3 n=2 g=1 Ω=2031 The task: First use your function to recreate the above table. Secondly use your function to generate all permutaions of 11 digits, perhaps count them don't display them, compare this method with methods in rc's permutations task. Thirdly here following are two ramdom 51 digit factorial base numbers I prepared earlier: 39.49.7.47.29.30.2.12.10.3.29.37.33.17.12.31.29.34.17.25.2.4.25.4.1.14.20.6.21.18.1.1.1.4.0.5.15.12.4.3.10.10.9.1.6.5.5.3.0.0.0 51.48.16.22.3.0.19.34.29.1.36.30.12.32.12.29.30.26.14.21.8.12.1.3.10.4.7.17.6.21.8.12.15.15.13.15.7.3.12.11.9.5.5.6.6.3.4.0.3.2.1 use your function to crate the corresponding permutation of the following shoe of cards: A♠K♠Q♠J♠10♠9♠8♠7♠6♠5♠4♠3♠2♠A♥K♥Q♥J♥10♥9♥8♥7♥6♥5♥4♥3♥2♥A♦K♦Q♦J♦10♦9♦8♦7♦6♦5♦4♦3♦2♦A♣K♣Q♣J♣10♣9♣8♣7♣6♣5♣4♣3♣2♣ Finally create your own 51 digit factorial base number and produce the corresponding permutation of the above shoe
#zkl
zkl
fcn fpermute(omega,num){ // eg (0,1,2,3), (0,0,0)..(3,2,1) omega=omega.copy(); // omega gonna be mutated foreach m,g in ([0..].zip(num)){ if(g) omega.insert(m,omega.pop(m+g)) } omega }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#J
J
  index=: $ #: I.@:, factorion=: 10&$: :(] = [: +/ [: ! #.^:_1)&>   FACTORIONS=: 9 0 +"1 index Q=: 9 10 11 12 factorion/ i. 1500000   NB. base, factorion expressed in bases 10, and base (,. ".@:((Num_j_,26}.Alpha_j_) {~ #.inv/)"1) FACTORIONS 9 1 1 9 2 2 9 41282 62558 10 1 1 10 2 2 10 145 145 10 40585 40585 11 1 1 11 2 2 11 26 24 11 48 44 11 40472 28453 12 1 1 12 2 2   NB. tallies of factorions in the bases (9+i.4),.+/"1 Q 9 3 10 4 11 5 12 2  
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Java
Java
  public class Factorion { public static void main(String [] args){ System.out.println("Base 9:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,9); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 10:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,10); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 11:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,11); if(multiplied == i){ System.out.print(i + "\t"); } } System.out.println("\nBase 12:"); for(int i = 1; i <= 1499999; i++){ String iStri = String.valueOf(i); int multiplied = operate(iStri,12); if(multiplied == i){ System.out.print(i + "\t"); } } } public static int factorialRec(int n){ int result = 1; return n == 0 ? result : result * n * factorialRec(n-1); }   public static int operate(String s, int base){ int sum = 0; String strx = fromDeci(base, Integer.parseInt(s)); for(int i = 0; i < strx.length(); i++){ if(strx.charAt(i) == 'A'){ sum += factorialRec(10); }else if(strx.charAt(i) == 'B') { sum += factorialRec(11); }else if(strx.charAt(i) == 'C') { sum += factorialRec(12); }else { sum += factorialRec(Integer.parseInt(String.valueOf(strx.charAt(i)), base)); } } return sum; } // Ln 57-71 from Geeks for Geeks @ https://www.geeksforgeeks.org/convert-base-decimal-vice-versa/ static char reVal(int num) { if (num >= 0 && num <= 9) return (char)(num + 48); else return (char)(num - 10 + 65); } static String fromDeci(int base, int num){ StringBuilder s = new StringBuilder(); while (num > 0) { s.append(reVal(num % base)); num /= base; } return new String(new StringBuilder(s).reverse()); } }  
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.
#Toka
Toka
10 cells is-array table 10 cells is-array even { variable source [ swap source ! >r reset r> 0 [ i source @ array.get dup 2 mod 0 <> [ drop ] ifTrue ] countedLoop depth 0 swap [ i even array.put ] countedLoop ] } is copy-even 10 0 [ i i table array.put ] countedLoop table 10 copy-even
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
#PL.2FM
PL/M
100H:   /* DECLARE OUTPUT IN TERMS OF CP/M - PL/M DOES NOT COME WITH ANY STANDARD LIBRARY */ BDOS: PROCEDURE(FUNC, ARG); DECLARE FUNC BYTE, ARG ADDRESS; GO TO 5; END BDOS;   PUT$STRING: PROCEDURE(STR); DECLARE STR ADDRESS; CALL BDOS(9, STR); CALL BDOS(9, .(13,10,'$')); END PUT$STRING;   /* PRINT A NUMBER */ PUT$NUMBER: PROCEDURE(N); DECLARE S (5) BYTE INITIAL ('...$'); DECLARE P ADDRESS; DECLARE (N, D, C BASED P) BYTE; P = .S(3); DIGIT: P = P-1; C = (N MOD 10) + '0'; N = N/10; IF N > 0 THEN GO TO DIGIT; CALL PUT$STRING(P); END PUT$NUMBER;   /* FIZZBUZZ */ DECLARE N BYTE; DO N = 1 TO 100; IF N MOD 15 = 0 THEN CALL PUT$STRING(.'FIZZBUZZ$'); ELSE IF N MOD 5 = 0 THEN CALL PUT$STRING(.'BUZZ$'); ELSE IF N MOD 3 = 0 THEN CALL PUT$STRING(.'FIZZ$'); ELSE CALL PUT$NUMBER(N); END;   /* EXIT TO CP/M */ CALL BDOS(0,0); EOF
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.
#BQN
BQN
# Function that returns a new prime generator PrimeGen ← {𝕤 i ← 0 # Counter: index of next prime to be output primes ← ↕0 next ← 2 Sieve ← { p 𝕊 i‿n: E ← {↕∘⌈⌾(((𝕩|-i)+𝕩×⊢)⁼)n-i} # Indices of multiples of 𝕩 i + / (1⥊˜n-i) E⊸{0¨⌾(𝕨⊸⊏)𝕩}´ p # Primes in segment [i,n) } {𝕤 { i=≠primes ? # Extend if required next ↩ ((2⋆24)⊸+ ⌊ ט) old←next # Sieve at most 16M new entries primes ∾↩ (primes(⍋↑⊣)√next) Sieve old‿next  ;@} (i+↩1) ⊢ i⊑primes } } _w_←{𝔽⍟𝔾∘𝔽_𝕣_𝔾∘𝔽⍟𝔾𝕩} # Looping utility for the session below
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
#FreeBASIC
FreeBASIC
'Fibonacci extended 'Freebasic version 24 Windows Dim Shared ADDQmod(0 To 19) As Ubyte Dim Shared ADDbool(0 To 19) As Ubyte   For z As Integer=0 To 19 ADDQmod(z)=(z Mod 10+48) ADDbool(z)=(-(10<=z)) Next z   Function plusINT(NUM1 As String,NUM2 As String) As String Dim As Byte flag #macro finish() three=Ltrim(three,"0") If three="" Then Return "0" If flag=1 Then Swap NUM2,NUM1 Return three Exit Function #endmacro var lenf=Len(NUM1) var lens=Len(NUM2) If lens>lenf Then Swap NUM2,NUM1 Swap lens,lenf flag=1 End If   var diff=lenf-lens-Sgn(lenf-lens) var three="0"+NUM1 var two=String(lenf-lens,"0")+NUM2 Dim As Integer n2 Dim As Ubyte addup,addcarry   addcarry=0   For n2=lenf-1 To diff Step -1 addup=two[n2]+NUM1[n2]-96 three[n2+1]=addQmod(addup+addcarry) addcarry=addbool(addup+addcarry) Next n2 If addcarry=0 Then finish() End If If n2=-1 Then three[0]=addcarry+48 finish() End If   For n2=n2 To 0 Step -1 addup=two[n2]+NUM1[n2]-96 three[n2+1]=addQmod(addup+addcarry) addcarry=addbool(addup+addcarry) Next n2 three[0]=addcarry+48 finish() End Function   Function fibonacci(n As Integer) As String Dim As String sl,l,term sl="0": l="1" If n=1 Then Return "0" If n=2 Then Return "1" n=n-2 For x As Integer= 1 To n term=plusINT(l,sl) sl=l l=term Next x Function =term End Function   '============== EXAMPLE =============== print "THE SEQUENCE TO 10:" print For n As Integer=1 To 10 Print "term";n;": "; fibonacci(n) Next n print print "Selected Fibonacci number" print "Fibonacci 500" print print fibonacci(500) Sleep
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
#Phixmonti
Phixmonti
/# Rosetta Code problem: http://rosettacode.org/wiki/Factors_of_an_integer by Galileo, 05/2022 #/   include ..\Utilitys.pmt   def Factors >ps ( ( 1 tps 2 / ) for tps over mod if drop endif endfor ps> ) enddef   11 Factors 21 Factors 32 factors 45 factors 67 factors 96 factors   pstack
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
#Icon_and_Unicon
Icon and Unicon
Inf=: _ NegInf=: __ NB. Negative zero cannot be represented in J to be distinct from 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
#J
J
Inf=: _ NegInf=: __ NB. Negative zero cannot be represented in J to be distinct from 0. NaN=. _.
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.
#ATS
ATS
(* Languages with pattern matching ALREADY HAVE THIS! *)   fn func (pred1 : bool, pred2 : bool) : void = case+ (pred1, pred2) of | (true, true) => println! ("(true, true)") | (true, false) => println! ("(true, false)") | (false, true) => println! ("(false, true)") | (false, false) => println! ("(false, false)")   implement main0 () = begin func (true, true); func (true, false); func (false, true); func (false, false) 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.
#C
C
/* Four-way branch. * * if2 (firsttest, secondtest * , bothtrue * , firstrue * , secondtrue * , bothfalse * ) */ #define if2(firsttest,secondtest,bothtrue,firsttrue,secondtrue,bothfalse)\ switch(((firsttest)?0:2)+((secondtest)?0:1)) {\ case 0: bothtrue; break;\ case 1: firsttrue; break;\ case 2: secondtrue; break;\ case 3: bothfalse; break;\ }  
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
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   PROC Main() REAL r2,r3,r5,tmp1,tmp2   Put(125) PutE() ;clear screen   IntToReal(2,r2) IntToReal(3,r3) IntToReal(5,r5)   PrintE("There is no power operator in Action!") PrintE("Power function for REAL type is used.") PrintE("But the precision is insufficient.") Power(r5,r3,tmp1) Power(tmp1,r2,tmp2) Print("(5^3)^2=") PrintRE(tmp2)   Power(r3,r2,tmp1) Power(r5,tmp1,tmp2) Print("5^(3^2)=") PrintRE(tmp2) RETURN
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
#Ada
Ada
with Ada.Text_IO;   procedure Exponentation_Order is use Ada.Text_IO; begin -- Put_Line ("5**3**2  : " & Natural'(5**3**2)'Image); Put_Line ("(5**3)**2 : " & Natural'((5**3)**2)'Image); Put_Line ("5**(3**2) : " & Natural'(5**(3**2))'Image); end Exponentation_Order;
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
#ALGOL_68
ALGOL 68
print( ( "5**3**2: ", 5**3**2, newline ) ); print( ( "(5**3)**2: ", (5**3)**2, newline ) ); print( ( "5**(3**2): ", 5**(3**2), newline ) )
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Julia
Julia
isfactorian(n, base) = mapreduce(factorial, +, map(c -> parse(Int, c, base=16), split(string(n, base=base), ""))) == n   printallfactorian(base) = println("Factorians for base $base: ", [n for n in 1:100000 if isfactorian(n, base)])   foreach(printallfactorian, 9:12)  
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[FactorionQ] FactorionQ[n_,b_:10]:=Total[IntegerDigits[n,b]!]==n Select[Range[1500000],FactorionQ[#,9]&] Select[Range[1500000],FactorionQ[#,10]&] Select[Range[1500000],FactorionQ[#,11]&] Select[Range[1500000],FactorionQ[#,12]&]
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Nim
Nim
from math import fac from strutils import join   iterator digits(n, base: Natural): Natural = ## Yield the digits of "n" in base "base". var n = n while true: yield n mod base n = n div base if n == 0: break   func isFactorion(n, base: Natural): bool = ## Return true if "n" is a factorion for base "base". var s = 0 for d in n.digits(base): inc s, fac(d) result = s == n   func factorions(base, limit: Natural): seq[Natural] = ## Return the list of factorions for base "base" up to "limit". for n in 1..limit: if n.isFactorion(base): result.add(n)     for base in 9..12: echo "Factorions for base ", base, ':' echo factorions(base, 1_500_000 - 1).join(" ")
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.
#TUSCRIPT
TUSCRIPT
  $$ MODE TUSCRIPT arr="1'4'9'16'25'36'49'64'81'100",even="" LOOP nr=arr rest=MOD (nr,2) IF (rest==0) even=APPEND (even,nr) ENDLOOP PRINT even  
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
#PL.2FSQL
PL/SQL
BEGIN FOR i IN 1 .. 100 LOOP CASE WHEN MOD(i, 15) = 0 THEN DBMS_OUTPUT.put_line('FizzBuzz'); WHEN MOD(i, 5) = 0 THEN DBMS_OUTPUT.put_line('Buzz'); WHEN MOD(i, 3) = 0 THEN DBMS_OUTPUT.put_line('Fizz'); ELSE DBMS_OUTPUT.put_line(i); END CASE; END LOOP; END;
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h>   #define CHUNK_BYTES (32 << 8) #define CHUNK_SIZE (CHUNK_BYTES << 6)   int field[CHUNK_BYTES]; #define GET(x) (field[(x)>>6] & 1<<((x)>>1&31)) #define SET(x) (field[(x)>>6] |= 1<<((x)>>1&31))   typedef unsigned uint; typedef struct { uint *e; uint cap, len; } uarray; uarray primes, offset;   void push(uarray *a, uint n) { if (a->len >= a->cap) { if (!(a->cap *= 2)) a->cap = 16; a->e = realloc(a->e, sizeof(uint) * a->cap); } a->e[a->len++] = n; }   uint low; void init(void) { uint p, q;   unsigned char f[1<<16]; memset(f, 0, sizeof(f)); push(&primes, 2); push(&offset, 0); for (p = 3; p < 1<<16; p += 2) { if (f[p]) continue; for (q = p*p; q < 1<<16; q += 2*p) f[q] = 1; push(&primes, p); push(&offset, q); } low = 1<<16; }   void sieve(void) { uint i, p, q, hi, ptop; if (!low) init();   memset(field, 0, sizeof(field));   hi = low + CHUNK_SIZE; ptop = sqrt(hi) * 2 + 1;   for (i = 1; (p = primes.e[i]*2) < ptop; i++) { for (q = offset.e[i] - low; q < CHUNK_SIZE; q += p) SET(q); offset.e[i] = q + low; }   for (p = 1; p < CHUNK_SIZE; p += 2) if (!GET(p)) push(&primes, low + p);   low = hi; }   int main(void) { uint i, p, c;   while (primes.len < 20) sieve(); printf("First 20:"); for (i = 0; i < 20; i++) printf(" %u", primes.e[i]); putchar('\n');   while (primes.e[primes.len-1] < 150) sieve(); printf("Between 100 and 150:"); for (i = 0; i < primes.len; i++) { if ((p = primes.e[i]) >= 100 && p < 150) printf(" %u", primes.e[i]); } putchar('\n');   while (primes.e[primes.len-1] < 8000) sieve(); for (i = c = 0; i < primes.len; i++) if ((p = primes.e[i]) >= 7700 && p < 8000) c++; printf("%u primes between 7700 and 8000\n", c);   for (c = 10; c <= 100000000; c *= 10) { while (primes.len < c) sieve(); printf("%uth prime: %u\n", c, primes.e[c-1]); }   return 0; }
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
#Frink
Frink
  fibonacciN[n] := { a = 0 b = 1 count = 0 while count < n { [a,b] = [b, a + b] count = count + 1 } return 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
#PHP
PHP
function GetFactors($n){ $factors = array(1, $n); for($i = 2; $i * $i <= $n; $i++){ if($n % $i == 0){ $factors[] = $i; if($i * $i != $n) $factors[] = $n/$i; } } sort($factors); return $factors; }
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.   For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it. Bonus Points Run all 5 sample programs at the aforementioned website and output their results.
#ALGOL_68
ALGOL 68
BEGIN # execute some ComputerZero programs # # instructions # INT nop = 0, lda = 1, sta = 2, add = 3, sub = 4, brz = 5, jmp = 6, stp = 7; PROC instr = ( INT op, v )INT: ( 32 * op ) + v; OP NOP = ( INT v )INT: instr( nop, v ); OP LDA = ( INT v )INT: instr( lda, v ); OP STA = ( INT v )INT: instr( sta, v ); OP ADD = ( INT v )INT: instr( add, v ); OP SUB = ( INT v )INT: instr( sub, v ); OP BRZ = ( INT v )INT: instr( brz, v ); OP JMP = ( INT v )INT: instr( jmp, v ); OP STP = ( INT v )INT: instr( stp, v ); # executes the program named name # PROC execute = ( STRING name, []INT program )VOID: BEGIN [ 0 : 31 ]INT m; # the computer 32 has bytes of memory # FOR i FROM LWB m TO UPB m DO m[ i ] := 0 OD; # "assemble" the program # INT m pos := -1; FOR i FROM LWB program TO UPB program DO m[ m pos +:= 1 ] := program[ i ] OD; # execute the program # BOOL running := TRUE; INT pc := 0; INT a := 0; WHILE running DO INT op := m[ pc ] OVER 32; INT operand := m[ pc ] MOD 32; pc +:= 1 MODAB 32; IF op = nop THEN SKIP ELIF op = lda THEN a := m[ operand ] ELIF op = sta THEN m[ operand ] := a ELIF op = add THEN a +:= m[ operand ] MODAB 256 ELIF op = sub THEN a -:= m[ operand ] MODAB 256 ELIF op = brz THEN IF a = 0 THEN pc := operand FI ELIF op = jmp THEN pc := operand ELSE # stp # running := FALSE; print( ( " " * ( 12 - ( ( UPB name - LWB name ) + 1 ) ) ) ); print( ( name, ": ", whole( a, -3 ), newline ) ) FI OD END # execute # ; # task test programs (from the Computer Zero website) # # the unary NOP, LDA, STA, etc. operators are used to construct the # # instructions; as parameterless operators aren't allowed, NOP and STP # # must have a dummy parameter # execute( "2+2", ( LDA 3, ADD 4, STP 0, 2, 2 ) ); execute( "7*8" , ( LDA 12, ADD 10, STA 12, LDA 11, SUB 13, STA 11, BRZ 8, JMP 0 , LDA 12, STP 0, 8, 7, 0, 1 ) ); execute( "fibonacci" , ( LDA 14, STA 15, ADD 13, STA 14, LDA 15, STA 13, LDA 16, SUB 17 , BRZ 11, STA 16, JMP 0, LDA 14, STP 0, 1, 1, 0 , 8, 1 ) ); execute( "linkedList" , ( LDA 13, ADD 15, STA 5, ADD 16, STA 7, NOP 0, STA 14, NOP 0 , BRZ 11, STA 15, JMP 0, LDA 14, STP 0, LDA 0, 0, 28 , 1, 0, 0, 0, 6, 0, 2, 26 , 5, 20, 3, 30, 1, 22, 4, 24 ) ); execute( "prisoner" , ( NOP 0, NOP 0, STP 0, 0, LDA 3, SUB 29, BRZ 18, LDA 3 , STA 29, BRZ 14, LDA 1, ADD 31, STA 1, JMP 2, LDA 0, ADD 31 , STA 0, JMP 2, LDA 3, STA 29, LDA 1, ADD 30, ADD 3, STA 1 , LDA 0, ADD 30, ADD 3, STA 0, JMP 2, 0, 1, 3 ) ); # subtractions yielding negative results # execute( "0-255", ( LDA 3, SUB 4, STP 0, 0, 255 ) ); execute( "0-1", ( LDA 3, SUB 4, STP 0, 0, 1 ) ); # overflow on addition # execute( "1+255", ( LDA 3, ADD 4, STP 0, 1, 255 ) ) END  
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#Java
Java
public class Extreme { public static void main(String[] args) { double negInf = -1.0 / 0.0; //also Double.NEGATIVE_INFINITY double inf = 1.0 / 0.0; //also Double.POSITIVE_INFINITY double nan = 0.0 / 0.0; //also Double.NaN double negZero = -2.0 / inf;   System.out.println("Negative inf: " + negInf); System.out.println("Positive inf: " + inf); System.out.println("NaN: " + nan); System.out.println("Negative 0: " + negZero); System.out.println("inf + -inf: " + (inf + negInf)); System.out.println("0 * NaN: " + (0 * nan)); System.out.println("NaN == NaN: " + (nan == 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.
#11l
11l
V HW = ‘ /++++!/===========?\>++.>+.+++++++..+++\ \+++\ | /+>+++++++>/ /++++++++++<<.++>./ $+++/ | \+++++++++>\ \+++++.>.+++.-----\ \==-<<<<+>+++/ /=.>.+>.--------.-/’   F snusp(store, code) V ds = [Byte(0)] * store V dp = 0 V cs = code.split("\n") V ipr = 0 V ipc = 0   L(row) cs ipc = row.findi(‘$’) I ipc != -1 ipr = L.index L.break   V id = 0   F step() I @id [&] 1 @ipr += 1 - (@id [&] 2) E @ipc += 1 - (@id [&] 2)   L ipr >= 0 & ipr < cs.len & ipc >= 0 & ipc < cs[ipr].len S cs[ipr][ipc] ‘>’ dp++ ‘<’ dp-- ‘+’ ds[dp]++ ‘-’ ds[dp]-- ‘.’  :stdout.write(Char(code' ds[dp])) ‘,’ ds[dp] = Byte(:stdin.read(1).code) ‘/’ id = (-)id ‘\’ id (+)= 1 ‘!’ step() ‘?’ I !(ds[dp]) step() step()   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.
#C.23
C#
    using System; using System.Reflection;   namespace Extend_your_language {     class Program {   public static void Main(string[] args) { Console.WriteLine(); Console.WriteLine("Hello World!"); Console.WriteLine();   int x = 0; int y = 0;   for(x=0;x<2;x++) { for(y=0;y<2;y++) {   CONDITIONS( (x==0) , (y==0) ). IF2 ("METHOD1"). ELSE1("METHOD2"). ELSE2("METHOD3"). ELSE ("METHOD4");   } }   Console.WriteLine(); Console.Write("Press any key to continue . . . "); Console.ReadKey(true); }         public static void METHOD1() { Console.WriteLine("METHOD 1 executed - both are true"); }   public static void METHOD2() { Console.WriteLine("METHOD 2 executed - first is true"); }   public static void METHOD3() { Console.WriteLine("METHOD 3 executed - second is true"); }   public static void METHOD4() { Console.WriteLine("METHOD 4 executed - both are false"); }     static int CONDITIONS(bool condition1, bool condition2) { int c = 0; if(condition1 && condition2) c = 0; else if(condition1) c = 1; else if(condition2) c = 2; else c = 3;   return c; } }     public static class ExtensionMethods {   public static int IF2(this int value, string method) { if(value == 0) { MethodInfo m = typeof(Program).GetMethod(method); m.Invoke(null,null); }   return value; }   public static int ELSE1(this int value, string method) { if(value == 1) { MethodInfo m = typeof(Program).GetMethod(method); m.Invoke(null,null); }   return value; }   public static int ELSE2(this int value, string method) { if(value == 2) { MethodInfo m = typeof(Program).GetMethod(method); m.Invoke(null,null); }   return value; }   public static void ELSE(this int value, string method) { if(value == 3) { MethodInfo m = typeof(Program).GetMethod(method); m.Invoke(null,null); } }   } }    
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
#ALGOL_W
ALGOL W
begin write( "5**3**2: ", round( 5 ** 3 ** 2 ) ); write( "(5**3)**2: ", round( ( 5 ** 3 ) ** 2 ) ); write( "5**(3**2): ", round( 5 ** round( 3 ** 2 ) ) ) 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
#APL
APL
5*3*2 1953125 (5*3)*2 15625 5*(3*2) 1953125
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#AppleScript
AppleScript
set r1 to 5 ^ 3 ^ 2 -- Changes to 5 ^ (3 ^ 2) when compiled. set r2 to (5 ^ 3) ^ 2 set r3 to 5 ^ (3 ^ 2)   return "5 ^ 3 ^ 2 = " & r1 & " (5 ^ 3) ^ 2 = " & r2 & " 5 ^ (3 ^ 2) = " & r3
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#OCaml
OCaml
let () = (* cache factorials from 0 to 11 *) let fact = Array.make 12 0 in fact.(0) <- 1; for n = 1 to pred 12 do fact.(n) <- fact.(n-1) * n; done;   for b = 9 to 12 do Printf.printf "The factorions for base %d are:\n" b; for i = 1 to pred 1_500_000 do let sum = ref 0 in let j = ref i in while !j > 0 do let d = !j mod b in sum := !sum + fact.(d); j := !j / b; done; if !sum = i then (print_int i; print_string " ") done; print_string "\n\n"; done
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Pascal
Pascal
program munchhausennumber; {$IFDEF FPC}{$MODE objFPC}{$Optimization,On,all}{$ELSE}{$APPTYPE CONSOLE}{$ENDIF} uses sysutils; type tdigit = byte; const MAXBASE = 17;   var DgtPotDgt : array[0..MAXBASE-1] of NativeUint; dgtCnt : array[0..MAXBASE-1] of NativeInt; cnt: NativeUint;   function convertToString(n:NativeUint;base:byte):AnsiString; const cBASEDIGITS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz'; var r,dgt: NativeUint; begin IF base > length(cBASEDIGITS) then EXIT('Base to big'); result := ''; repeat r := n div base; dgt := n-r*base; result := cBASEDIGITS[dgt+1]+result; n := r; until n =0; end;   function CheckSameDigits(n1,n2,base:NativeUInt):boolean; var   i : NativeUInt; Begin fillchar(dgtCnt,SizeOf(dgtCnt),#0); repeat //increment digit of n1 i := n1;n1 := n1 div base;i := i-n1*base;inc(dgtCnt[i]); //decrement digit of n2 i := n2;n2 := n2 div base;i := i-n2*base;dec(dgtCnt[i]); until (n1=0) AND (n2= 0); result := true; For i := 2 to Base-1 do result := result AND (dgtCnt[i]=0); result := result AND (dgtCnt[0]+dgtCnt[1]=0);   end;   procedure Munch(number,DgtPowSum,minDigit:NativeUInt;digits,base:NativeInt); var i: NativeUint; s1,s2: AnsiString; begin inc(cnt); number := number*base; IF digits > 1 then Begin For i := minDigit to base-1 do Munch(number+i,DgtPowSum+DgtPotDgt[i],i,digits-1,base); end else For i := minDigit to base-1 do //number is always the arrangement of the digits leading to smallest number IF (number+i)<= (DgtPowSum+DgtPotDgt[i]) then IF CheckSameDigits(number+i,DgtPowSum+DgtPotDgt[i],base) then iF number+i>0 then begin s1 := convertToString(DgtPowSum+DgtPotDgt[i],base); s2 := convertToString(number+i,base); If length(s1)= length(s2) then writeln(Format('%*d %*s  %*s',[Base-1,DgtPowSum+DgtPotDgt[i],Base-1,s1,Base-1,s2])); end; end;   //factorions procedure InitDgtPotDgt(base:byte); var i: NativeUint; Begin DgtPotDgt[0]:= 1; For i := 1 to Base-1 do DgtPotDgt[i] := DgtPotDgt[i-1]*i; DgtPotDgt[0]:= 0; end; { //Munchhausen numbers procedure InitDgtPotDgt; var i,k,dgtpow: NativeUint; Begin // digit ^ digit ,special case 0^0 here 0 DgtPotDgt[0]:= 0; For i := 1 to Base-1 do Begin dgtpow := i; For k := 2 to i do dgtpow := dgtpow*i; DgtPotDgt[i] := dgtpow; end; end; } var base : byte; begin cnt := 0; For base := 2 to MAXBASE do begin writeln('Base = ',base); InitDgtPotDgt(base); Munch(0,0,0,base,base); end; writeln('Check Count ',cnt); end.
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#UNIX_Shell
UNIX Shell
a=(1 2 3 4 5) unset e[@] for ((i=0;i<${#a[@]};i++)); do [ $((a[$i]%2)) -eq 0 ] && e[$i]="${a[$i]}" done
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
#Pony
Pony
use "collections"   actor Main new create(env: Env) => for i in Range[I32](1, 100) do env.out.print(fizzbuzz(i)) end   fun fizzbuzz(n: I32): String => if (n % 15) == 0 then "FizzBuzz" elseif (n % 5) == 0 then "Buzz" elseif (n % 3) == 0 then "Fizz" else n.string() end
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.
#C.2B.2B
C++
#include <iostream> #include <cstdint> #include <queue> #include <utility> #include <vector> #include <limits>   template<typename integer> class prime_generator { public: integer next_prime(); integer count() const { return count_; } private: struct queue_item { queue_item(integer prime, integer multiple, unsigned int wheel_index) : prime_(prime), multiple_(multiple), wheel_index_(wheel_index) {} integer prime_; integer multiple_; unsigned int wheel_index_; }; struct cmp { bool operator()(const queue_item& a, const queue_item& b) const { return a.multiple_ > b.multiple_; } }; static integer wheel_next(unsigned int& index) { integer offset = wheel_[index]; ++index; if (index == std::size(wheel_)) index = 0; return offset; } typedef std::priority_queue<queue_item, std::vector<queue_item>, cmp> queue; integer next_ = 11; integer count_ = 0; queue queue_; unsigned int wheel_index_ = 0; static const unsigned int wheel_[]; static const integer primes_[]; };   template<typename integer> const unsigned int prime_generator<integer>::wheel_[] = { 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2, 10, 2, 10 };   template<typename integer> const integer prime_generator<integer>::primes_[] = { 2, 3, 5, 7 };   template<typename integer> integer prime_generator<integer>::next_prime() { if (count_ < std::size(primes_)) return primes_[count_++]; integer n = next_; integer prev = 0; while (!queue_.empty()) { queue_item item = queue_.top(); if (prev != 0 && prev != item.multiple_) n += wheel_next(wheel_index_); if (item.multiple_ > n) break; else if (item.multiple_ == n) { queue_.pop(); queue_item new_item(item); new_item.multiple_ += new_item.prime_ * wheel_next(new_item.wheel_index_); queue_.push(new_item); } else throw std::overflow_error("prime_generator: overflow!"); prev = item.multiple_; } if (std::numeric_limits<integer>::max()/n > n) queue_.emplace(n, n * n, wheel_index_); next_ = n + wheel_next(wheel_index_); ++count_; return n; }   int main() { typedef uint32_t integer; prime_generator<integer> pgen; std::cout << "First 20 primes:\n"; for (int i = 0; i < 20; ++i) { integer p = pgen.next_prime(); if (i != 0) std::cout << ", "; std::cout << p; } std::cout << "\nPrimes between 100 and 150:\n"; for (int n = 0; ; ) { integer p = pgen.next_prime(); if (p > 150) break; if (p >= 100) { if (n != 0) std::cout << ", "; std::cout << p; ++n; } } int count = 0; for (;;) { integer p = pgen.next_prime(); if (p > 8000) break; if (p >= 7700) ++count; } std::cout << "\nNumber of primes between 7700 and 8000: " << count << '\n';   for (integer n = 10000; n <= 10000000; n *= 10) { integer prime; while (pgen.count() != n) prime = pgen.next_prime(); std::cout << n << "th prime: " << prime << '\n'; } return 0; }
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
#FRISC_Assembly
FRISC Assembly
FIBONACCI PUSH R1 PUSH R2 PUSH R3   MOVE 0, R1 MOVE 1, R2   FIB_LOOP SUB R0, 1, R0 JP_Z FIB_DONE   MOVE R2, R3 ADD R1, R2, R2 MOVE R3, R1   JP FIB_LOOP   FIB_DONE MOVE R2, R0   POP R3 POP R2 POP R1   RET
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
#Picat
Picat
factors(N) = [[D,N // D] : D in 1..N.sqrt.floor, N mod D == 0].flatten.sort_remove_dups.
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.   For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it. Bonus Points Run all 5 sample programs at the aforementioned website and output their results.
#J
J
OPS=: 'nop lda sta add sub brz jmp stp'   assemble1=: {{ y=. tolower y ins=. {.;:y-.":i.10 cod=. 8|(;:OPS) i. ins val=. {.0".y-.OPS if. *cod do. assert. 32>val val+32*cod else. assert. 256>val val end. }}   assemble=: {{ if. 0=L. y do. delim=. {.((tolower y)-.(":i.10),;OPS),LF y=. delim cut y end. code=. assemble1@> y mem=: code (i.#code)} 32#0 }}   exec1=: {{ 'cod val'=. 0 32#:pc{mem pc=: 32|pc+1 select. cod case. 0 do. case. 1 do. acc=: val{mem case. 2 do. mem=: acc val} mem case. 3 do. acc=: 256|acc+val{mem case. 4 do. acc=: 256|acc-val{mem case. 5 do. pc=: 32|pc[^:(*acc) val case. 6 do. pc=: 32|val case. 7 do. pc=: __ end. }}   exec=: {{ pc=: acc=: 0 while. 0<:pc do. exec1'' end. acc }}
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.   For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it. Bonus Points Run all 5 sample programs at the aforementioned website and output their results.
#Julia
Julia
mutable struct ComputerZero ip::Int ram::Vector{UInt8} accum::UInt8 isready::Bool end function ComputerZero(program) memory = zeros(UInt8, 32) for i in 1:min(32, length(program)) memory[i] = program[i] end return ComputerZero(1, memory, 0, true) end   NOP(c) = (c.ip = mod1(c.ip + 1, 32)) LDA(c) = (c.accum = c.ram[c.ram[c.ip] & 0b00011111 + 1]; c.ip = mod1(c.ip + 1, 32)) STA(c) = (c.ram[c.ram[c.ip] & 0b00011111 + 1] = c.accum; c.ip = mod1(c.ip + 1, 32)) ADD(c) = (c.accum += c.ram[c.ram[c.ip] & 0b00011111 + 1]; c.ip = mod1(c.ip + 1, 32)) SUB(c) = (c.accum -= c.ram[c.ram[c.ip] & 0b00011111 + 1]; c.ip = mod1(c.ip + 1, 32)) BRZ(c) = (c.ip = (c.accum == 0) ? c.ram[c.ip] & 0b00011111 + 1 : mod1(c.ip + 1, 32)) JMP(c) = (c.ip = c.ram[c.ip] & 0b00011111 + 1) STP(c) = (println("Program completed with accumulator value $(c.accum).\n"); c.isready = false)   const step = [NOP, LDA, STA, ADD, SUB, BRZ, JMP, STP] const instructions = ["NOP", "LDA", "STA", "ADD", "SUB", "BRZ", "JMP", "STP"] const assemblywords = Dict(s => i - 1 for (i, s) in pairs(instructions))   function run(compzero::ComputerZero, debug = false) while compzero.isready instruction = compzero.ram[compzero.ip] opcode, operand = instruction >> 5 + 1, instruction & 0b00011111 debug && println("op $(instructions[opcode]), operand $operand") step[opcode](compzero) end return compzero.accum end run(program::Vector, debug = false) = run(ComputerZero(program), debug)   function compile(text::String) bin, lines = UInt8[], 0 for line in strip.(split(text, "\n")) lines += 1 if isempty(line) push!(bin, 0) elseif (m = match(r"(\w\w\w)\s+(\d\d?)", line)) != nothing push!(bin, UInt8((assemblywords[m.captures[1]] << 5) | parse(UInt8, m.captures[2]))) elseif (m = match(r"(\w\w\w)", line)) != nothing push!(bin, UInt8(assemblywords[m.match] << 5)) elseif (m = match(r"\d\d?", line)) != nothing push!(bin, parse(UInt8, m.match)) else error("Compilation error at line $lines: error parsing <$line>") end end println("Compiled $lines lines.") return bin end   const testprograms = [ """ LDA 3 ADD 4 STP 2 2 """, """ LDA 12 ADD 10 STA 12 LDA 11 SUB 13 STA 11 BRZ 8 JMP 0 LDA 12 STP 8 7 0 1 """, """ LDA 14 STA 15 ADD 13 STA 14 LDA 15 STA 13 LDA 16 SUB 17 BRZ 11 STA 16 JMP 0 LDA 14 STP 1 1 0 8 1 """, """ LDA 13 ADD 15 STA 5 ADD 16 STA 7 NOP STA 14 NOP BRZ 11 STA 15 JMP 0 LDA 14 STP LDA 0 0 28 1       6 0 2 26 5 20 3 30 1 22 4 24 """, """ 0 0 STP NOP LDA 3 SUB 29 BRZ 18 LDA 3 STA 29 BRZ 14 LDA 1 ADD 31 STA 1 JMP 2 LDA 0 ADD 31 STA 0 JMP 2 LDA 3 STA 29 LDA 0 ADD 30 ADD 3 STA 0 LDA 1 ADD 30 ADD 3 STA 1 JMP 2 0 1 3 """ ]   for t in testprograms run(compile(t)) end  
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#jq
jq
0/0 #=> null 1e1000 #=> 1.7976931348623157e+308
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
#Julia
Julia
  function showextremes() values = [0.0, -0.0, Inf, -Inf, NaN] println(1 ./ values) end   showextremes()   @show Inf + 2.0 @show Inf + Inf @show Inf - Inf @show Inf * Inf @show Inf / Inf @show Inf * 0 @show 0 == -0 @show NaN == NaN @show NaN === 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.
#Ada
Ada
# # 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.
#Clay
Clay
alias if2(cond1:Bool, cond2:Bool, both, first, second, neither) { var res1 = cond1; var res2 = cond2;   if (res1 and res2) return both; if (res1) return first; if (res2) return second; return neither; }  
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.
#Clojure
Clojure
  (defmacro if2 [[cond1 cond2] bothTrue firstTrue secondTrue else] `(let [cond1# ~cond1 cond2# ~cond2] (if cond1# (if cond2# ~bothTrue ~firstTrue) (if cond2# ~secondTrue ~else))))  
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
#Arturo
Arturo
print 5^3^2 print (5^3)^2 print 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
#AWK
AWK
  # syntax: GAWK -f EXPONENTIATION_ORDER.AWK BEGIN { printf("5^3^2 = %d\n",5^3^2) printf("(5^3)^2 = %d\n",(5^3)^2) printf("5^(3^2) = %d\n",5^(3^2)) exit(0) }  
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#BASIC
BASIC
10 PRINT "5**3**2 = ";5**3**2 20 PRINT "(5**3)**2 = ";(5**3)**2 30 PRINT "5**(3**2) = ";5**(3**2)
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Perl
Perl
use strict; use warnings; use ntheory qw/factorial todigits/;   my $limit = 1500000;   for my $b (9 .. 12) { print "Factorions in base $b:\n"; $_ == factorial($_) and print "$_ " for 0..$b-1;   for my $i (1 .. int $limit/$b) { my $sum; my $prod = $i * $b;   for (reverse todigits($i, $b)) { $sum += factorial($_); $sum = 0 && last if $sum > $prod; }   next if $sum == 0; ($sum + factorial($_) == $prod + $_) and print $prod+$_ . ' ' for 0..$b-1; } print "\n\n"; }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Phix
Phix
with javascript_semantics for base=9 to 12 do printf(1,"The factorions for base %d are: ", base) for i=1 to 1499999 do atom total = 0, j = i, d while j>0 and total<=i do d = remainder(j,base) total += factorial(d) j = floor(j/base) end while if total==i then printf(1,"%d ", i) end if end for printf(1,"\n") end for
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.
#UnixPipes
UnixPipes
yes \ | cat -n | while read a; do ; expr $a % 2 >/dev/null && echo $a ; done
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
#Pop11
Pop11
lvars str; for i from 1 to 100 do if i rem 15 = 0 then 'FizzBuzz' -> str; elseif i rem 3 = 0 then 'Fizz' -> str; elseif i rem 5 = 0 then 'Buzz' -> str; else '' >< i -> str; endif; printf(str, '%s\n'); endfor;
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.
#Clojure
Clojure
ns test-project-intellij.core (:gen-class) (:require [clojure.string :as string]))   (def primes " The following routine produces a infinite sequence of primes (i.e. can be infinite since the evaluation is lazy in that it only produces values as needed). The method is from clojure primes.clj library which produces primes based upon O'Neill's paper: 'The Genuine Sieve of Eratosthenes'.   Produces primes based upon trial division on previously found primes up to (sqrt number), and uses 'wheel' to avoid testing numbers which are divisors of 2, 3, 5, or 7. A full explanation of the method is available at: [https://github.com/stuarthalloway/programming-clojure/pull/12] "   (concat [2 3 5 7] (lazy-seq (let [primes-from ; generates primes by only checking if primes ; numbers which are not divisible by 2, 3, 5, or 7 (fn primes-from [n [f & r]] (if (some #(zero? (rem n %)) (take-while #(<= (* % %) n) primes)) (recur (+ n f) r) (lazy-seq (cons n (primes-from (+ n f) r)))))   ; wheel provides offsets from previous number to insure we are not landing on a divisor of 2, 3, 5, 7 wheel (cycle [2 4 2 4 6 2 6 4 2 4 6 6 2 6 4 2 6 4 6 8 4 2 4 2 4 8 6 4 6 2 4 6 2 6 6 4 2 4 6 2 6 4 2 4 2 10 2 10])] (primes-from 11 wheel)))))   (defn between [lo hi] "Primes between lo and hi value " (->> (take-while #(<= % hi) primes) (filter #(>= % lo)) ))   (println "First twenty:" (take 20 primes))   (println "Between 100 and 150:" (between 100 150))   (println "Number between 7,7700 and 8,000:" (count (between 7700 8000)))   (println "10,000th prime:" (nth primes (dec 10000))) ; decrement by one since nth starts counting from 0     }
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
#FunL
FunL
def fib( 0 ) = 0 fib( 1 ) = 1 fib( n ) = fib( n - 1 ) + fib( n - 2 )
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#PicoLisp
PicoLisp
(de factors (N) (filter '((D) (=0 (% N D))) (range 1 N) ) )
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.   For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it. Bonus Points Run all 5 sample programs at the aforementioned website and output their results.
#Phix
Phix
with javascript_semantics constant NOP = 0b000_00000, -- no operation LDA = 0b001_00000, -- load accumulator, a := memory [xxxxx] STA = 0b010_00000, -- store accumulator, memory [xxxxx] := a ADD = 0b011_00000, -- add, a := a + memory [xxxxx] SUB = 0b100_00000, -- subtract, a := a – memory [xxxxx] BRZ = 0b101_00000, -- branch on zero, if a = 0 then goto xxxxx JMP = 0b110_00000, -- jump, goto xxxxx STP = 0b111_00000, -- stop OP = 0b111_00000, -- operator mask ARG = 0b000_11111 -- memory location (0 based) procedure execute(string name, sequence program) sequence memory = deep_copy(program) integer pc = 1, a = 0 while true do integer ppc = memory[pc], op = and_bitsu(ppc,OP), arg = and_bits(ppc,ARG)+1 pc += 1 switch op do case NOP: break case LDA: a = memory[arg] case STA: memory[arg] = a case ADD: a = and_bitsu(a+memory[arg],#FF) case SUB: a = and_bitsu(a-memory[arg],#FF) case BRZ: if a=0 then pc = arg end if case JMP: pc = arg case STP: printf(1,"%12s: %3d\n",{name,a}) return end switch end while end procedure execute("2+2",{LDA+3, ADD+4, STP, 2,2}) execute("7*8",{LDA+12, ADD+10, STA+12, LDA+11, SUB+13, STA+11, BRZ+8, JMP+0, LDA+12, STP, 8,7,0,1}) execute("fibonacci",{LDA+14, STA+15, ADD+13, STA+14, LDA+15, STA+13, LDA+16, SUB+17, BRZ+11, STA+16, JMP+0, LDA+14, STP, 1,1,0,8,1}) execute("linkedList",{LDA+13, ADD+15, STA+5, ADD+16, STA+7, NOP, STA+14, NOP, BRZ+11, STA+15, JMP+0, LDA+14, STP, LDA+0, 0,28,1,0,0, 0,6,0,2,26,5,20,3,30,1,22,4,24}) execute("prisoner",{NOP, NOP, STP, 0, LDA+3, SUB+29, BRZ+18, LDA+3, STA+29, BRZ+14, LDA+1, ADD+31, STA+1, JMP+2, LDA+0, ADD+31, STA+0, JMP+2, LDA+3, STA+29, LDA+1, ADD+30, ADD+3, STA+1, LDA+0, ADD+30, ADD+3, STA+0, JMP+2, 0, 1, 3}) -- subtractions yielding negative results execute("0-255",{LDA+3,SUB+4,STP, 0,255}) execute("0-1",{LDA+3, SUB+4, STP, 0,1}) -- overflow on addition execute("1+255",{LDA+3, ADD+4, STP, 1, 255})
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
#Kotlin
Kotlin
// version 1.0.5-2   @Suppress("DIVISION_BY_ZERO", "FLOAT_LITERAL_CONFORMS_ZERO")   fun main(args: Array<String>) { val inf = 1.0 / 0.0 val negInf = -1.0 / 0.0 val nan = 0.0 / 0.0 val negZero = -1.0e-325   println("*** Indirect ***\n") println("Infinity  : $inf") println("Negative infinity : $negInf") println("Not a number  : $nan") println("Negative zero  : $negZero")   println("\n*** Direct ***\n") println("Infinity  : ${Double.POSITIVE_INFINITY}") println("Negative infinity : ${Double.NEGATIVE_INFINITY}") println("Not a number  : ${Double.NaN}") println("Negative zero  : ${-0.0}")   println("\n*** Calculations ***\n") println("inf * inf  : ${inf * inf}") println("inf + negInf  : ${inf + negInf}") println("nan / nan  : ${nan / nan}") println("negZero + 0.0  : ${negZero + 0.0}") }
http://rosettacode.org/wiki/Extreme_floating_point_values
Extreme floating point values
The IEEE floating point specification defines certain 'extreme' floating point values such as minus zero, -0.0, a value distinct from plus zero; not a number, NaN; and plus and minus infinity. The task is to use expressions involving other 'normal' floating point values in your language to calculate these, (and maybe other), extreme floating point values in your language and assign them to variables. Print the values of these variables if possible; and show some arithmetic with these values and variables. If your language can directly enter these extreme floating point values then show it. See also   What Every Computer Scientist Should Know About Floating-Point Arithmetic Related tasks   Infinity   Detect division by zero   Literals/Floating point
#Lua
Lua
    local inf=math.huge local minusInf=-math.huge local NaN=0/0 local negativeZeroSorta=-1E-240  
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.
#ALGOL_68
ALGOL 68
# # 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.
#COBOL
COBOL
  EVALUATE EXPRESSION-1 ALSO EXPRESSION-2 WHEN TRUE ALSO TRUE DISPLAY 'Both are true.' WHEN TRUE ALSO FALSE DISPLAY 'Expression 1 is true.' WHEN FALSE ALSO TRUE DISPLAY 'Expression 2 is true.' WHEN OTHER DISPLAY 'Neither is true.' END-EVALUATE  
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
#Bracmat
Bracmat
put$str$("5^3^2: " 5^3^2 "\n(5^3)^2: " (5^3)^2 "\n5^(3^2): " 5^(3^2) \n)
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
#C
C
#include<stdio.h> #include<math.h>   int main() { printf("(5 ^ 3) ^ 2 = %.0f",pow(pow(5,3),2)); printf("\n5 ^ (3 ^ 2) = %.0f",pow(5,pow(3,2)));   return 0; }
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#C.2B.2B
C++
#include <iostream> #include <cmath>   int main() { std::cout << "(5 ^ 3) ^ 2 = " << (uint) pow(pow(5,3), 2) << std::endl; std::cout << "5 ^ (3 ^ 2) = "<< (uint) pow(5, (pow(3, 2)));   return EXIT_SUCCESS; }
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#PureBasic
PureBasic
Declare main()   If OpenConsole() : main() : Else : End 1 : EndIf Input() : End   Procedure main() Define.i n,b,d,i,j,sum Dim fact.i(12)   fact(0)=1 For n=1 To 11 : fact(n)=fact(n-1)*n : Next   For b=9 To 12 PrintN("The factorions for base "+Str(b)+" are: ") For i=1 To 1500000-1 sum=0 : j=i While j>0 d=j%b : sum+fact(d) : j/b Wend If sum=i : Print(Str(i)+" ") : EndIf Next Print(~"\n\n") Next EndProcedure
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Python
Python
fact = [1] # cache factorials from 0 to 11 for n in range(1, 12): fact.append(fact[n-1] * n)   for b in range(9, 12+1): print(f"The factorions for base {b} are:") for i in range(1, 1500000): fact_sum = 0 j = i while j > 0: d = j % b fact_sum += fact[d] j = j//b if fact_sum == i: print(i, end=" ") print("\n")  
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Ursala
Ursala
#import std #import nat   x = <89,36,13,15,41,39,21,3,15,92,16,59,52,88,33,65,54,88,93,43>   #cast %nL   y = (not remainder\2)*~ x
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
#PostScript
PostScript
1 1 100 { /c false def dup 3 mod 0 eq { (Fizz) print /c true def } if dup 5 mod 0 eq { (Buzz) print /c true def } if c {pop}{( ) cvs print} ifelse (\n) print } for
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.
#CoffeeScript
CoffeeScript
  primes = () -> yield 2 yield 3   sieve = ([] for i in [1..3]) sieve[0].push 3 [r, s] = [3, 9] pos = 1 n = 5 loop isPrime = true if sieve[pos].length > 0 # this entry has a list of factors isPrime = false sieve[(pos + m) % sieve.length].push m for m in sieve[pos] sieve[pos] = []   if n is s # n is the next square if isPrime isPrime = false # r divides n, so not actually prime sieve[(pos + r) % sieve.length].push r # however, r is prime r += 2 s = r*r   yield n if isPrime n += 2 pos += 1 if pos is sieve.length sieve.push [] # array size must exceed largest prime found sieve.push [] # adding two entries keeps size = O(sqrt n) pos = 0   undefined # prevent CoffeeScript from aggregating values   module.exports = { primes }  
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
#Futhark
Futhark
  fun main(n: int): int = loop((a,b) = (0,1)) = for _i < n do (b, a + b) in 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
#PILOT
PILOT
T  :Enter a number. A  :#n C  :factor = 1 T  :The factors of #n are: *Loop C  :remainder = n % factor T ( remainder = 0 )  :#factor J ( factor = n )  :*Finished C  :factor = factor + 1 J  :*Loop *Finished END:
http://rosettacode.org/wiki/Execute_Computer/Zero
Execute Computer/Zero
Execute Computer/Zero is an implementation of Computer/zero Assembly. Other implementations of Computer/zero Assembly. Task Create a Computer/zero Assembly emulator. You may consider this webpage as a reference implementation. Output the results of the sample programs "2+2" and "7*8" found there.   The virtual machine "bytecode" needs to be able to modify itself (or at least act as though it can) while the virtual machine is running, to be consistent with the reference implementation.   For output, it is sufficient to have the implementation of the STP opcode return the accumulator to your actual language, and then use your standard printing routines to output it. Bonus Points Run all 5 sample programs at the aforementioned website and output their results.
#Python
Python
"""Computer/zero Assembly emulator. Requires Python >= 3.7"""   import re   from typing import Dict from typing import Iterable from typing import List from typing import NamedTuple from typing import Optional from typing import Tuple     NOP = 0b000 LDA = 0b001 STA = 0b010 ADD = 0b011 SUB = 0b100 BRZ = 0b101 JMP = 0b110 STP = 0b111   OPCODES = { "NOP": NOP, "LDA": LDA, "STA": STA, "ADD": ADD, "SUB": SUB, "BRZ": BRZ, "JMP": JMP, "STP": STP, }   RE_INSTRUCTION = re.compile( r"\s*" r"(?:(?P<label>\w+):)?" r"\s*" rf"(?P<opcode>{'|'.join(OPCODES)})?" r"\s*" r"(?P<argument>\w+)?" r"\s*" r"(?:;(?P<comment>[\w\s]+))?" )     class AssemblySyntaxError(Exception): pass     class Instruction(NamedTuple): label: Optional[str] opcode: Optional[str] argument: Optional[str] comment: Optional[str]     def parse(assembly: str) -> Tuple[List[Instruction], Dict[str, int]]: instructions: List[Instruction] = [] labels: Dict[str, int] = {} linenum: int = 0   for line in assembly.split("\n"): match = RE_INSTRUCTION.match(line)   if not match: raise AssemblySyntaxError(f"{line}: {linenum}")   instructions.append(Instruction(**match.groupdict())) label = match.group(1) if label: labels[label] = linenum   linenum += 1   return instructions, labels     def compile(instructions: List[Instruction], labels: Dict[str, int]) -> Iterable[int]: for instruction in instructions: if instruction.argument is None: argument = 0 elif instruction.argument.isnumeric(): argument = int(instruction.argument) else: argument = labels[instruction.argument]   if instruction.opcode: yield OPCODES[instruction.opcode] << 5 | argument else: yield argument     def run(bytecode: bytes) -> int: accumulator = 0 program_counter = 0 memory = list(bytecode)[:32] + [0 for _ in range(32 - len(bytecode))]   while program_counter < 32: operation = memory[program_counter] >> 5 argument = memory[program_counter] & 0b11111 program_counter += 1   if operation == NOP: continue elif operation == LDA: accumulator = memory[argument] elif operation == STA: memory[argument] = accumulator elif operation == ADD: accumulator = (accumulator + memory[argument]) % 256 elif operation == SUB: accumulator = (accumulator - memory[argument]) % 256 elif operation == BRZ: if accumulator == 0: program_counter = argument elif operation == JMP: program_counter = argument elif operation == STP: break else: raise Exception(f"error: {operation} {argument}")   return accumulator     SAMPLES = [ """\ LDA x ADD y  ; accumulator = x + y STP x: 2 y: 2 """, """\ loop: LDA prodt ADD x STA prodt LDA y SUB one STA y BRZ done JMP loop done: LDA prodt  ; to display it STP x: 8 y: 7 prodt: 0 one: 1 """, """\ loop: LDA n STA temp ADD m STA n LDA temp STA m LDA count SUB one BRZ done STA count JMP loop done: LDA n  ; to display it STP m: 1 n: 1 temp: 0 count: 8  ; valid range: 1-11 one: 1 """, """\ start: LDA load ADD car  ; head of list STA ldcar ADD one STA ldcdr  ; next CONS cell ldcar: NOP STA value ldcdr: NOP BRZ done  ; 0 stands for NIL STA car JMP start done: LDA value  ; CAR of last CONS STP load: LDA 0 value: 0 car: 28 one: 1  ; order of CONS cells  ; in memory  ; does not matter 6 0  ; 0 stands for NIL 2  ; (CADR ls) 26  ; (CDDR ls) -- etc. 5 20 3 30 1  ; value of (CAR ls) 22  ; points to (CDR ls) 4 24 """, """\ p: 0  ; NOP in first round c: 0 start: STP  ; wait for p's move pmove: NOP LDA pmove SUB cmove BRZ same LDA pmove STA cmove  ; tit for tat BRZ cdeft LDA c  ; p defected, c did not ADD three STA c JMP start cdeft: LDA p ADD three STA p JMP start same: LDA pmove STA cmove  ; tit for tat LDA p ADD one ADD pmove STA p LDA c ADD one ADD pmove STA c JMP start cmove: 0  ; co-operate initially one: 1 three: 3 """, """\ LDA 3 SUB 4 STP 0 0 255 """, """\ LDA 3 SUB 4 STP 0 0 1 """, """\ LDA 3 ADD 4 STP 0 1 255 """, ]     def main() -> None: for sample in SAMPLES: instructions, labels = parse(sample) bytecode = bytes(compile(instructions, labels)) result = run(bytecode) print(result)     if __name__ == "__main__": main()  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Column@{ReleaseHold[ Function[expression, Row@{HoldForm@InputForm@expression, " = ", Quiet@expression}, HoldAll] /@ Hold[1./0., 0./0., Limit[-Log[x], x -> 0], Limit[Log[x], x -> 0], Infinity + 1, Infinity + Infinity, 2 Infinity, Infinity - Infinity, 0 Infinity, ComplexInfinity + 1, ComplexInfinity + ComplexInfinity, 2 ComplexInfinity, 0 ComplexInfinity, Indeterminate + 1, 0 Indeterminate]]}
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
#Maxima
Maxima
USER>write 3e145 30000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 USER>write 3e146 <MAXNUMBER>
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.
#AutoHotkey
AutoHotkey
# # 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.
#Common_Lisp
Common Lisp
(defmacro if2 (cond1 cond2 both first second &rest neither) (let ((res1 (gensym)) (res2 (gensym))) `(let ((,res1 ,cond1) (,res2 ,cond2)) (cond ((and ,res1 ,res2) ,both) (,res1 ,first) (,res2 ,second) (t ,@neither)))))
http://rosettacode.org/wiki/Exponentiation_order
Exponentiation order
This task will demonstrate the order of exponentiation   (xy)   when there are multiple exponents. (Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Task requirements Show the result of a language's evaluation of multiple exponentiation (either as an integer or floating point). If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. Using whatever operator or syntax your language supports (if any), show the results in three lines (with identification):   5**3**2   (5**3)**2   5**(3**2) If there are other methods (or formats) of multiple exponentiations, show them as well. See also MathWorld entry:   exponentiation Related tasks   exponentiation operator   arbitrary-precision integers (included)   Exponentiation with infix operators in (or operating on) the base
#C.23
C#
using System;   namespace exponents { class Program { static void Main(string[] args) { /* * Like C, C# does not have an exponent operator. * Exponentiation is done via Math.Pow, which * only takes two arguments */ Console.WriteLine(Math.Pow(Math.Pow(5, 3), 2)); Console.WriteLine(Math.Pow(5, Math.Pow(3, 2))); Console.Read(); }   } }  
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
#Clojure
Clojure
(use 'clojure.math.numeric-tower) ;; (5**3)**2 (expt (expt 5 3) 2) ; => 15625   ;; 5**(3**2) (expt 5 (expt 3 2)) ; => 1953125   ;; (5**3)**2 alternative: use reduce (reduce expt [5 3 2]) ; => 15625   ;; 5**(3**2) alternative: evaluating right-to-left with reduce requires a small modification (defn rreduce [f coll] (reduce #(f %2 %) (reverse coll))) (rreduce expt [5 3 2]) ; => 1953125
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Quackery
Quackery
[ table ] is results ( n --> s ) 4 times [ ' [ stack [ ] ] copy ' results put ]   [ results dup take rot join swap put ] is addresult ( n n --> )   [ table 9 10 11 12 ] is radix ( n --> n )   [ table 1 ] is ! ( n --> n ) 1 11 times [ i^ 1+ * dup ' ! put ] drop   [ dip dup 0 temp put [ tuck /mod ! temp tally swap over 0 = until ] 2drop temp take = ] is factorion ( n n --> b )   1500000 times [ i^ 4 times [ dup i^ radix factorion if [ dup i^ addresult ] ] drop ] 4 times [ say "Factorions for base " i^ radix echo say ": " i^ results take echo cr ]
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Racket
Racket
#lang racket   (define fact (curry list-ref (for/fold ([result (list 1)] #:result (reverse result)) ([x (in-range 1 20)]) (cons (* x (first result)) result))))   (for ([b (in-range 9 13)]) (printf "The factorions for base ~a are:\n" b) (for ([i (in-range 1 1500000)]) (let loop ([sum 0] [n i]) (cond [(positive? n) (loop (+ sum (fact (modulo n b))) (quotient n b))] [(= sum i) (printf "~a " i)]))) (newline))
http://rosettacode.org/wiki/Factorions
Factorions
Definition A factorion is a natural number that equals the sum of the factorials of its digits. Example 145   is a factorion in base 10 because: 1! + 4! + 5! = 1 + 24 + 120 = 145 It can be shown (see talk page) that no factorion in base 10 can exceed   1,499,999. Task Write a program in your language to demonstrate, by calculating and printing out the factorions, that:   There are   3   factorions in base   9   There are   4   factorions in base 10   There are   5   factorions in base 11   There are   2   factorions in base 12     (up to the same upper bound as for base 10) See also Wikipedia article OEIS:A014080 - Factorions in base 10 OEIS:A193163 - Factorions in base n
#Raku
Raku
constant @factorial = 1, |[\*] 1..*;   constant $limit = 1500000;   constant $bases = 9 .. 12;   my @result;   $bases.map: -> $base {   @result[$base] = "\nFactorions in base $base:\n1 2";   sink (1 .. $limit div $base).map: -> $i { my $product = $i * $base; my $partial;   for $i.polymod($base xx *) { $partial += @factorial[$_]; last if $partial > $product }   next if $partial > $product;   my $sum;   for ^$base { last if ($sum = $partial + @factorial[$_]) > $product + $_; @result[$base] ~= " $sum" and last if $sum == $product + $_ } } }   .say for @result[$bases];
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.
#V
V
[even? dup 2 / >int 2 * - zero?].   [1 2 3 4 5 6 7 8 9] [even?] filter =[2 4 6 8]
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
#Potion
Potion
  1 to 100 (a): if (a % 15 == 0): 'FizzBuzz'. elsif (a % 3 == 0): 'Fizz'. elsif (a % 5 == 0): 'Buzz'. else: a. string print "\n" print.
http://rosettacode.org/wiki/Extensible_prime_generator
Extensible prime generator
Task Write a generator of prime numbers, in order, that will automatically adjust to accommodate the generation of any reasonably high prime. The routine should demonstrably rely on either: Being based on an open-ended counter set to count without upper limit other than system or programming language limits. In this case, explain where this counter is in the code. Being based on a limit that is extended automatically. In this case, choose a small limit that ensures the limit will be passed when generating some of the values to be asked for below. If other methods of creating an extensible prime generator are used, the algorithm's means of extensibility/lack of limits should be stated. The routine should be used to: Show the first twenty primes. Show the primes between 100 and 150. Show the number of primes between 7,700 and 8,000. Show the 10,000th prime. Show output on this page. Note: You may reference code already on this site if it is written to be imported/included, then only the code necessary for import and the performance of this task need be shown. (It is also important to leave a forward link on the referenced tasks entry so that later editors know that the code is used for multiple tasks). Note 2: If a languages in-built prime generator is extensible or is guaranteed to generate primes up to a system limit, (231 or memory overflow for example), then this may be used as long as an explanation of the limits of the prime generator is also given. (Which may include a link to/excerpt from, language documentation). Note 3:The task is written so it may be useful in solving the task   Emirp primes   as well as others (depending on its efficiency). Reference Prime Numbers. Website with large count of primes.
#D
D
void main() { import std.stdio, std.range, std.algorithm, sieve_of_eratosthenes3;   Prime prime; writeln("First twenty primes:\n", 20.iota.map!prime); writeln("Primes primes between 100 and 150:\n", uint.max.iota.map!prime.until!q{a > 150}.filter!q{a > 99}); writeln("Number of primes between 7,700 and 8,000: ", uint.max.iota.map!prime.until!q{a > 8_000} .filter!q{a > 7_699}.walkLength); writeln("10,000th prime: ", prime(9_999)); }
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
#FutureBasic
FutureBasic
window 1, @"Fibonacci Sequence", (0,0,480,620)   local fn Fibonacci( n as long ) as long static long s1 static long s2 long temp   if ( n < 2 ) s1 = n exit fn else temp = s1 + s2 s2 = s1 s1 = temp exit fn end if end fn = s1   long i CFTimeInterval t   t = fn CACurrentMediaTime   for i = 0 to 40 print i;@".\t";fn Fibonacci(i) next i   print : printf @"Compute time: %.3f ms",(fn CACurrentMediaTime-t)*1000   HandleEvents