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/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.
#PowerShell
PowerShell
$array = -15..37 $array | Where-Object { $_ % 2 -eq 0 }
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Never
Never
func fizz_buzz() -> int { var i = 1;   for (i = 1; i <= 100; i = i + 1) { /* if (i % 15 == 0) */ if (i % 3 == 0 && i % 5 == 0) { prints("Fizz Buzz\n") } else if (i % 3 == 0) { prints("Fizz\n") } else if (i % 5 == 0) { prints("Buzz\n") } else { prints(i + "\n") } };   0 }   func main() -> int { fizz_buzz();   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
#DWScript
DWScript
function fib(N : Integer) : Integer; begin if N < 2 then Result := 1 else Result := fib(N-2) + fib(N-1); 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
#LFE
LFE
  (defun factors (n) (list-comp ((<- i (when (== 0 (rem n i))) (lists:seq 1 (trunc (/ n 2))))) i))  
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.
#Prolog
Prolog
evens(D, Es) :- findall(E, (member(E, D), E mod 2 =:= 0), Es).
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
#NewLISP
NewLISP
(dotimes (i 100) (println (cond ((= 0 (% i 15)) "FizzBuzz") ((= 0 (% i 3)) "Fizz") ((= 0 (% i 5)) "Buzz") ('t i))))
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
#Dyalect
Dyalect
func fib(n) { if n < 2 { return n } else { return fib(n - 1) + fib(n - 2) } }   print(fib(30))
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
#Liberty_BASIC
Liberty BASIC
num = 10677106534462215678539721403561279 maxnFactors = 1000 dim primeFactors(maxnFactors), nPrimeFactors(maxnFactors) global nDifferentPrimeNumbersFound, nFactors, iFactor     print "Start finding all factors of ";num; ":"   nDifferentPrimeNumbersFound=0 dummy = factorize(num,2) nFactors = showPrimeFactors(num) dim factors(nFactors) dummy = generateFactors(1,1) sort factors(), 0, nFactors-1 for i=1 to nFactors print i;" ";factors(i-1) next i   print "done"   wait     function factorize(iNum,offset) factorFound=0 i = offset do if (iNum MOD i)=0 _ then if primeFactors(nDifferentPrimeNumbersFound) = i _ then nPrimeFactors(nDifferentPrimeNumbersFound) = nPrimeFactors(nDifferentPrimeNumbersFound) + 1 else nDifferentPrimeNumbersFound = nDifferentPrimeNumbersFound + 1 primeFactors(nDifferentPrimeNumbersFound) = i nPrimeFactors(nDifferentPrimeNumbersFound) = 1 end if if iNum/i<>1 then dummy = factorize(iNum/i,i) factorFound=1 end if i=i+1 loop while factorFound=0 and i<=sqr(iNum) if factorFound=0 _ then nDifferentPrimeNumbersFound = nDifferentPrimeNumbersFound + 1 primeFactors(nDifferentPrimeNumbersFound) = iNum nPrimeFactors(nDifferentPrimeNumbersFound) = 1 end if end function     function showPrimeFactors(iNum) showPrimeFactors=1 print iNum;" = "; for i=1 to nDifferentPrimeNumbersFound print primeFactors(i);"^";nPrimeFactors(i); if i<nDifferentPrimeNumbersFound then print " * "; else print "" showPrimeFactors = showPrimeFactors*(nPrimeFactors(i)+1) next i end function     function generateFactors(product,pIndex) if pIndex>nDifferentPrimeNumbersFound _ then factors(iFactor) = product iFactor=iFactor+1 else for i=0 to nPrimeFactors(pIndex) dummy = generateFactors(product*primeFactors(pIndex)^i,pIndex+1) next i end if end function
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.
#PureBasic
PureBasic
Dim Tal.i(9) Dim Evens.i(0)   ;- Set up an array with random numbers For i=0 To ArraySize(Tal()) Tal(i)=Random(100) Next   ;- Pick out all Even and save them j=0 For i=0 To ArraySize(Tal()) If Tal(i)%2=0 ReDim Evens(j) ; extend the Array as we find new Even's Evens(j)=tal(i) j+1 EndIf Next   ;- Display the result PrintN("List of Randoms") For i=0 To ArraySize(Tal()) Print(Str(Tal(i))+" ") Next PrintN(#CRLF$+#CRLF$+"List of Even(s)") For i=0 To ArraySize(Evens()) Print(Str(Evens(i))+" ") Next
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
#NewtonScript
NewtonScript
for i := 1 to 100 do begin if i mod 15 = 0 then print("FizzBuzz") else if i mod 3 = 0 then print("Fizz") else if i mod 5 = 0 then print("Buzz") else print(i); print("\n") end
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#E
E
def fib(n) { var s := [0, 1] for _ in 0..!n { def [a, b] := s s := [b, a+b] } return s[0] }
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
#Lingo
Lingo
on factors(n) res = [1] repeat with i = 2 to n/2 if n mod i = 0 then res.add(i) end repeat res.add(n) return res 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.
#Python
Python
values = range(10) evens = [x for x in values if not x & 1] ievens = (x for x in values if not x & 1) # lazy # alternately but less idiomatic: evens = filter(lambda x: not x & 1, values)
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
#Nickle
Nickle
/* Fizzbuzz in nickle */   void function fizzbuzz(size) { for (int i = 1; i < size; i++) { if (i % 15 == 0) { printf("Fizzbuzz\n"); } else if (i % 5 == 0) { printf("Buzz\n"); } else if (i % 3 == 0) { printf("Fizz\n"); } else { printf("%i\n", i); } } }   fizzbuzz(1000);
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
#EasyLang
EasyLang
func fib n . res . if n < 2 res = n . prev = 0 val = 1 for _ range n - 1 res = prev + val prev = val val = res . . call fib 36 r print r
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
#Logo
Logo
to factors :n output filter [equal? 0 modulo :n ?] iseq 1 :n end   show factors 28  ; [1 2 4 7 14 28]
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.
#Quackery
Quackery
[ [] ]'[ rot witheach [ tuck over do iff [ dip [ nested join ] ] else nip ] drop ] is only ( [ --> [ )   [ 1 & not ] is even ( n --> b )   [] 10 times [ 10 random join ] say "Ten arbitrary digits: " dup echo cr say "Only the even digits: " only even echo cr
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
#Nim
Nim
for i in 1..100: if i mod 15 == 0: echo("FizzBuzz") elif i mod 3 == 0: echo("Fizz") elif i mod 5 == 0: echo("Buzz") else: echo(i)
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
#EchoLisp
EchoLisp
  (define (fib n) (if (< n 2) n (+ (fib (- n 2)) (fib (1- n)))))   (remember 'fib #(0 1))   (for ((i 12)) (write (fib i))) 0 1 1 2 3 5 8 13 21 34 55 89  
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
#Lua
Lua
function Factors( n ) local f = {}   for i = 1, n/2 do if n % i == 0 then f[#f+1] = i end end f[#f+1] = n   return f 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.
#Q
Q
x where 0=x mod 2
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Nix
Nix
with (import <nixpkgs> { }).lib; with builtins; let fizzbuzz = { x ? 1 }: '' ${if (mod x 15 == 0) then "FizzBuzz" else if (mod x 3 == 0) then "Fizz" else if (mod x 5 == 0) then "Buzz" else (toString x)} '' + (if (x < 100) then fizzbuzz { x = x + 1; } else ""); in fizzbuzz { }
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
#ECL
ECL
//Calculates Fibonacci sequence up to n steps using Binet's closed form solution     FibFunction(UNSIGNED2 n) := FUNCTION REAL Sqrt5 := Sqrt(5); REAL Phi := (1+Sqrt(5))/2; REAL Phi_Inv := 1/Phi; UNSIGNED FibValue := ROUND( ( POWER(Phi,n)-POWER(Phi_Inv,n) ) /Sqrt5); RETURN FibValue; END;   FibSeries(UNSIGNED2 n) := FUNCTION   Fib_Layout := RECORD UNSIGNED5 FibNum; UNSIGNED5 FibValue; END;   FibSeq := DATASET(n+1, TRANSFORM ( Fib_Layout , SELF.FibNum := COUNTER-1 , SELF.FibValue := IF(SELF.FibNum<2,SELF.FibNum, FibFunction(SELF.FibNum) ) ) );   RETURN FibSeq;   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
#M2000_Interpreter
M2000 Interpreter
  \\ Factors of an integer \\ For act as BASIC's FOR (if N<1 no loop start) FORM 60,40 SET SWITCHES "+FOR" MODULE LikeBasic { 10 INPUT N% 20 FOR I%=1 TO N% 30 IF N%/I%=INT(N%/I%) THEN PRINT I%, 40 NEXT I% 50 PRINT } CALL LikeBasic SET SWITCHES "-FOR" MODULE LikeM2000 { DEF DECIMAL N%, I% INPUT N% IF N%<1 THEN EXIT FOR I%=1 TO N% { IF N% MOD I%=0 THEN PRINT I%, } PRINT } CALL LikeM2000    
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.
#R
R
a <- 1:100 evennums <- a[ a%%2 == 0 ] print(evennums)
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
#Oberon-2
Oberon-2
MODULE FizzBuzz;   IMPORT Out;   VAR i: INTEGER;   BEGIN FOR i := 1 TO 100 DO IF i MOD 15 = 0 THEN Out.String("FizzBuzz") ELSIF i MOD 5 = 0 THEN Out.String("Buzz") ELSIF i MOD 3 = 0 THEN Out.String("Fizz") ELSE Out.Int(i,0) END; Out.Ln END END FizzBuzz.
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
#EDSAC_order_code
EDSAC order code
[ Fibonacci sequence ==================   A program for the EDSAC   Calculates the nth Fibonacci number and displays it at the top of storage tank 3   The default value of n is 10   To calculate other Fibonacci numbers, set the starting value of the count to n-2   Works with Initial Orders 2 ]     T56K [ set load point ] GK [ set theta ]   [ Orders ]   [ 0 ] T20@ [ a = 0 ] A17@ [ a += y ] U18@ [ temp = a ] A16@ [ a += x ] T17@ [ y = a; a = 0 ] A18@ [ a += temp ] T16@ [ x = a; a = 0 ]   A19@ [ a = count ] S15@ [ a -= 1 ] U19@ [ count = a ] E@ [ if a>=0 go to θ ]   T20@ [ a = 0 ] A17@ [ a += y ] T96F [ C(96) = a; a = 0]   ZF [ halt ]   [ Data ]   [ 15 ] P0D [ const: 1 ] [ 16 ] P0F [ var: x = 0 ] [ 17 ] P0D [ var: y = 1 ] [ 18 ] P0F [ var: temp = 0 ] [ 19 ] P4F [ var: count = 8 ] [ 20 ] P0F [ used to clear a ]   EZPF [ begin execution ]
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
#Maple
Maple
  numtheory:-divisors(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.
#Racket
Racket
  -> (filter even? '(0 1 2 3 4 5 6 7 8 9)) '(0 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
#Objeck
Objeck
bundle Default { class Fizz { function : Main(args : String[]) ~ Nil { for(i := 0; i <= 100; i += 1;) { if(i % 15 = 0) { "FizzBuzz"->PrintLine(); } else if(i % 3 = 0) { "Fizz"->PrintLine(); } else if(i % 5 = 0) { "Buzz"->PrintLine(); } else { i->PrintLine(); }; }; } } }
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
#Eiffel
Eiffel
  class APPLICATION   create make   feature   fibonacci (n: INTEGER): INTEGER require non_negative: n >= 0 local i, n2, n1, tmp: INTEGER do n2 := 0 n1 := 1 from i := 1 until i >= n loop tmp := n1 n1 := n2 + n1 n2 := tmp i := i + 1 end Result := n1 if n = 0 then Result := 0 end end   feature {NONE} -- Initialization   make -- Run application. do print (fibonacci (0)) print (" ") print (fibonacci (1)) print (" ") print (fibonacci (2)) print (" ") print (fibonacci (3)) print (" ") print (fibonacci (4)) print ("%N") end   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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
Factorize[n_Integer] := Divisors[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.
#Raku
Raku
my @a = 1..6; my @even = grep * %% 2, @a;
http://rosettacode.org/wiki/FizzBuzz
FizzBuzz
Task Write a program that prints the integers from   1   to   100   (inclusive). But:   for multiples of three,   print   Fizz     (instead of the number)   for multiples of five,   print   Buzz     (instead of the number)   for multiples of both three and five,   print   FizzBuzz     (instead of the number) The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy. Also see   (a blog)   dont-overthink-fizzbuzz   (a blog)   fizzbuzz-the-programmers-stairway-to-heaven
#Objective-C
Objective-C
// FizzBuzz in Objective-C #import <Foundation/Foundation.h>   int main(int argc, char* argv[]) { for (NSInteger i=1; I <= 101; i++) { if (i % 15 == 0) { NSLog(@"FizzBuzz\n"); } else if (i % 3 == 0) { NSLog(@"Fizz\n"); } else if (i % 5 == 0) { NSLog(@"Buzz\n"); } else { NSLog(@"%li\n", i); } } }
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
#Ela
Ela
fib = fib' 0 1 where fib' a b 0 = a fib' a b n = fib' b (a + b) (n - 1)
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#MATLAB_.2F_Octave
MATLAB / Octave
function fact(n); f = factor(n); % prime decomposition K = dec2bin(0:2^length(f)-1)-'0'; % generate all possible permutations F = ones(1,2^length(f)); for k = 1:size(K) F(k) = prod(f(~K(k,:))); % and compute products end; F = unique(F); % eliminate duplicates printf('There are %i factors for %i.\n',length(F),n); disp(F); 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.
#Raven
Raven
[ 0 1 2 3 4 5 6 7 8 9 ] as nums group nums each dup 1 & if drop list as evens
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
#OCaml
OCaml
let fizzbuzz i = match i mod 3, i mod 5 with 0, 0 -> "FizzBuzz" | 0, _ -> "Fizz" | _, 0 -> "Buzz" | _ -> string_of_int i   let _ = for i = 1 to 100 do print_endline (fizzbuzz i) done
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
#Elena
Elena
import extensions;   fibu(n) { int[] ac := new int[]{ 0,1 }; if (n < 2) { ^ ac[n] } else { for(int i := 2, i <= n, i+=1) { int t := ac[1]; ac[1] := ac[0] + ac[1]; ac[0] := t };   ^ ac[1] } }   public program() { for(int i := 0, i <= 10, i+=1) { console.printLine(fibu(i)) } }
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
#Maxima
Maxima
(%i96) divisors(100); (%o96) {1,2,4,5,10,20,25,50,100}
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.
#REBOL
REBOL
a: [] repeat i 100 [append a i] ; Build and load array.   evens: [] repeat element a [if even? element [append evens element]]   print mold evens
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
#Octave
Octave
for i = 1:100 if ( mod(i,15) == 0 ) disp("FizzBuzz"); elseif ( mod(i, 3) == 0 ) disp("Fizz") elseif ( mod(i, 5) == 0 ) disp("Buzz") else disp(i) endif endfor
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
#Elixir
Elixir
defmodule Fibonacci do def fib(0), do: 0 def fib(1), do: 1 def fib(n), do: fib(0, 1, n-2)   def fib(_, prv, -1), do: prv def fib(prvprv, prv, n) do next = prv + prvprv fib(prv, next, n-1) end end   IO.inspect Enum.map(0..10, fn i-> Fibonacci.fib(i) 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
#MAXScript
MAXScript
  fn factors n = ( return (for i = 1 to n+1 where mod n i == 0 collect i) )  
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.
#Red
Red
Red [] orig: [] repeat i 10 [append orig i] ?? orig cpy: [] forall orig [if even? orig/1 [append cpy orig/1]] ;; or - because we know each second element is even :- ) ;; cpy: extract next orig 2 ?? cpy remove-each ele orig [odd? ele]  ;; destructive ?? orig  
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
#Oforth
Oforth
: fizzbuzz | i | 100 loop: i [ null i 3 mod ifZero: [ "Fizz" + ] i 5 mod ifZero: [ "Buzz" + ] dup ifNull: [ drop i ] . ] ;
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
#Elm
Elm
fibonacci : Int -> Int fibonacci n = if n < 2 then n else fibonacci(n - 2) + fibonacci(n - 1)
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Mercury
Mercury
:- module fac.   :- interface. :- import_module io. :- pred main(io::di, io::uo) is det.   :- implementation. :- import_module float, int, list, math, string.   main(!IO) :- io.command_line_arguments(Args, !IO), list.filter_map(string.to_int, Args, CleanArgs), list.foldl((pred(Arg::in, !.IO::di, !:IO::uo) is det :- factor(Arg, X), io.format("factor(%d, [", [i(Arg)], !IO), io.write_list(X, ",", io.write_int, !IO), io.write_string("])\n", !IO) ), CleanArgs, !IO).   :- pred factor(int::in, list(int)::out) is det. factor(N, Factors) :- Limit = float.truncate_to_int(math.sqrt(float(N))), factor(N, 2, Limit, [], Unsorted), list.sort_and_remove_dups([1, N | Unsorted], Factors).   :- pred factor(int, int, int, list(int), list(int)). :- mode factor(in, in, in, in, out) is det. factor(N, X, Limit, !Accumulator) :- ( if X > Limit then true else ( if 0 = N mod X then !:Accumulator = [X, N / X | !.Accumulator] else true ), factor(N, X + 1, Limit, !Accumulator) ).   :- func factor(int) = list(int). %:- mode factor(in) = out is det. factor(N) = Factors :- factor(N, Factors).   :- end_module fac.
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.
#REXX
REXX
/*REXX program selects all even numbers from an array and puts them ──► a new array.*/ parse arg N seed . /*obtain optional arguments from the CL*/ if N=='' | N=="," then N= 50 /*Not specified? Then use the default.*/ if datatype(seed,'W') then call random ,,seed /*use the RANDOM seed for repeatability*/ old.= /*the OLD array, all are null so far. */ new.= /* " NEW " " " " " " */ do i=1 for N /*generate N random numbers ──► OLD */ old.i= random(1, 99999) /*generate random number 1 ──► 99999*/ end /*i*/ #= 0 /*number of elements in NEW (so far).*/ do j=1 for N /*process the elements of the OLD array*/ if old.j//2 \== 0 then iterate /*if element isn't even, then skip it.*/ #= # + 1 /*bump the number of NEW elements. */ new.#= old.j /*assign the number to the NEW array.*/ end /*j*/   do k=1 for # /*display all the NEW numbers. */ say right('new.'k, 20) "=" right(new.k, 9) /*display a line (an array element). */ end /*k*/ /*stick a fork in it, we're all 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
#Ol
Ol
  (for-each (lambda (x) (print (cond ((and (zero? (mod x 3)) (zero? (mod x 5))) "FizzBuzz") ((zero? (mod x 3)) "Fizz") ((zero? (mod x 5)) "Buzz") (else x)))) (iota 100))  
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
#Emacs_Lisp
Emacs Lisp
(defun fib (n a b c) (cond ((< c n) (fib n b (+ a b) (+ 1 c))) ((= c n) b) (t a)))   (defun fibonacci (n) (if (< n 2) n (fib n 0 1 1)))
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#min
min
(mod 0 ==) :divisor? (() 0 shorten) :new (new (over swons 'pred dip) pick times nip) :iota   (  :n n sqrt int iota  ; Only consider numbers up to sqrt(n). (n swap divisor?) filter =f1 f1 (n swap div) map reverse =f2  ; "Mirror" the list of divisors at sqrt(n). (f1 last f2 first ==) (f2 rest #f2) when  ; Handle perfect squares. f1 f2 concat ) :factors   24 factors puts! 9 factors puts! 11 factors puts!
http://rosettacode.org/wiki/Filter
Filter
Task Select certain elements from an Array into a new Array in a generic way. To demonstrate, select all even numbers from an Array. As an option, give a second solution which filters destructively, by modifying the original Array rather than creating a new Array.
#Ring
Ring
  aList = [1, 2, 3, 4, 5, 6] bArray = list(3) see evenSelect(aList)   func evenSelect aArray i = 0 for n = 1 to len(aArray) if (aArray[n] % 2) = 0 i = i + 1 bArray[i] = aArray[n] ok next return bArray  
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
#OOC
OOC
fizz: func (n: Int) -> Bool { if(n % 3 == 0) { printf("Fizz") return true } return false }   buzz: func (n: Int) -> Bool { if(n % 5 == 0) { printf("Buzz") return true } return false }   main: func { for(n in 1..100) { fizz:= fizz(n) buzz:= buzz(n) fizz || buzz || printf("%d", n) println() } }
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
#Erlang
Erlang
  -module(fib). -export([fib/1]).   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
#MiniScript
MiniScript
factors = function(n) result = [1] for i in range(2, n) if n % i == 0 then result.push i end for return result end function   while true n = val(input("Number to factor (0 to quit)? ")) if n <= 0 then break print factors(n) end while
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.
#Ruby
Ruby
# Enumerable#select returns a new array. ary = [1, 2, 3, 4, 5, 6] even_ary = ary.select {|elem| elem.even?} p even_ary # => [2, 4, 6]   # Enumerable#select also works with Range. range = 1..6 even_ary = range.select {|elem| elem.even?} p even_ary # => [2, 4, 6]
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
#Order
Order
#include <order/interpreter.h>   // Get FB for one number #define ORDER_PP_DEF_8fizzbuzz ORDER_PP_FN( \ 8fn(8N, \ 8let((8F, 8fn(8N, 8G, \ 8is_0(8remainder(8N, 8G)))), \ 8cond((8ap(8F, 8N, 15), 8quote(fizzbuzz)) \ (8ap(8F, 8N, 3), 8quote(fizz)) \ (8ap(8F, 8N, 5), 8quote(buzz)) \ (8else, 8N)))) )   // Print E followed by a comma (composable, 8print is not a function) #define ORDER_PP_DEF_8print_el ORDER_PP_FN( \ 8fn(8E, 8print(8E 8comma)) )   ORDER_PP( // foreach instead of map, to print but return nothing 8seq_for_each(8compose(8print_el, 8fizzbuzz), 8seq_iota(1, 100)) )
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
#ERRE
ERRE
!------------------------------------------- ! derived from my book "PROGRAMMARE IN ERRE" ! iterative solution !-------------------------------------------   PROGRAM FIBONACCI   !$DOUBLE   !VAR F1#,F2#,TEMP#,COUNT%,N%   BEGIN  !main INPUT("Number",N%) F1=0 F2=1 REPEAT TEMP=F2 F2=F1+F2 F1=TEMP COUNT%=COUNT%+1 UNTIL COUNT%=N% PRINT("FIB(";N%;")=";F2)    ! Obviously a FOR loop or a WHILE loop can  ! be used to solve this problem   END PROGRAM  
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
#.D0.9C.D0.9A-61.2F52
МК-61/52
П9 1 П6 КИП6 ИП9 ИП6 / П8 ^ [x] x#0 21 - x=0 03 ИП6 С/П ИП8 П9 БП 04 1 С/П БП 21
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.
#Run_BASIC
Run BASIC
dim a1(100) count = 100 for i = 1 to 100 a1(i) = int(rnd(0)*100)+1 count = count - (a1(i) mod 2) next   'dim the extract and fill it dim a2(count) for i = 1 to 100 if not(a1(i) mod 2) then n = n+1 a2(n) = a1(i) end if next   for i = 1 to count print a2(i) next
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the perimeter format as it traces around the perimeter. A second format A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. A single edge is described by the vertex numbers at its two ends, always in ascending order. All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the edge format. Task 1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) 2. Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
#11l
11l
F perim_equal(p1, =p2) I p1.len != p2.len | Set(p1) != Set(p2) R 0B I any((0 .< p1.len).map(n -> @p2 == (@p1[n ..] [+] @p1[0 .< n]))) R 1B p2 = reversed(p2) R any((0 .< p1.len).map(n -> @p2 == (@p1[n ..] [+] @p1[0 .< n])))   F edge_to_periphery(e) V edges = sorted(e) [Int] p I !edges.empty p = [edges[0][0], edges[0][1]] edges.pop(0) V last = I !p.empty {p.last} E -1 L !edges.empty L(ij) edges V (i, j) = ij I i == last p.append(j) last = j edges.pop(L.index) L.break E I j == last p.append(i) last = i edges.pop(L.index) L.break L.was_no_break R ‘>>>Error! Invalid edge format<<<’ R String(p[0 .< (len)-1])   print(‘Perimeter format equality checks:’) L(eq_check) [(‘Q’, [8, 1, 3], ‘R’, [1, 3, 8]), (‘U’, [18, 8, 14, 10, 12, 17, 19], ‘V’, [8, 14, 10, 12, 17, 19, 18])] V (n1, p1, n2, p2) = eq_check V eq = I perim_equal(p1, p2) {‘==’} E ‘!=’ print(‘ ’n1‘ ’eq‘ ’n2)   print("\nEdge to perimeter format translations:") V edge_d = [‘E’ = [(1, 11), (7, 11), (1, 7)], ‘F’ = [(11, 23), (1, 17), (17, 23), (1, 11)], ‘G’ = [(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)], ‘H’ = [(1, 3), (9, 11), (3, 11), (1, 11)]] L(name, edges) edge_d print(‘ ’name‘: ’edges"\n -> "edge_to_periphery(edges))
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
#Oz
Oz
declare fun {FizzBuzz X} if X mod 15 == 0 then 'FizzBuzz' elseif X mod 3 == 0 then 'Fizz' elseif X mod 5 == 0 then 'Buzz' else X end end in for I in 1..100 do {Show {FizzBuzz I}} end
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Euphoria
Euphoria
  function fibor(integer n) if n<2 then return n end if return fibor(n-1)+fibor(n-2) end function  
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
#MUMPS
MUMPS
factors(num) New fctr,list,sep,sqrt If num<1 Quit "Too small a number" If num["." Quit "Not an integer" Set sqrt=num**0.5\1 For fctr=1:1:sqrt Set:num/fctr'["." list(fctr)=1,list(num/fctr)=1 Set (list,fctr)="",sep="[" For Set fctr=$Order(list(fctr)) Quit:fctr="" Set list=list_sep_fctr,sep="," Quit list_"]"   w $$factors(45) ; [1,3,5,9,15,45] w $$factors(53) ; [1,53] w $$factors(64) ; [1,2,4,8,16,32,64]
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.
#Rust
Rust
fn main() { println!("new vec filtered: "); let nums: Vec<i32> = (1..20).collect(); let evens: Vec<i32> = nums.iter().cloned().filter(|x| x % 2 == 0).collect(); println!("{:?}", evens);   // Filter an already existing vector println!("original vec filtered: "); let mut nums: Vec<i32> = (1..20).collect(); nums.retain(|x| x % 2 == 0); println!("{:?}", nums); }
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the perimeter format as it traces around the perimeter. A second format A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. A single edge is described by the vertex numbers at its two ends, always in ascending order. All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the edge format. Task 1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) 2. Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
#Go
Go
package main   import ( "fmt" "sort" )   // Check a slice contains a value. func contains(s []int, f int) bool { for _, e := range s { if e == f { return true } } return false }   // Assumes s1, s2 are of same length. func sliceEqual(s1, s2 []int) bool { for i := 0; i < len(s1); i++ { if s1[i] != s2[i] { return false } } return true }   // Reverses slice in place. func reverse(s []int) { for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 { s[i], s[j] = s[j], s[i] } }   // Check two perimeters are equal. func perimEqual(p1, p2 []int) bool { le := len(p1) if le != len(p2) { return false } for _, p := range p1 { if !contains(p2, p) { return false } } // use copy to avoid mutating 'p1' c := make([]int, le) copy(c, p1) for r := 0; r < 2; r++ { for i := 0; i < le; i++ { if sliceEqual(c, p2) { return true } // do circular shift to right t := c[le-1] copy(c[1:], c[0:le-1]) c[0] = t } // now process in opposite direction reverse(c) } return false }   type edge [2]int   // Translates a face to perimeter format. func faceToPerim(face []edge) []int { // use copy to avoid mutating 'face' le := len(face) if le == 0 { return nil } edges := make([]edge, le) for i := 0; i < le; i++ { // check edge pairs are in correct order if face[i][1] <= face[i][0] { return nil } edges[i] = face[i] } // sort edges in ascending order sort.Slice(edges, func(i, j int) bool { if edges[i][0] != edges[j][0] { return edges[i][0] < edges[j][0] } return edges[i][1] < edges[j][1] }) var perim []int first, last := edges[0][0], edges[0][1] perim = append(perim, first, last) // remove first edge copy(edges, edges[1:]) edges = edges[0 : le-1] le-- outer: for le > 0 { for i, e := range edges { found := false if e[0] == last { perim = append(perim, e[1]) last, found = e[1], true } else if e[1] == last { perim = append(perim, e[0]) last, found = e[0], true } if found { // remove i'th edge copy(edges[i:], edges[i+1:]) edges = edges[0 : le-1] le-- if last == first { if le == 0 { break outer } else { return nil } } continue outer } } } return perim[0 : len(perim)-1] }   func main() { fmt.Println("Perimeter format equality checks:") areEqual := perimEqual([]int{8, 1, 3}, []int{1, 3, 8}) fmt.Printf(" Q == R is %t\n", areEqual) areEqual = perimEqual([]int{18, 8, 14, 10, 12, 17, 19}, []int{8, 14, 10, 12, 17, 19, 18}) fmt.Printf(" U == V is %t\n", areEqual) e := []edge{{7, 11}, {1, 11}, {1, 7}} f := []edge{{11, 23}, {1, 17}, {17, 23}, {1, 11}} g := []edge{{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}} h := []edge{{1, 3}, {9, 11}, {3, 11}, {1, 11}} fmt.Println("\nEdge to perimeter format translations:") for i, face := range [][]edge{e, f, g, h} { perim := faceToPerim(face) if perim == nil { fmt.Printf("  %c => Invalid edge format\n", i + 'E') } else { fmt.Printf("  %c => %v\n", i + 'E', perim) } } }
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
#PARI.2FGP
PARI/GP
{for(n=1,100, print(if(n%3, if(n%5, n , "Buzz" ) , if(n%5, "Fizz" , "FizzBuzz" ) )) )}
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if the computer programming language has one). Other programming languages may make use of the   POW   or some other BIF   (Built─In Ffunction),   or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an   infix operator   operating in   (or operating on)   the base. Example A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). Task   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.   Raise the following numbers   (integer or real):   -5     and   +5   to the following powers:   2nd     and   3rd   using the following expressions   (if applicable in your language):   -x**p   -(x)**p   (-x)**p   -(x**p)   Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. Related tasks   Exponentiation order   Exponentiation operator   Arbitrary-precision integers (included)   Parsing/RPN to infix conversion   Operator precedence References Wikipedia: Order of operations in Programming languages
#Ada
Ada
logical_operator  ::= and | or | xor relational_operator  ::= = | /= | < | <= | > | >= binary_adding_operator  ::= + | – | & unary_adding_operator  ::= + | – multiplying_operator  ::= * | / | mod | rem highest_precedence_operator ::= ** | abs | not
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
#Excel
Excel
FIBONACCI =LAMBDA(n, APPLYN(n - 2)( LAMBDA(xs, APPENDROWS(xs)( SUM( LASTNROWS(2)(xs) ) ) ) )({1;1}) )
http://rosettacode.org/wiki/Factors_of_an_integer
Factors of an integer
Basic Data Operation This is a basic data operation. It represents a fundamental action on a basic data type. You may see other such operations in the Basic Data Operations category, or: Integer Operations Arithmetic | Comparison Boolean Operations Bitwise | Logical String Operations Concatenation | Interpolation | Comparison | Matching Memory Operations Pointers & references | Addresses Task Compute the   factors   of a positive integer. These factors are the positive integers by which the number being factored can be divided to yield a positive integer result. (Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty;   this task does not require handling of either of these cases). Note that every prime number has two factors:   1   and itself. Related tasks   count in factors   prime decomposition   Sieve of Eratosthenes   primality by trial division   factors of a Mersenne number   trial factoring of a Mersenne number   partition an integer X into N primes   sequence of primes by Trial Division   sequence: smallest number greater than previous term with exactly n divisors
#Nanoquery
Nanoquery
n = int(input())   for i in range(1, n / 2) if (n % i = 0) print i + " " end end println 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.
#Salmon
Salmon
iterate(x; comprehend(y; [1...10]; y % 2 == 0) (y)) x!;
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the perimeter format as it traces around the perimeter. A second format A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. A single edge is described by the vertex numbers at its two ends, always in ascending order. All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the edge format. Task 1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) 2. Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
#Haskell
Haskell
import Data.List (find, delete, (\\)) import Control.Applicative ((<|>))   ------------------------------------------------------------   newtype Perimeter a = Perimeter [a] deriving Show   instance Eq a => Eq (Perimeter a) where Perimeter p1 == Perimeter p2 = null (p1 \\ p2) && ((p1 `elem` zipWith const (iterate rotate p2) p1) || Perimeter p1 == Perimeter (reverse p2))   rotate lst = zipWith const (tail (cycle lst)) lst   toEdges :: Ord a => Perimeter a -> Maybe (Edges a) toEdges (Perimeter ps) | allDifferent ps = Just . Edges $ zipWith ord ps (tail (cycle ps)) | otherwise = Nothing where ord a b = if a < b then (a, b) else (b, a)   allDifferent [] = True allDifferent (x:xs) = all (x /=) xs && allDifferent xs   ------------------------------------------------------------   newtype Edges a = Edges [(a, a)] deriving Show   instance Eq a => Eq (Edges a) where e1 == e2 = toPerimeter e1 == toPerimeter e2   toPerimeter :: Eq a => Edges a -> Maybe (Perimeter a) toPerimeter (Edges ((a, b):es)) = Perimeter . (a :) <$> go b es where go x rs | x == a = return [] | otherwise = do p <- find ((x ==) . fst) rs <|> find ((x ==) . snd) rs let next = if fst p == x then snd p else fst p (x :) <$> go next (delete p rs)
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
#Pascal
Pascal
program fizzbuzz(output); var i: integer; begin for i := 1 to 100 do if i mod 15 = 0 then writeln('FizzBuzz') else if i mod 3 = 0 then writeln('Fizz') else if i mod 5 = 0 then writeln('Buzz') else writeln(i) end.
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if the computer programming language has one). Other programming languages may make use of the   POW   or some other BIF   (Built─In Ffunction),   or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an   infix operator   operating in   (or operating on)   the base. Example A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). Task   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.   Raise the following numbers   (integer or real):   -5     and   +5   to the following powers:   2nd     and   3rd   using the following expressions   (if applicable in your language):   -x**p   -(x)**p   (-x)**p   -(x**p)   Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. Related tasks   Exponentiation order   Exponentiation operator   Arbitrary-precision integers (included)   Parsing/RPN to infix conversion   Operator precedence References Wikipedia: Order of operations in Programming languages
#ALGOL_68
ALGOL 68
BEGIN # show the results of exponentiation and unary minus in various combinations # FOR x FROM -5 BY 10 TO 5 DO FOR p FROM 2 TO 3 DO print( ( "x = ", whole( x, -2 ), " p = ", whole( p, 0 ) ) ); print( ( " -x**p ", whole( -x**p, -4 ) ) ); print( ( " -(x)**p ", whole( -(x)**p, -4 ) ) ); print( ( " (-x)**p ", whole( (-x)**p, -4 ) ) ); print( ( " -(x**p) ", whole( -(x**p), -4 ) ) ); print( ( newline ) ) OD OD END
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if the computer programming language has one). Other programming languages may make use of the   POW   or some other BIF   (Built─In Ffunction),   or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an   infix operator   operating in   (or operating on)   the base. Example A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). Task   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.   Raise the following numbers   (integer or real):   -5     and   +5   to the following powers:   2nd     and   3rd   using the following expressions   (if applicable in your language):   -x**p   -(x)**p   (-x)**p   -(x**p)   Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. Related tasks   Exponentiation order   Exponentiation operator   Arbitrary-precision integers (included)   Parsing/RPN to infix conversion   Operator precedence References Wikipedia: Order of operations in Programming languages
#AWK
AWK
  # syntax: GAWK -f EXPONENTIATION_WITH_INFIX_OPERATORS_IN_OR_OPERATING_ON_THE_BASE.AWK # converted from FreeBASIC BEGIN { print(" x p | -x^p -(x)^p (-x)^p -(x^p)") print("--------+------------------------------------") for (x=-5; x<=5; x+=10) { for (p=2; p<=3; p++) { printf("%3d %3d | %8d %8d %8d %8d\n",x,p,(-x^p),(-(x)^p),((-x)^p),(-(x^p))) } } exit(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
#F.23
F#
  let fibonacci n : bigint = let rec f a b n = match n with | 0 -> a | 1 -> b | n -> (f b (a + b) (n - 1)) f (bigint 0) (bigint 1) n > fibonacci 100;; val it : bigint = 354224848179261915075I
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
#NetRexx
NetRexx
/* NetRexx *********************************************************** * 21.04.2013 Walter Pachl * 21.04.2013 add method main to accept argument(s) *********************************************************************/ options replace format comments java crossref symbols nobinary class divl method main(argwords=String[]) static arg=Rexx(argwords) Parse arg a b Say a b If a='' Then Do help='java divl low [high] shows' help=help||' divisors of all numbers between low and high' Say help Return End If b='' Then b=a loop x=a To b say x '->' divs(x) End   method divs(x) public static returns Rexx if x==1 then return 1 /*handle special case of 1 */ lo=1 hi=x odd=x//2 /* 1 if x is odd */ loop j=2+odd By 1+odd While j*j<x /*divide by numbers<sqrt(x) */ if x//j==0 then Do /*Divisible? Add two divisors:*/ lo=lo j /* list low divisors */ hi=x%j hi /* list high divisors */ End End If j*j=x Then /*for a square number as input */ lo=lo j /* add its square root */ return lo hi /* return both lists */
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.
#Sather
Sather
class MARRAY{T} < $ARR{T} is include ARRAY{T};   filter_by(r:ROUT{T}:BOOL):SAME is o:MARRAY{T} := #; loop e ::= elt!; if r.call(e) then o := o.append(#MARRAY{T}(|e|)); end; end; return o; end;   end;   class MAIN is main is a ::= #MARRAY{INT}(|5, 6, 7, 8, 9, 10, 11|); sel ::= a.filter_by( bind(_.is_even) ); loop #OUT + sel.elt! + " "; end; #OUT + "\n"; end; end;
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the perimeter format as it traces around the perimeter. A second format A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. A single edge is described by the vertex numbers at its two ends, always in ascending order. All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the edge format. Task 1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) 2. Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
#J
J
NB. construct a list of all rotations of one of the faces NB. including all rotations of the reversed list. NB. Find out if the other face is a member of this list. NB. ,&:rotations -> append, but first enlist the rotations. rotations=. |."0 1~ i.@# reverse=: |. same_perimeter=: e. (,&:rotations reverse) (3, 1, 8)same_perimeter(8, 1, 3) 1 (18, 8, 14, 10, 12, 17, 19)same_perimeter(8, 14, 10, 12, 17, 19, 18) 1
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the perimeter format as it traces around the perimeter. A second format A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. A single edge is described by the vertex numbers at its two ends, always in ascending order. All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the edge format. Task 1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) 2. Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
#Julia
Julia
iseq(f, g) = any(n -> f == circshift(g, n), 1:length(g))   function toface(evec) try ret, edges = collect(evec[1]), copy(evec[2:end]) while !isempty(edges) i = findfirst(x -> ret[end] == x[1] || ret[end] == x[2], edges) push!(ret, ret[end] == edges[i][1] ? edges[i][2] : edges[i][1]) deleteat!(edges, i) end return ret[1:end-1] catch println("Invalid edges vector: $evec") exit(1) end end   const faces1 = [ [[8, 1, 3], [1, 3, 8]], [[18, 8, 14, 10, 12, 17, 19], [8, 14, 10, 12, 17, 19, 18]] ]   const faces2 = [ [(1, 11), (7, 11), (1, 7)], [(11, 23), (1, 17), (17, 23), (1, 11)], [(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)], [(1, 3), (9, 11), (3, 11), (1, 11)] ]   for faces in faces1 println("Faces are ", iseq(faces[1], faces[2]) ? "" : "not ", "equivalent.") end   for face in faces2 println(toface(face)) end  
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
#PDP-8_Assembly
PDP-8 Assembly
  /-------------------------------------------------------- /THIS PROGRAM PRINTS THE INTEGERS FROM 1 TO 100 (INCL). /WITH THE FOLLOWING RESTRICTIONS: / FOR MULTIPLES OF THREE, PRINT 'FIZZ' / FOR MULTIPLES OF FIVE, PRINT 'BUZZ' / FOR MULTIPLES OF BOTH THREE AND FIVE, PRINT 'FIZZBUZZ' /--------------------------------------------------------   /-------------------------------------------------------- /DEFINES /-------------------------------------------------------- SWBA=7447 /EAE MODE A INSTRUCTION DVI=7407 /EAE DIVIDE INSTRUCTION AIX0=0010 /AUTO INDEX REGISTER 0 CR=0215 /CARRIAGE RETURN LF=0212 /LINEFEED EOT=0000 /END OF TEXT NUL FIZMOD=0003 /CONSTANT DECIMAL 3 (FIZZ) BUZMOD=0005 /CONSTANT DECIMAL 5 (BUZZ) K10=0012 /CONSTANT DECIMAL 10   LAST=0144 /FIZZBUZZ THE NUMBERS 1..LAST /0144 OCTAL == 100 DECIMAL /CAN BE ANY FROM [0001...7777]   /-------------------------------------------------------- /FIZZBUZZ START=0200 /-------------------------------------------------------- *200 /START IN MEMORY AT 0200 OCTAL FZZBZZ, CLA /CLEAR AC TAD (-LAST-1 /LOAD CONSTANT -(LAST+1) DCA CNTR /SET UP MAIN COUNTER TAD (-FIZMOD /SET UP FIZZ COUNTER DCA FIZCTR /TO -3 TAD (-BUZMOD /SET UP BUZZ COUNTER DCA BUZCTR /TO -5 LOOP, ISZ CNTR /READY? SKP /NO: CONTINUE JMP I [7600 /YES: RETURN TO OS/8, REPLACE BY /'HLT' IF NOT ON OS/8 CHKFIZ, ISZ FIZCTR /MULTIPLE OF 3? JMP CHKBUZ /NO: CONTINUE TAD FIZSTR /YES: LOAD ADDRESS OF 'FIZZ' JMS STROUT /PRINT IT TO TTY TAD (-FIZMOD /RELOAD THE DCA FIZCTR /MOD 3 COUNTER CHKBUZ, ISZ BUZCTR /MULTIPLE OF 5? JMP CHKNUM /NO: CONTINUE TAD BUZSTR /YES: LOAD ADDRESS OF 'BUZZ' JMS STROUT /PRINT IT TO TTY TAD (-BUZMOD /RELOAD THE DCA BUZCTR /MOD 5 COUNTER JMP NXTLIN /PRINT NEWLINE AND CONTINUE CHKNUM, TAD FIZCTR /CHECK WHETHER MOD 3 COUNTER TAD (FIZMOD /IS RELOADED SNA /DID WE JUST PRINT 'FIZZ'? JMP NXTLIN /YES: PRINT NEWLINE AND CONTINUE CLA /ZERO THE AC NUM, TAD CNTR /LOAD THE MAIN NUMBER COUNTER TAD (LAST+1 /OFFSET IT TO A POSITIVE VALUE JMS NUMOUT /PRINT IT TO THE TTY NXTLIN, TAD LINSTR /LOAD THE ADDRESS OF THE NEWLINE JMS STROUT /PRINT IT TO TTY JMP LOOP /CONTINUE WITH THE NEXT NUMBER CNTR, 0 /MAIN COUNTER FIZCTR, 0 /FIZZ COUNTER BUZCTR, 0 /BUZZ COUNTER   /-------------------------------------------------------- /WRITE ASCII CHARACTER IN AC TO TTY /PRE : AC=ASCII CHARACTER /POST: AC=0 /-------------------------------------------------------- CHROUT, .-. TLS /SEND CHARACTER TO TTY TSF /IS TTY READY FOR NEXT CHARACTER? JMP .-1 /NO TRY AGAIN CLA /AC=0 JMP I CHROUT /RETURN   /-------------------------------------------------------- /WRITE NUL TERMINATED ASCII STRING TO TTY /PRE : AC=ADDRESS OF STRING MINUS 1 /POST: AC=0 /-------------------------------------------------------- STROUT, .-. DCA AIX0 /STORE POINTER IN AUTO INDEX 0 STRLOP, TAD I AIX0 /GET NEXT CHARACTER FROM STRING SNA /SKIP IF NOT EOT JMP I STROUT /RETURN JMS CHROUT /PRINT CHARACTER JMP STRLOP /GO GET NEXT CHARACTER   /-------------------------------------------------------- /WRITE NUMBER IN AC TO TTY AS DECIMAL /PRE : AC=UNSIGNED NUMBER BETWEEN 0000 AND 7777 /POST: AC=0 /-------------------------------------------------------- NUMOUT, .-. SWBA /SET EAE IN MODE A MQL /MQ=NUM; AC=0 TAD BUFFER /LOAD END OF BUFFER DCA BUFPTR /IN BUFPTR SKP /NUM IS ALREADY IN MQ NUMLOP, MQL /MQ=NUM; AC=0 DVI /MQ=NUM/10; AC=NUM-(NUM/10)*10 K10 /DECIMAL 10 TAD ("0 /ADD ASCII ZERO DCA I BUFPTR /STORE CHAR BUFFER, BACK TO FRONT CMA /AC=-1 TAD BUFPTR /DECREMENT DCA BUFPTR /BUFFER POINTER MQA /MQ -> AC SZA /READY IF ZERO JMP NUMLOP /GET NEXT DIGIT TAD BUFPTR /LOAD START OF CONVERTED NUMBER JMS STROUT /SEND IT TO TTY JMP I NUMOUT /RETURN BUFFER, .+4 /ADDRESS OF BUFFER *.+4 /RESERVE 4 LOCATIONS (MAX=4095) EOT /END OF BUFFER BUFPTR, 0 /POINTER IN BUFFER   /-------------------------------------------------------- /STRINGS /-------------------------------------------------------- FIZSTR, . /FIZZ STRING "F; "I; "Z; "Z; EOT BUZSTR, . /BUZZ STRING "B; "U; "Z; "Z; EOT LINSTR, . /NEWLINE STIRNG CR; LF; EOT $  
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if the computer programming language has one). Other programming languages may make use of the   POW   or some other BIF   (Built─In Ffunction),   or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an   infix operator   operating in   (or operating on)   the base. Example A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). Task   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.   Raise the following numbers   (integer or real):   -5     and   +5   to the following powers:   2nd     and   3rd   using the following expressions   (if applicable in your language):   -x**p   -(x)**p   (-x)**p   -(x**p)   Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. Related tasks   Exponentiation order   Exponentiation operator   Arbitrary-precision integers (included)   Parsing/RPN to infix conversion   Operator precedence References Wikipedia: Order of operations in Programming languages
#BASIC
BASIC
S$=" ":M$=CHR$(13):?M$" X P -X^P -(X)^P (-X)^P -(X^P)":FORX=-5TO+5STEP10:FORP=2TO3:?M$MID$("+",1+(X<0));X" "PRIGHT$(S$+STR$(-X^P),8)RIGHT$(S$+STR$(-(X)^P),8)RIGHT$(S$+STR$((-X)^P),8)RIGHT$(S$+STR$(-(X^P)),8);:NEXTP,X
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if the computer programming language has one). Other programming languages may make use of the   POW   or some other BIF   (Built─In Ffunction),   or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an   infix operator   operating in   (or operating on)   the base. Example A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). Task   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.   Raise the following numbers   (integer or real):   -5     and   +5   to the following powers:   2nd     and   3rd   using the following expressions   (if applicable in your language):   -x**p   -(x)**p   (-x)**p   -(x**p)   Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. Related tasks   Exponentiation order   Exponentiation operator   Arbitrary-precision integers (included)   Parsing/RPN to infix conversion   Operator precedence References Wikipedia: Order of operations in Programming languages
#F.23
F#
  printfn "-5.0**2.0=%f; -(5.0**2.0)=%f" (-5.0**2.0) (-(5.0**2.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
#Factor
Factor
: fib ( n -- m ) dup 2 < [ [ 0 1 ] dip [ swap [ + ] keep ] times drop ] unless ;
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
#Nim
Nim
import intsets, math, algorithm   proc factors(n: int): seq[int] = var fs: IntSet for x in 1 .. int(sqrt(float(n))): if n mod x == 0: fs.incl(x) fs.incl(n div x)   for x in fs: result.add(x) result.sort()   echo factors(45)
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.
#Scala
Scala
(1 to 100).filter(_ % 2 == 0)
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the perimeter format as it traces around the perimeter. A second format A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. A single edge is described by the vertex numbers at its two ends, always in ascending order. All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the edge format. Task 1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) 2. Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
#Nim
Nim
import algorithm, strutils   type Perimeter = seq[int] Face = tuple[name: char; perimeter: Perimeter] Edge = tuple[first, last: int]   const None = -1 # No point.   #---------------------------------------------------------------------------------------------------   func isSame(p1, p2: Perimeter): bool = ## Return "true" if "p1" and "p2" represent the same face.   if p1.len != p2.len: return false   for p in p1: if p notin p2: return false   var start = p2.find(p1[0]) if p1 == p2[start..^1] & p2[0..<start]: return true   let p3 = reversed(p2) start = p3.find(p1[0]) if p1 == p3[start..^1] & p3[0..<start]: return true   #---------------------------------------------------------------------------------------------------   func `$`(perimeter: Perimeter): string = ## Convert a perimeter to a string. '(' & perimeter.join(", ") & ')'   func `$`(face: Face): string = ## Convert a perimeter formatted face to a string. face.name & $face.perimeter   #---------------------------------------------------------------------------------------------------   func toPerimeter(edges: seq[Edge]): Perimeter = ## Convert a list of edges to perimeter representation. ## Return an empty perimeter if the list of edges doesn’t represent a face.   var edges = edges let firstEdge = edges.pop() # First edge taken in account. var nextPoint = firstEdge.first # Next point to search in remaining edges. result.add(nextpoint)   while edges.len > 0: # Search an edge. var idx = None for i, e in edges: if e.first == nextPoint or e.last == nextPoint: idx = i nextPoint = if nextpoint == e.first: e.last else: e.first break if idx == None: return @[] # No edge found containing "newPoint".   # Add next point to perimeter and remove the edge. result.add(nextPoint) edges.del(idx)   # Check that last added point is the expected one. if nextPoint != firstEdge.last: return @[]   #———————————————————————————————————————————————————————————————————————————————————————————————————   when isMainModule:   # List of pairs of perimeter formatted faces to compare. const FP = [(('P', @[8, 1, 3]), ('R', @[1, 3, 8])), (('U', @[18, 8, 14, 10, 12, 17, 19]), ('V', @[8, 14, 10, 12, 17, 19, 18]))]   echo "Perimeter comparison:" for (p1, p2) in FP: echo p1, if isSame(p1[1], p2[1]): " is same as " else: "is not same as", p2   # List of edge formatted faces. const FE = {'E': @[(1, 11), (7, 11), (1, 7)], 'F': @[(11, 23), (1, 17), (17, 23), (1, 11)], 'G': @[(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)], 'H': @[(1, 3), (9, 11), (3, 11), (1, 11)]}   echo "" echo "Conversion from edge to perimeter format:" for (faceName, edges) in FE: let perimeter = edges.toPerimeter() echo faceName, ": ", if perimeter.len == 0: "Invalid edge list" else: $perimeter
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the perimeter format as it traces around the perimeter. A second format A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. A single edge is described by the vertex numbers at its two ends, always in ascending order. All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the edge format. Task 1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) 2. Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
#Perl
Perl
use strict; use warnings; use feature 'say'; use Set::Scalar; use Set::Bag; use Storable qw(dclone);   sub show { my($pts) = @_; my $p='( '; $p .= '(' . join(' ',@$_) . ') ' for @$pts; $p.')' }   sub check_equivalence { my($a, $b) = @_; Set::Scalar->new(@$a) == Set::Scalar->new(@$b) }   sub edge_to_periphery { my $a = dclone \@_;   my $bag_a = Set::Bag->new; for my $p (@$a) { $bag_a->insert( @$p[0] => 1); $bag_a->insert( @$p[1] => 1); } 2 != @$bag_a{$_} and return 0 for keys %$bag_a;   my $b = shift @$a; while ($#{$a} > 0) { for my $k (0..$#{$a}) { my $v = @$a[$k]; if (@$v[0] == @$b[-1]) { push @$b, @$v[1]; splice(@$a,$k,1); last } elsif (@$v[1] == @$b[-1]) { push @$b, @$v[0]; splice(@$a,$k,1); last } } } @$b; }   say 'Perimeter format equality checks:'; for ([[8, 1, 3], [1, 3, 8]], [[18, 8, 14, 10, 12, 17, 19], [8, 14, 10, 12, 17, 19, 18]]) { my($a, $b) = @$_; say '(' . join(', ', @$a) . ') equivalent to (' . join(', ', @$b) . ')? ', check_equivalence($a, $b) ? 'True' : 'False'; }   say "\nEdge to perimeter format translations:"; for ([[1, 11], [7, 11], [1, 7]], [[11, 23], [1, 17], [17, 23], [1, 11]], [[8, 14], [17, 19], [10, 12], [10, 14], [12, 17], [8, 18], [18, 19]], [[1, 3], [9, 11], [3, 11], [1, 11]]) { say show($_) . ' ==> (' . (join ' ', edge_to_periphery(@$_) or 'Invalid edge format') . ')' }
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
#Peloton
Peloton
<# DEFINE USERDEFINEDROUTINE LITERAL>__FizzBuzz|<# SUPPRESSAUTOMATICWHITESPACE> <# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3</#> <# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5</#> <# ONLYFIRSTOFLASTTWO><# SAY LITERAL>Fizz</#></#> <# ONLYSECONDOFLASTTWO><# SAY LITERAL>Buzz</#></#> <# BOTH><# SAY LITERAL>FizzBuzz</#></#> <# NEITHER><# SAY PARAMETER>1</#></#> </#></#> <# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|...</#> </#>
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if the computer programming language has one). Other programming languages may make use of the   POW   or some other BIF   (Built─In Ffunction),   or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an   infix operator   operating in   (or operating on)   the base. Example A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). Task   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.   Raise the following numbers   (integer or real):   -5     and   +5   to the following powers:   2nd     and   3rd   using the following expressions   (if applicable in your language):   -x**p   -(x)**p   (-x)**p   -(x**p)   Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. Related tasks   Exponentiation order   Exponentiation operator   Arbitrary-precision integers (included)   Parsing/RPN to infix conversion   Operator precedence References Wikipedia: Order of operations in Programming languages
#Factor
Factor
USING: infix locals prettyprint sequences sequences.generalizations sequences.repeating ;   :: row ( x p -- seq ) x p "-x**p" [infix -x**p infix] "-(x)**p" [infix -(x)**p infix] "(-x)**p" [infix (-x)**p infix] "-(x**p)" [infix -(x**p) infix] 10 narray ;   { "x value" "p value" } { "expression" "result" } 8 cycle append -5 2 row -5 3 row 5 2 row 5 3 row 5 narray simple-table.
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if the computer programming language has one). Other programming languages may make use of the   POW   or some other BIF   (Built─In Ffunction),   or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an   infix operator   operating in   (or operating on)   the base. Example A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). Task   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.   Raise the following numbers   (integer or real):   -5     and   +5   to the following powers:   2nd     and   3rd   using the following expressions   (if applicable in your language):   -x**p   -(x)**p   (-x)**p   -(x**p)   Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. Related tasks   Exponentiation order   Exponentiation operator   Arbitrary-precision integers (included)   Parsing/RPN to infix conversion   Operator precedence References Wikipedia: Order of operations in Programming languages
#FreeBASIC
FreeBASIC
print " x p | -x^p -(x)^p (-x)^p -(x^p)" print "----------------+---------------------------------------------" for x as integer = -5 to 5 step 10 for p as integer = 2 to 3 print using " ## ## | #### #### #### ####";_ x;p;(-x^p);(-(x)^p);((-x)^p);(-(x^p)) next p next x
http://rosettacode.org/wiki/Exponentiation_with_infix_operators_in_(or_operating_on)_the_base
Exponentiation with infix operators in (or operating on) the base
(Many programming languages,   especially those with extended─precision integer arithmetic,   usually support one of **, ^, ↑ or some such for exponentiation.) Some languages treat/honor infix operators when performing exponentiation   (raising numbers to some power by the language's exponentiation operator,   if the computer programming language has one). Other programming languages may make use of the   POW   or some other BIF   (Built─In Ffunction),   or some other library service. If your language's exponentiation operator is not one of the usual ones, please comment on how to recognize it. This task will deal with the case where there is some form of an   infix operator   operating in   (or operating on)   the base. Example A negative five raised to the 3rd power could be specified as: -5 ** 3 or as -(5) ** 3 or as (-5) ** 3 or as something else (Not all computer programming languages have an exponential operator and/or support these syntax expression(s). Task   compute and display exponentiation with a possible infix operator, whether specified and/or implied/inferred.   Raise the following numbers   (integer or real):   -5     and   +5   to the following powers:   2nd     and   3rd   using the following expressions   (if applicable in your language):   -x**p   -(x)**p   (-x)**p   -(x**p)   Show here (on this page) the four (or more) types of symbolic expressions for each number and power. Try to present the results in the same format/manner as the other programming entries to make any differences apparent. The variables may be of any type(s) that is/are applicable in your language. Related tasks   Exponentiation order   Exponentiation operator   Arbitrary-precision integers (included)   Parsing/RPN to infix conversion   Operator precedence References Wikipedia: Order of operations in Programming languages
#Go
Go
package main   import ( "fmt" "math" )   type float float64   func (f float) p(e float) float { return float(math.Pow(float64(f), float64(e))) }   func main() { ops := []string{"-x.p(e)", "-(x).p(e)", "(-x).p(e)", "-(x.p(e))"} for _, x := range []float{float(-5), float(5)} { for _, e := range []float{float(2), float(3)} { fmt.Printf("x = %2.0f e = %0.0f | ", x, e) fmt.Printf("%s = %4.0f | ", ops[0], -x.p(e)) fmt.Printf("%s = %4.0f | ", ops[1], -(x).p(e)) fmt.Printf("%s = %4.0f | ", ops[2], (-x).p(e)) fmt.Printf("%s = %4.0f\n", ops[3], -(x.p(e))) } } }
http://rosettacode.org/wiki/Fibonacci_sequence
Fibonacci sequence
The Fibonacci sequence is a sequence   Fn   of natural numbers defined recursively: F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2, if n>1 Task Write a function to generate the   nth   Fibonacci number. Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion). The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition: Fn = Fn+2 - Fn+1, if n<0 support for negative     n     in the solution is optional. Related tasks   Fibonacci n-step number sequences‎   Leonardo numbers References   Wikipedia, Fibonacci number   Wikipedia, Lucas number   MathWorld, Fibonacci Number   Some identities for r-Fibonacci numbers   OEIS Fibonacci numbers   OEIS Lucas numbers
#Falcon
Falcon
function fib_i(n)   if n < 2: return n   fibPrev = 1 fib = 1 for i in [2:n] tmp = fib fib += fibPrev fibPrev = tmp end return fib 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
#Niue
Niue
[ 'n ; [ negative-or-zero [ , ] if [ n not-factor [ , ] when ] else ] n times n ] 'factors ;   [ dup 0 <= ] 'negative-or-zero ; [ swap dup rot swap mod 0 = not ] 'not-factor ;   ( tests ) 100 factors .s .clr ( => 1 2 4 5 10 20 25 50 100 ) newline 53 factors .s .clr ( => 1 53 ) newline 64 factors .s .clr ( => 1 2 4 8 16 32 64 ) newline 12 factors .s .clr ( => 1 2 3 4 6 12 )
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
#Ada
Ada
  subtype Consistent_Float is Float range Float'Range; -- No IEEE ideals  
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
#AppleScript
AppleScript
-- Permutate a list according to a given factorial base number. on FBNShuffle(|Ω|, fbn) set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to "." set fbnDigits to fbn's text items set AppleScript's text item delimiters to astid   repeat with m from 1 to (count fbnDigits) set m_plus_g to m + (item m of fbnDigits) set v to item m_plus_g of |Ω| repeat with i from (m_plus_g - 1) to m by -1 set item (i + 1) of |Ω| to item i of |Ω| end repeat set item m of |Ω| to v end repeat end FBNShuffle   -- Generate all the factorial base numbers having a given number of digits. on generateFBNs(numberOfDigits) script o property partials : {} property permutations : {} end script   if (numberOfDigits > 0) then repeat with i from 0 to numberOfDigits set end of o's permutations to (i as text) end repeat repeat with maxDigit from (numberOfDigits - 1) to 1 by -1 set o's partials to o's permutations set o's permutations to {} repeat with i from 1 to (count o's partials) set thisPartial to item i of o's partials repeat with j from 0 to maxDigit set end of o's permutations to (thisPartial & ("." & j)) end repeat end repeat end repeat end if   return o's permutations end generateFBNs   -- Generate a random factorial base number having a given number of digits. on generateRandomFBN(numberOfDigits) set fbnDigits to {} repeat with maxDigit from numberOfDigits to 1 by -1 set end of fbnDigits to (random number maxDigit) end repeat   set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to "." set fbn to fbnDigits as text set AppleScript's text item delimiters to astid   return fbn end generateRandomFBN   (* Test code *)   set astid to AppleScript's text item delimiters set AppleScript's text item delimiters to ""   -- 1. Reproduce table of {0, 1, 2, 3} permutations set output to {"1. Reproduce table of {0, 1, 2, 3} permutations:"} set elements to {0, 1, 2, 3} set listOfFBNs to generateFBNs((count elements) - 1) repeat with fbn in listOfFBNs copy elements to |Ω| FBNShuffle(|Ω|, fbn) set end of output to fbn's contents & " -> " & |Ω| end repeat   -- 2. Generate and count all 11-digit permutations. No way! set end of output to "" set numberOfDigits to 11 set numberOfPermutations to 1 repeat with base from 2 to (numberOfDigits + 1) set numberOfPermutations to numberOfPermutations * base end repeat set end of output to "2. " & numberOfDigits & "-digit factorial base numbers have " & (numberOfPermutations div 1) & " possible permutations!"   -- 3. Card shoe permutations with the given FBNs. set end of output to "" set shoe to {"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♣"} copy shoe to shoe1 copy shoe to shoe2 set fbn1 to "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" set fbn2 to "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" FBNShuffle(shoe1, fbn1) FBNShuffle(shoe2, fbn2) set end of output to "3. Shuffle " & shoe set end of output to "With " & fbn1 & (linefeed & " -> " & shoe1) set end of output to "With " & fbn2 & (linefeed & " -> " & shoe2)   -- 4. Card shoe permutation with randomly generated FBN. set end of output to "" set fbn3 to generateRandomFBN(51) FBNShuffle(shoe, fbn3) set end of output to "4. With randomly generated " & fbn3 & (linefeed & " -> " & shoe)   set AppleScript's text item delimiters to linefeed set output to output as text set AppleScript's text item delimiters to astid return output
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
#11l
11l
V fact = [1] L(n) 1..11 fact.append(fact[n-1] * n)   L(b) 9..12 print(‘The factorions for base ’b‘ are:’) L(i) 1..1'499'999 V fact_sum = 0 V j = i L j > 0 V d = j % b fact_sum += fact[d] j I/= b I 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.
#Scheme
Scheme
  (define filter (lambda (fn lst) (let iter ((lst lst) (result '())) (if (null? lst) (reverse result) (let ((item (car lst)) (rest (cdr lst))) (if (fn item) (iter rest (cons item result)) (iter rest result)))))))  
http://rosettacode.org/wiki/Faces_from_a_mesh
Faces from a mesh
A mesh defining a surface has uniquely numbered vertices, and named, simple-polygonal faces described usually by an ordered list of edge numbers going around the face, For example: External image of two faces Rough textual version without edges: 1 17 7 A B 11 23 A is the triangle (1, 11, 7), or equally (7, 11, 1), going anti-clockwise, or any of all the rotations of those ordered vertices. 1 7 A 11 B is the four-sided face (1, 17, 23, 11), or equally (23, 17, 1, 11) or any of their rotations. 1 17 B 11 23 Let's call the above the perimeter format as it traces around the perimeter. A second format A separate algorithm returns polygonal faces consisting of a face name and an unordered set of edge definitions for each face. A single edge is described by the vertex numbers at its two ends, always in ascending order. All edges for the face are given, but in an undefined order. For example face A could be described by the edges (1, 11), (7, 11), and (1, 7) (The order of each vertex number in an edge is ascending, but the order in which the edges are stated is arbitrary). Similarly face B could be described by the edges (11, 23), (1, 17), (17, 23), and (1, 11) in arbitrary order of the edges. Let's call this second format the edge format. Task 1. Write a routine to check if two perimeter formatted faces have the same perimeter. Use it to check if the following pairs of perimeters are the same: Q: (8, 1, 3) R: (1, 3, 8) U: (18, 8, 14, 10, 12, 17, 19) V: (8, 14, 10, 12, 17, 19, 18) 2. Write a routine and use it to transform the following faces from edge to perimeter format. E: {(1, 11), (7, 11), (1, 7)} F: {(11, 23), (1, 17), (17, 23), (1, 11)} G: {(8, 14), (17, 19), (10, 12), (10, 14), (12, 17), (8, 18), (18, 19)} H: {(1, 3), (9, 11), (3, 11), (1, 11)} Show your output here.
#Phix
Phix
with javascript_semantics function perequiv(sequence a, b) -- Works by aligning and rotating in one step, so theoretically much faster on massive sets. -- (ahem, faster than multiple rotates, index-only loops would obviously be even faster...) bool res = (length(a)==length(b)) if res and length(a)>0 then integer k = find(a[1],b) if k=0 then res = false else -- align with a (ie make b[1]==a[1], by -- rotating b k places in one operation) b = b[k..$]&b[1..k-1] if a!=b then -- eg {8,3,4,5} <=> {8,5,4,3}, ie -- rotate *and* keep in alignment. b[2..$] = reverse(b[2..$]) res = (a==b) end if end if end if -- return res return {"false","true"}[res+1] end function function edge2peri(sequence edges) sequence was = edges, res = {} string error = "" integer lnk = 0 if length(edges)<2 then error = "too short" else -- edges = sort(deep_copy(edges)) -- (see note below) res = deep_copy(edges[1]) edges = edges[2..$] lnk = res[2] while length(edges) and error="" do bool found = false for i=1 to length(edges) do integer k = find(lnk,edges[i]) if k then lnk = edges[i][3-k] edges[i..i] = {} if edges={} then if lnk!=res[1] then error = "oh dear" end if else if find(lnk,res) then error = "oops" end if res &= lnk end if found = true exit end if end for if not found then error = "bad link" exit end if end while end if if length(error) then res = {error,res,lnk,edges,was} end if return res end function constant ptests = {{{8, 1, 3}, {1, 3, 8}}, {{18, 8, 14, 10, 12, 17, 19}, {8, 14, 10, 12, 17, 19, 18}}, -- (check our results below against Go etc) {{1,11,7},{1,7,11}}, {{11,23,17,1},{1,11,23,17}}} for i=1 to length(ptests) do sequence {p,q} = ptests[i] printf(1,"%v equivalent to %v: %s\n",{p,q,perequiv(p,q)}) end for constant etests = {{{1, 11}, {7, 11}, {1, 7}}, {{11, 23}, {1, 17}, {17, 23}, {1, 11}}, {{8, 14}, {17, 19}, {10, 12}, {10, 14}, {12, 17}, {8, 18}, {18, 19}}, {{1, 3}, {9, 11}, {3, 11}, {1, 11}}} for i=1 to length(etests) do printf(1,"%v\n",{edge2peri(etests[i])}) end for