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/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Python
Python
import sys print(sys.getrecursionlimit())
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) ...
#Golfscript
Golfscript
100,{)6,{.(&},{1$1$%{;}{4*35+6875*25base{90\-}%}if}%\or}%n*
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Nanoquery
Nanoquery
import Nanoquery.IO println new(File, "input.txt").length() println new(File, "/input.txt").length()
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java symbols binary   runSample(arg) return   -- . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . method fileSize(fn) public static returns double ff = File(fn) fSize = ff.length() return fSize   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Fortran
Fortran
program FileIO   integer, parameter :: out = 123, in = 124 integer :: err character :: c   open(out, file="output.txt", status="new", action="write", access="stream", iostat=err) if (err == 0) then open(in, file="input.txt", status="old", action="read", access="stream", iostat=err) if (err == 0) the...
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#Haskell
Haskell
module Main where   import Control.Monad import Data.List import Data.Monoid import Text.Printf   entropy :: (Ord a) => [a] -> Double entropy = sum . map (\c -> (c *) . logBase 2 $ 1.0 / c) . (\cs -> let { sc = sum cs } in map (/ sc) cs) . map (fromIntegral . length) . group . so...
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Haskell
Haskell
import Data.List ( groupBy )   parseFasta :: FilePath -> IO () parseFasta fileName = do file <- readFile fileName let pairedFasta = readFasta $ lines file mapM_ (\(name, code) -> putStrLn $ name ++ ": " ++ code) pairedFasta   readFasta :: [String] -> [(String, String)] readFasta = pair . map concat . groupBy (\x ...
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#J
J
require 'strings' NB. not needed for J versions greater than 6. parseFasta=: ((': ' ,~ LF&taketo) , (LF -.~ LF&takeafter));._1
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#ALGOL_68
ALGOL 68
PRIO DICE = 9; # ideally = 11 #   OP DICE = ([]SCALAR in, INT step)[]SCALAR: ( ### Dice the array, extract array values a "step" apart ### IF step = 1 THEN in ELSE INT upb out := 0; [(UPB in-LWB in)%step+1]SCALAR out; FOR index FROM LWB in BY step TO UPB in DO out...
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#8086_Assembly
8086 Assembly
P: equ 929 ; P for 2^P-1 cpu 8086 bits 16 org 100h section .text mov ax,P ; Is P prime? call prime mov dx,notprm jc msg ; If not, say so and stop. xor bp,bp ; Let BP hold k test_k: inc bp ; k += 1 mov ax,P ; Calculate 2kP + 1 mul bp ; AX = kP shl ax,1 ; AX = 2kP inc ax ; AX = 2kP + 1 mov dx,ovfl ...
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   public static class FareySequence { public static void Main() { for (int i = 1; i <= 11; i++) { Console.WriteLine($"F{i}: " + string.Join(", ", Generate(i).Select(f => $"{f.num}/{f.den}"))); } for (int i = 100; ...
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#D
D
import std.array; import std.stdio;   int turn(int base, int n) { int sum = 0; while (n != 0) { int re = n % base; n /= base; sum += re; } return sum % base; }   void fairShare(int base, int count) { writef("Base %2d:", base); foreach (i; 0..count) { auto t = turn...
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#F.C5.8Drmul.C3.A6
Fōrmulæ
package main   import ( "fmt" "math/big" )   func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) ...
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#Go
Go
package main   import ( "fmt" "math/big" )   func bernoulli(z *big.Rat, n int64) *big.Rat { if z == nil { z = new(big.Rat) } a := make([]big.Rat, n+1) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) } } return z.S...
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Ring
Ring
  decimals(0) load "stdlib.ring"   see "working..." + nl see "The first 10 Fermat numbers are:" + nl   num = 0 limit = 9   for n = 0 to limit fermat = pow(2,pow(2,n)) + 1 mod = fermat%2 if n > 5 ferm = string(fermat) tmp = number(right(ferm,1))+1 fermat = left(ferm,len(ferm)-1) + strin...
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Ruby
Ruby
This uses the `factor` function from the `coreutils` library that comes standard with most GNU/Linux, BSD, and Unix systems. https://www.gnu.org/software/coreutils/ https://en.wikipedia.org/wiki/GNU_Core_Utilities
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} ...
#Befunge
Befunge
110p>>55+109"iccanaceD"22099v v9013"Tetranacci"9014"Lucas"< >"iccanobirT"2109"iccanobiF"v >>:#,_0p20p0>:01-\2>#v0>#g<>> ^_@#:,+55$_^ JH v`1:v#\p03< _$.1+:77+`^vg03:_0g+>\:1+#^ 50p-\30v v\<>\30g1-\^$$_:1- 05g04\g< >`#^_:40p30g0>^!:g
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Ruby
Ruby
def main maxIt = 13 maxItJ = 10 a1 = 1.0 a2 = 0.0 d1 = 3.2 puts " i d" for i in 2 .. maxIt a = a1 + (a1 - a2) / d1 for j in 1 .. maxItJ x = 0.0 y = 0.0 for k in 1 .. 1 << i y = 1.0 - 2.0 * y * x x = a -...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Scala
Scala
object Feigenbaum1 extends App { val (max_it, max_it_j) = (13, 10) var (a1, a2, d1, a) = (1.0, 0.0, 3.2, 0.0)   println(" i d") var i: Int = 2 while (i <= max_it) { a = a1 + (a1 - a2) / d1 for (_ <- 0 until max_it_j) { var (x, y) = (0.0, 0.0) for (_ <- 0 until 1 << i) { y = 1...
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#Wren
Wren
import "/str" for Str import "/fmt" for Fmt   var exts = ["zip", "rar", "7z", "gz", "archive", "A##", "tar.bz2"]   var tests = [ "MyData.a##", "MyData.tar.Gz", "MyData.gzip" , "MyData.7z.backup", "MyData...", "MyData", "MyData_v1.0.tar.bz2", "MyData_v1.0.bz2" ]   var ucExts = exts.map { |e| "." + Str.upper(e) ...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Ring
Ring
  load "stdlib.ring" see GetFileInfo( "test.ring" )   func GetFileInfo cFile cOutput = systemcmd("dir /T:W " + cFile ) aList = str2list(cOutput) cLine = aList[6] aInfo = split(cLine," ") return aInfo  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Ruby
Ruby
#Get modification time: modtime = File.mtime('filename')   #Set the access and modification times: File.utime(actime, mtime, 'path')   #Set just the modification time: File.utime(File.atime('path'), mtime, 'path')   #Set the access and modification times to the current time: File.utime(nil, nil, 'path')
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Run_BASIC
Run BASIC
files #f, DefaultDir$ + "\*.*" ' all files in the default directory   print "hasanswer: ";#f HASANSWER() ' does it exist print "rowcount: ";#f ROWCOUNT() ' number of files in the directory print ' #f DATEFORMAT("mm/dd/yy") ...
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Ruby
Ruby
def fibonacci_word(n) words = ["1", "0"] (n-1).times{ words << words[-1] + words[-2] } words[n] end   def print_fractal(word) area = Hash.new(" ") x = y = 0 dx, dy = 0, -1 area[[x,y]] = "S" word.each_char.with_index(1) do |c,n| area[[x+dx, y+dy]] = dx.zero? ? "|" : "-" x, y = x+2*dx, y+2*dy ...
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Rust
Rust
// [dependencies] // svg = "0.8.0"   use svg::node::element::path::Data; use svg::node::element::Path;   fn fibonacci_word(n: usize) -> Vec<u8> { let mut f0 = vec![1]; let mut f1 = vec![0]; if n == 0 { return f0; } else if n == 1 { return f1; } let mut i = 2; loop { l...
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Oz
Oz
declare fun {CommonPrefix Sep Paths} fun {GetParts P} {String.tokens P Sep} end Parts = {ZipN {Map Paths GetParts}} EqualParts = {List.takeWhile Parts fun {$ X|Xr} {All Xr {Equals X}} end} in {Join Sep {Map EqualParts Head}} end   fun {ZipN Xs} if {Some Xs {Equals nil}} then nil el...
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.
#D
D
void main() { import std.algorithm: filter, equal;   immutable data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; auto evens = data.filter!(x => x % 2 == 0); // Lazy. assert(evens.equal([2, 4, 6, 8, 10])); }
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Quackery
Quackery
0 [ 1+ dup echo cr recurse ]
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#R
R
#Get the limit options("expressions")   #Set it options(expressions = 10000)   #Test it recurse <- function(x) { print(x) recurse(x+1)   } recurse(0)
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Racket
Racket
#lang racket (define (recursion-limit) (with-handlers ((exn? (lambda (x) 0))) (add1 (recursion-limit))))
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) ...
#Golo
Golo
module FizzBuzz   augment java.lang.Integer { function getFizzAndOrBuzz = |this| -> match { when this % 15 == 0 then "FizzBuzz" when this % 3 == 0 then "Fizz" when this % 5 == 0 then "Buzz" otherwise this } }   function main = |args| { foreach i in [1..101] { println(i: getFizzAndOrBuzz()) } }  
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#NewLISP
NewLISP
(println (first (file-info "input.txt"))) (println (first (file-info "/input.txt")))
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Nim
Nim
import os echo getFileSize "input.txt" echo getFileSize "/input.txt"
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Objeck
Objeck
  use IO; ... File("input.txt")->Size()->PrintLine(); File("c:\input.txt")->Size()->PrintLine();  
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   /' input.txt contains:   The quick brown fox jumps over the lazy dog. Empty vessels make most noise. Too many chefs spoil the broth. A rolling stone gathers no moss. '/   Open "output.txt" For Output As #1 Open "input.txt" For Input As #2 Dim line_ As String ' note that line is a keyword   While N...
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Frink
Frink
  contents = read["file:input.txt"] w = new Writer["output.txt"] w.print[contents] w.close[]  
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#Icon_and_Unicon
Icon and Unicon
procedure main(A) n := integer(A[1]) | 37 write(right("N",4)," ",right("length",15)," ",left("Entrophy",15)," ", " Fibword") every w := fword(i := 1 to n) do { writes(right(i,4)," ",right(*w,15)," ",left(H(w),15)) if i <= 8 then write(": ",w) else write() } end   procedure ...
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Java
Java
import java.io.*; import java.util.Scanner;   public class ReadFastaFile {   public static void main(String[] args) throws FileNotFoundException {   boolean first = true;   try (Scanner sc = new Scanner(new File("test.fasta"))) { while (sc.hasNextLine()) { String line = s...
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#JavaScript
JavaScript
  const fs = require("fs"); const readline = require("readline");   const args = process.argv.slice(2); if (!args.length) { console.error("must supply file name"); process.exit(1); }   const fname = args[0];   const readInterface = readline.createInterface({ input: fs.createReadStream(fname), console: f...
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 |...
#0815
0815
  <:1:~>|~#:end:>~x}:str:/={^:wei:~%x<:a:x=$~ =}:wei:x<:1:+{>~>x=-#:fin:^:str:}:fin:{{~%  
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#APL
APL
fft←{ 1>k←2÷⍨N←⍴⍵:⍵ 0≠1|2⍟N:'Argument must be a power of 2 in length' even←∇(N⍴0 1)/⍵ odd←∇(N⍴1 0)/⍵ T←even×*(0J¯2×(○1)×(¯1+⍳k)÷N) (odd+T),odd-T }
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#360_Assembly
360 Assembly
* Factors of a Mersenne number 11/09/2015 MERSENNE CSECT USING MERSENNE,R15 MVC Q,=F'929' q=929 (M929=2**929-1) LA R6,1 k=1 LOOPK C R6,=F'1048576' do k=1 to 2**20 BNL ELOOPK LR R5,R6 k M ...
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#Ada
Ada
with Ada.Text_IO; -- reuse Is_Prime from [[Primality by Trial Division]] with Is_Prime;   procedure Mersenne is function Is_Set (Number : Natural; Bit : Positive) return Boolean is begin return Number / 2 ** (Bit - 1) mod 2 = 1; end Is_Set;   function Get_Max_Bit (Number : Natural) return Natural is ...
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#C.2B.2B
C++
#include <iostream>   struct fraction { fraction(int n, int d) : numerator(n), denominator(d) {} int numerator; int denominator; };   std::ostream& operator<<(std::ostream& out, const fraction& f) { out << f.numerator << '/' << f.denominator; return out; }   class farey_sequence { public: explic...
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Factor
Factor
USING: formatting kernel math math.parser sequences ;   : nth-fairshare ( n base -- m ) [ >base string>digits sum ] [ mod ] bi ;   : <fairshare> ( n base -- seq ) [ nth-fairshare ] curry { } map-integers ;   { 2 3 5 11 } [ 25 over <fairshare> "%2d -> %u\n" printf ] each
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#FreeBASIC
FreeBASIC
  Function Turn(mibase As Integer, n As Integer) As Integer Dim As Integer sum = 0 While n <> 0 Dim As Integer re = n Mod mibase n \= mibase sum += re Wend Return sum Mod mibase End Function   Sub Fairshare(mibase As Integer, count As Integer) Print Using "mibase ##:"; mibase...
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#Go
Go
package main   import ( "fmt" "math/big" )   func bernoulli(n uint) *big.Rat { a := make([]big.Rat, n+1) z := new(big.Rat) for m := range a { a[m].SetFrac64(1, int64(m+1)) for j := m; j >= 1; j-- { d := &a[j-1] d.Mul(z.SetInt64(int64(j)), d.Sub(d, &a[j])) ...
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#Groovy
Groovy
import java.util.stream.IntStream   class FaulhabersFormula { private static long gcd(long a, long b) { if (b == 0) { return a } return gcd(b, a % b) }   private static class Frac implements Comparable<Frac> { private long num private long denom   ...
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Rust
Rust
struct DivisorGen { curr: u64, last: u64, }   impl Iterator for DivisorGen { type Item = u64;   fn next(&mut self) -> Option<u64> { self.curr += 2u64;   if self.curr < self.last{ None } else { Some(self.curr) } } }   fn divisor_gen(num : u64) ...
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Scala
Scala
import scala.collection.mutable import scala.collection.mutable.ListBuffer   object FermatNumbers { def main(args: Array[String]): Unit = { println("First 10 Fermat numbers:") for (i <- 0 to 9) { println(f"F[$i] = ${fermat(i)}") } println() println("First 12 Fermat numbers factored:") fo...
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} ...
#Bracmat
Bracmat
( ( nacci = Init Cnt N made tail . ( plus = n .  !arg:#%?n ?arg&!n+plus$!arg | 0 ) & !arg:(?Init.?Cnt) & !Init:? [?N & !Init:?made & !Cnt+-1*!N:?times & -1+-1*!N:?M & whl ' ( !times+-1:~<0:?times & !made:? [!M ?ta...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Sidef
Sidef
var a1 = 1 var a2 = 0 var δ = 3.2.float   say " i\tδ"   for i in (2..15) { var a0 = ((a1 - a2)/δ + a1) 10.times { var (x, y) = (0, 0) 2**i -> times { y = (1 - 2*x*y) x = (a0 - x²) } a0 -= x/y } δ = ((a1 - a2) / (a0 - a1)) (a2, a1) = (a1, a0) ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Swift
Swift
import Foundation   func feigenbaum(iterations: Int = 13) { var a = 0.0 var a1 = 1.0 var a2 = 0.0 var d = 0.0 var d1 = 3.2   print(" i d")   for i in 2...iterations { a = a1 + (a1 - a2) / d1   for _ in 1...10 { var x = 0.0 var y = 0.0   for _ in 1...1<<i { y = 1.0 -...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Visual_Basic_.NET
Visual Basic .NET
Module Module1   Sub Main() Dim maxIt = 13 Dim maxItJ = 10 Dim a1 = 1.0 Dim a2 = 0.0 Dim d1 = 3.2 Console.WriteLine(" i d") For i = 2 To maxIt Dim a = a1 + (a1 - a2) / d1 For j = 1 To maxItJ Dim x = 0.0 ...
http://rosettacode.org/wiki/File_extension_is_in_extensions_list
File extension is in extensions list
File extension is in extensions list You are encouraged to solve this task according to the task description, using any language you may know. Filename extensions are a rudimentary but commonly used way of identifying files types. Task Given an arbitrary filename and a list of extensions, tell whether the filename...
#zkl
zkl
fcn hasExtension(fnm){ var [const] extensions=T(".zip",".rar",".7z",".gz",".archive",".a##"); nm,ext:=File.splitFileName(fnm)[-2,*].apply("toLower"); if(extensions.holds(ext)) True; else if(ext==".bz2" and ".tar"==File.splitFileName(nm)[-1]) True; else False } nms:=T("MyData.a##","MyData.tar.Gz","MyData....
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Rust
Rust
use std::fs;   fn main() -> std::io::Result<()> { let metadata = fs::metadata("foo.txt")?;   if let Ok(time) = metadata.accessed() { println!("{:?}", time); } else { println!("Not supported on this platform"); } Ok(()) }  
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Scala
Scala
import java.io.File import java.util.Date   object FileModificationTime extends App { def test(file: File) { val (t, init) = (file.lastModified(), s"The following ${if (file.isDirectory()) "directory" else "file"} called ${file.getPath()}")   println(init + (if (t == 0) " does not exist." else " was mod...
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Scala
Scala
  def fibIt = Iterator.iterate(("1","0")){case (f1,f2) => (f2,f1+f2)}.map(_._1)   def turnLeft(c: Char): Char = c match { case 'R' => 'U' case 'U' => 'L' case 'L' => 'D' case 'D' => 'R' }   def turnRight(c: Char): Char = c match { case 'R' => 'D' case 'D' => 'L' case 'L' => 'U' case 'U' => 'R' }   def d...
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#PARI.2FGP
PARI/GP
cdp(v)={ my(s=""); v=apply(t->Vec(t),v); for(i=1,vecmin(apply(length,v)), for(j=2,#v, if(v[j][i]!=v[1][i],return(s))); if(i>1&v[1][i]=="/",s=concat(vecextract(v[1],1<<(i-1)-1)) ) ); if(vecmax(apply(length,v))==vecmin(apply(length,v)),concat(v[1]),s) }; cdp(["/home/user1/tmp/coverage/test",...
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.
#Delphi
Delphi
program FilterEven;   {$APPTYPE CONSOLE}   uses SysUtils, Types;   const SOURCE_ARRAY: array[0..9] of Integer = (0,1,2,3,4,5,6,7,8,9); var i: Integer; lEvenArray: TIntegerDynArray; begin for i in SOURCE_ARRAY do begin if not Odd(i) then begin SetLength(lEvenArray, Length(lEvenArray) + 1); ...
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Raku
Raku
my $x = 0; recurse;   sub recurse () { ++$x; say $x if $x %% 1_000_000; recurse; }
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Retro
Retro
: try -6 5 out wait 5 in putn cr try ;
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) ...
#Gosu
Gosu
for (i in 1..100) {   if (i % 3 == 0 && i % 5 == 0) { print("FizzBuzz") continue }   if (i % 3 == 0) { print("Fizz") continue }   if (i % 5 == 0) { print("Buzz") continue }   // default print(i)   }
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Objective-C
Objective-C
NSFileManager *fm = [NSFileManager defaultManager];   // Pre-OS X 10.5 NSLog(@"%llu", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileSize]);   // OS X 10.5+ NSLog(@"%llu", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileSize]);
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#OCaml
OCaml
let printFileSize filename = let ic = open_in filename in Printf.printf "%d\n" (in_channel_length ic); close_in ic ;;   printFileSize "input.txt" ;; printFileSize "/input.txt" ;;
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#Gambas
Gambas
Public Sub Main() Dim sOutput As String = "Hello " Dim sInput As String = File.Load(User.Home &/ "input.txt") 'Has the word 'World!' stored   File.Save(User.Home &/ "output.txt", sOutput) File.Save(User.Home &/ "input.txt", sOutput & sInput)   Print "'input.txt' contains - " & sOutput & sInput Print "'output.txt' conta...
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#GAP
GAP
CopyFile := function(src, dst) local f, g, line; f := InputTextFile(src); g := OutputTextFile(dst, false); while true do line := ReadLine(f); if line = fail then break else WriteLine(g, Chomp(line)); fi; od; CloseStream(f); CloseStream(g); end;
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#J
J
F_Words=: (,<@;@:{~&_1 _2)@]^:(2-~[)&('1';'0')
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#Java
Java
import java.util.*;   public class FWord { private /*v*/ String fWord0 = ""; private /*v*/ String fWord1 = "";   private String nextFWord () { final String result;   if ( "".equals ( fWord1 ) ) result = "1"; else if ( "".equals ( fWord0 ) ) result = "0"; else ...
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#jq
jq
  def fasta: foreach (inputs, ">") as $line # state: [accumulator, print ] ( [null, null]; if $line[0:1] == ">" then [($line[1:] + ": "), .[0]] else [ (.[0] + $line), false] end; if .[1] then .[1] else empty end )  ;   fasta
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Julia
Julia
for line in eachline("data/fasta.txt") if startswith(line, '>') print(STDOUT, "\n$(line[2:end]): ") else print(STDOUT, "$line") end end
http://rosettacode.org/wiki/FASTA_format
FASTA format
In bioinformatics, long character strings are often encoded in a format called FASTA. A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line. Task Write a program that reads a FASTA file such as: >Rosetta_Example_1 THERECANBENOSPACE ...
#Kotlin
Kotlin
// version 1.1.2   import java.util.Scanner import java.io.File   fun checkNoSpaces(s: String) = ' ' !in s && '\t' !in s   fun main(args: Array<String>) { var first = true val sc = Scanner(File("input.fasta")) while (sc.hasNextLine()) { val line = sc.nextLine() if (line[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 |...
#11l
11l
F factor(n) V factors = Set[Int]() L(x) 1..Int(sqrt(n)) I n % x == 0 factors.add(x) factors.add(n I/ x) R sorted(Array(factors))   L(i) (45, 53, 64) print(i‘: factors: ’String(factor(i)))
http://rosettacode.org/wiki/Fast_Fourier_transform
Fast Fourier transform
Task Calculate the   FFT   (Fast Fourier Transform)   of an input sequence. The most general case allows for complex numbers at the input and results in a sequence of equal length, again of complex numbers. If you need to restrict yourself to real numbers, the output should be the magnitude   (i.e.:   sqrt(re2 + im2)...
#BBC_BASIC
BBC BASIC
@% = &60A   DIM Complex{r#, i#} DIM in{(7)} = Complex{}, out{(7)} = Complex{} DATA 1, 1, 1, 1, 0, 0, 0, 0   PRINT "Input (real, imag):" FOR I% = 0 TO 7 READ in{(I%)}.r# PRINT in{(I%)}.r# "," in{(I%)}.i# NEXT   PROCfft(out{()}, in{()}, 0, 1, DIM(in{()},1)+1...
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number
Factors of a Mersenne number
A Mersenne number is a number in the form of 2P-1. If P is prime, the Mersenne number may be a Mersenne prime (if P is not prime, the Mersenne number is also not prime). In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy,...
#ALGOL_68
ALGOL 68
MODE ISPRIMEINT = INT; PR READ "prelude/is_prime.a68" PR;   MODE POWMODSTRUCT = INT; PR READ "prelude/pow_mod.a68" PR;   PROC m factor = (INT p)INT:BEGIN INT m factor; INT max k, msb, n, q;   FOR i FROM bits width - 2 BY -1 TO 0 WHILE ( BIN p SHR i AND 2r1 ) = 2r0 DO msb := i OD;   max k := ENTIER sqrt(...
http://rosettacode.org/wiki/Farey_sequence
Farey sequence
The   Farey sequence   Fn   of order   n   is the sequence of completely reduced fractions between   0   and   1   which, when in lowest terms, have denominators less than or equal to   n,   arranged in order of increasing size. The   Farey sequence   is sometimes incorrectly called a   Farey series. Each Farey se...
#Common_Lisp
Common Lisp
(defun farey (n) (labels ((helper (begin end) (let ((med (/ (+ (numerator begin) (numerator end)) (+ (denominator begin) (denominator end))))) (if (<= (denominator med) n) (append (helper begin med) (list med) (helper med end)))))) (append (list 0) (helper 0 1) (list 1))))  ...
http://rosettacode.org/wiki/Fairshare_between_two_and_more
Fairshare between two and more
The Thue-Morse sequence is a sequence of ones and zeros that if two people take turns in the given order, the first persons turn for every '0' in the sequence, the second for every '1'; then this is shown to give a fairer, more equitable sharing of resources. (Football penalty shoot-outs for example, might not favour t...
#Go
Go
package main   import ( "fmt" "sort" "strconv" "strings" )   func fairshare(n, base int) []int { res := make([]int, n) for i := 0; i < n; i++ { j := i sum := 0 for j > 0 { sum += j % base j /= base } res[i] = sum % base } re...
http://rosettacode.org/wiki/Faulhaber%27s_triangle
Faulhaber's triangle
Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula: ∑ k = 1 n k p = 1 p + 1 ∑ j = 0 p ( p + 1 j ) B j n p + 1 − j {\displaystyle \sum _{k...
#Groovy
Groovy
import java.math.MathContext import java.util.stream.LongStream   class FaulhabersTriangle { private static final MathContext MC = new MathContext(256)   private static long gcd(long a, long b) { if (b == 0) { return a } return gcd(b, a % b) }   private static class F...
http://rosettacode.org/wiki/Faulhaber%27s_formula
Faulhaber's formula
In mathematics,   Faulhaber's formula,   named after Johann Faulhaber,   expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n,   the coefficients involving Bernoulli numbers. Task Generate the first 10 closed-form expressions, starting with p = 0. R...
#Haskell
Haskell
import Data.Ratio ((%), numerator, denominator) import Data.List (intercalate, transpose) import Data.Bifunctor (bimap) import Data.Char (isSpace) import Data.Monoid ((<>)) import Data.Bool (bool)   ------------------------- FAULHABER ------------------------ faulhaber :: [[Rational]] faulhaber = tail $ scanl (...
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Sidef
Sidef
func fermat_number(n) { 2**(2**n) + 1 }   func fermat_one_factor(n) { fermat_number(n).ecm_factor }   for n in (0..9) { say "F_#{n} = #{fermat_number(n)}" }   say ''   for n in (0..13) { var f = fermat_one_factor(n) say ("F_#{n} = ", join(' * ', f.shift, f.map { <C P>[.is_prime] + .len }...)) ...
http://rosettacode.org/wiki/Fermat_numbers
Fermat numbers
In mathematics, a Fermat number, named after Pierre de Fermat who first studied them, is a positive integer of the form Fn = 22n + 1 where n is a non-negative integer. Despite the simplicity of generating Fermat numbers, they have some powerful mathematical properties and are extensively used in cryptography & pseudo-...
#Tcl
Tcl
namespace import ::tcl::mathop::* package require math::numtheory 1.1.1; # Buggy before tcllib-1.20   proc fermat n { + [** 2 [** 2 $n]] 1 }     for {set i 0} {$i < 10} {incr i} { puts "F$i = [fermat $i]" }   for {set i 1} {1} {incr i} { puts -nonewline "F$i... " flush stdout set F [fermat $i] set factors [math::...
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences
Fibonacci n-step number sequences
These number series are an expansion of the ordinary Fibonacci sequence where: For n = 2 {\displaystyle n=2} we have the Fibonacci sequence; with initial values [ 1 , 1 ] {\displaystyle [1,1]} and F k 2 = F k − 1 2 + F k − 2 2 {\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}} ...
#BQN
BQN
NStep ← ⊑(1↓⊢∾+´)∘⊢⍟⊣ Nacci ← (2⋆0∾↕)∘(⊢-1˙)   >((↕10) NStep¨ <)¨ (Nacci¨ 2‿3‿4) ∾ <2‿1
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Vlang
Vlang
fn feigenbaum() { max_it, max_itj := 13, 10 mut a1, mut a2, mut d1 := 1.0, 0.0, 3.2 println(" i d") for i := 2; i <= max_it; i++ { mut a := a1 + (a1-a2)/d1 for j := 1; j <= max_itj; j++ { mut x, mut y := 0.0, 0.0 for k := 1; k <= 1<<u32(i); k++ { ...
http://rosettacode.org/wiki/Feigenbaum_constant_calculation
Feigenbaum constant calculation
Task Calculate the Feigenbaum constant. See   Details in the Wikipedia article:   Feigenbaum constant.
#Wren
Wren
import "/fmt" for Fmt   var feigenbaum = Fn.new { var maxIt = 13 var maxItJ = 10 var a1 = 1 var a2 = 0 var d1 = 3.2 System.print(" i d") for (i in 2..maxIt) { var a = a1 + (a1 - a2)/d1 for (j in 1..maxItJ) { var x = 0 var y = 0 for (k...
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Seed7
Seed7
$ include "seed7_05.s7i"; include "osfiles.s7i"; include "time.s7i";   const proc: main is func local var time: modificationTime is time.value; begin modificationTime := getMTime("data.txt"); setMTime("data.txt", modificationTime); end func;
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Sidef
Sidef
var file = File.new(__FILE__); say file.stat.mtime; # seconds since the epoch   # keep atime unchanged # set mtime to current time file.utime(file.stat.atime, Time.now);
http://rosettacode.org/wiki/File_modification_time
File modification time
Task Get and set the modification time of a file.
#Slate
Slate
slate[1]> (File newNamed: 'LICENSE') fileInfo modificationTimestamp. 1240349799
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Scilab
Scilab
final_length = 37;   word_n = ''; word_n_1 = ''; word_n_2 = '';   for i = 1:final_length if i == 1 then word_n = '1'; elseif i == 2 word_n = '0'; elseif i == 3 word_n = '01'; word_n_1 = '0'; else word_n_2 = word_n_1; word_n_1 = word_n; word_n = wor...
http://rosettacode.org/wiki/Fibonacci_word/fractal
Fibonacci word/fractal
The Fibonacci word may be represented as a fractal as described here: (Clicking on the above website   (hal.archives-ouvertes.fr)   will leave a cookie.) For F_wordm start with F_wordCharn=1 Draw a segment forward If current F_wordChar is 0 Turn left if n is even Turn right if n is odd next n and iterate until e...
#Sidef
Sidef
var(m=17, scale=3) = ARGV.map{.to_i}...   (var world = Hash.new){0}{0} = 1 var loc = 0 var dir = 1i   var fib = ['1', '0'] func fib_word(n) { fib[n] \\= (fib_word(n-1) + fib_word(n-2)) }   func step { scale.times { loc += dir world{loc.im}{loc.re} = 1 } }   func turn_left { dir *= 1i } fun...
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Perl
Perl
sub common_prefix { my $sep = shift; my $paths = join "\0", map { $_.$sep } @_; $paths =~ /^ ( [^\0]* ) $sep [^\0]* (?: \0 \1 $sep [^\0]* )* $/x; return $1; }
http://rosettacode.org/wiki/Find_common_directory_path
Find common directory path
Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories. Test your routine using the forward slash '/' character as the directory separator and the foll...
#Phix
Phix
with javascript_semantics function common_directory_path(sequence paths, integer sep='/') sequence res = {} if length(paths) then res = split(paths[1],sep)[1..-2] for i=2 to length(paths) do sequence pi = split(paths[i],sep)[1..-2] for j=1 to length(res) do ...
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.
#Dyalect
Dyalect
func Array.Filter(pred) { var arr = [] for x in this when pred(x) { arr.Add(x) } arr }   var arr = [1..20].Filter(x => x % 2 == 0) print(arr)
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#REXX
REXX
/*REXX program finds the recursion limit: a subroutine that repeatably calls itself. */ parse version x; say x; say /*display which REXX is being used. */ #=0 /*initialize the numbers of invokes to 0*/ call self ...
http://rosettacode.org/wiki/Find_limit_of_recursion
Find limit of recursion
Find limit of recursion is part of Short Circuit's Console Program Basics selection. Task Find the limit of recursion.
#Ring
Ring
  recurse(0)   func recurse x see ""+ x + nl recurse(x+1)  
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) ...
#Groovy
Groovy
1.upto(100) { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i }
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Oforth
Oforth
File new("input.txt") size println File new("/input.txt") size println
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#ooRexx
ooRexx
Parse Version v Say v fid='test.txt' x=sysfiletree(fid,a.) Say a.0 Say a.1 Say left(copies('123456789.',10),length(a.1)) Parse Var a.1 20 size . Say 'file size:' size s=charin(fid,,1000) Say length(s) Say 'file' fid 'type' fid
http://rosettacode.org/wiki/File_size
File size
Verify the size of a file called     input.txt     for a file in the current working directory, and another one in the file system root.
#Oz
Oz
declare [Path] = {Module.link ['x-oz://system/os/Path.ozf']} in {Show {Path.size "input.txt"}} {Show {Path.size "/input.txt"}}
http://rosettacode.org/wiki/File_input/output
File input/output
File input/output is part of Short Circuit's Console Program Basics selection. Task Create a file called   "output.txt",   and place in it the contents of the file   "input.txt",   via an intermediate variable. In other words, your program will demonstrate:   how to read from a file into a variable   how to write ...
#GML
GML
var file, str; file = file_text_open_read("input.txt"); str = ""; while (!file_text_eof(file)) { str += file_text_read_string(file); if (!file_text_eof(file)) { str += " "; //It is important to note that a linebreak is actually inserted here rather than a character code of some kind ...
http://rosettacode.org/wiki/Fibonacci_word
Fibonacci word
The   Fibonacci Word   may be created in a manner analogous to the   Fibonacci Sequence   as described here: Define   F_Word1   as   1 Define   F_Word2   as   0 Form     F_Word3   as   F_Word2     concatenated with   F_Word1   i.e.:   01 Form     F_Wordn   as   F_Wordn-1   concatenated with   F_wordn-...
#JavaScript
JavaScript
//makes outputting a table possible in environments //that don't support console.table() function console_table(xs) { function pad(n,s) { var res = s; for (var i = s.length; i < n; i++) res += " "; return res; }   if (xs.length === 0) console.log("No data"); ...