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/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 ... | #Pascal | Pascal | #!/usr/bin/perl
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
open my $fh_out, '>', 'output.txt' or die "could not open <output.txt> for writing: $!";
# '>' overwrites file, '>>' appends to file, just like in the shell
binmode $fh_out; # marks filehandle for binary content on... |
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 ... | #Perl | Perl | #!/usr/bin/perl
open my $fh_in, '<', 'input.txt' or die "could not open <input.txt> for reading: $!";
open my $fh_out, '>', 'output.txt' or die "could not open <output.txt> for writing: $!";
# '>' overwrites file, '>>' appends to file, just like in the shell
binmode $fh_out; # marks filehandle for binary content on... |
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-... | #Wren | Wren | import "/fmt" for Fmt
var entropy = Fn.new { |s|
var m = {}
for (c in s) {
var d = m[c]
m[c] = (d) ? d + 1 : 1
}
var hm = 0
for (k in m.keys) {
var c = m[k]
hm = hm + c * c.log2
}
var l = s.count
return l.log2 - hm/l
}
var fibWord = Fn.new { |n|
if... |
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 ... | #APL | APL |
fib←{⍵≤1:⍵ ⋄ (∇ ⍵-1)+∇ ⍵-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 |... | #bc | bc | /* Calculate the factors of n and return their count.
* This function mutates the global array f[] which will
* contain all factors of n in ascending order after the call!
*/
define f(n) {
auto i, d, h, h[], l, o
/* Local variables:
* i: Loop variable.
* d: Complementary (higher) factor to 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)... | #Klong | Klong | fft::{ff2::{[n e o p t k];n::#x;
f::{p::2:#x;e::ff2(*'p);o::ff2({x@1}'p);k::-1;
t::{k::k+1;cmul(cexp(cdiv(cmul([0 -2];(k*pi),0);n,0));x)}'o;
(e cadd't),e csub't};
:[n<2;x;f(x)]};
n::#x;k::{(2^x)<n}{1+x}:~1;n#ff2({x,0}'x,&(2^k)-n)} |
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,... | #Maxima | Maxima | mersenne_fac(p) := block([m: 2^p - 1, k: 1],
while mod(m, 2 * k * p + 1) # 0 do k: k + 1,
2 * k * p + 1
)$
mersenne_fac(929);
/* 13007 */ |
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,... | #Nim | Nim | import math
proc isPrime(a: int): bool =
if a == 2: return true
if a < 2 or a mod 2 == 0: return false
for i in countup(3, int sqrt(float a), 2):
if a mod i == 0:
return false
return true
const q = 929
if not isPrime q: quit 1
var r = q
while r > 0: r = r shl 1
var d = 2 * q + 1
while true:
var ... |
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... | #Ring | Ring |
# Project : Farey sequence
for i = 1 to 11
count = 0
see "F" + string(i) + " = "
farey(i, false)
next
see nl
for x = 100 to 1000 step 100
count = 0
see "F" + string(x) + " = "
see farey(x, false)
see nl
next
func farey(n, descending)
a = 0
b = 1
c ... |
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... | #Ruby | Ruby | def farey(n, length=false)
if length
(n*(n+3))/2 - (2..n).sum{|k| farey(n/k, true)}
else
(1..n).each_with_object([]){|k,a|(0..k).each{|m|a << Rational(m,k)}}.uniq.sort
end
end
puts 'Farey sequence for order 1 through 11 (inclusive):'
for n in 1..11
puts "F(#{n}): " + farey(n).join(", ")
end
puts 'Numb... |
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}}
... | #J | J | nacci =: (] , +/@{.)^:(-@#@]`(-#)`]) |
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.
| #IDL | IDL | result = array[where(NOT array AND 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)
... | #K | K | `0:\:{:[0=#a:{,/$(:[0=x!3;"Fizz"];:[0=x!5;"Buzz"])}@x;$x;a]}'1_!101 |
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 ... | #Phix | Phix | integer fn = open("input.txt","rb")
string txt = get_text(fn)
close(fn)
fn = open("output.txt","wb")
puts(fn,txt)
close(fn)
|
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 ... | #PHP | PHP | <?php
if (!$in = fopen('input.txt', 'r')) {
die('Could not open input file.');
}
if (!$out = fopen('output.txt', 'w')) {
die('Could not open output file.');
}
while (!feof($in)) {
$data = fread($in, 512);
fwrite($out, $data);
}
fclose($out);
fclose($in);
?> |
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-... | #zkl | zkl | fcn entropy(bs){ //binary String-->Float
len:=bs.len(); num1s:=(bs-"0").len();
T(num1s,len-num1s).filter().apply('wrap(p){ p=p.toFloat()/len; -p*p.log() })
.sum(0.0) / (2.0).log();
}
" N Length Entropy Fibword".println();
ws:=L("1","0");
foreach n in ([1..37]){
if(n>2) ws.append(ws[-1]+ws[-2]);
... |
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-... | #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET x$="1": LET y$="0": LET z$=""
20 PRINT "N, Length, Entropy, Word"
30 LET n=1
40 PRINT n;" ";LEN x$;" ";
50 LET s$=x$: LET base=2: GO SUB 1000
60 PRINT entropy
70 PRINT x$
80 LET n=2
90 PRINT n;" ";LEN y$;" ";
100 LET s$=y$: GO SUB 1000
110 PRINT entropy
120 PRINT y$
130 FOR n=1 TO 18
140 LET x$="1": LET y$="0"
1... |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow ... | #AppleScript | AppleScript | set fibs to {}
set x to (text returned of (display dialog "What fibbonaci number do you want?" default answer "3"))
set x to x as integer
repeat with y from 1 to x
if (y = 1 or y = 2) then
copy 1 to the end of fibs
else
copy ((item (y - 1) of fibs) + (item (y - 2) of fibs)) to the end of fibs
end if
end repeat
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 |... | #Befunge | Befunge | 10:p&v: >:0:g%#v_0:g\:0:g/\v
>:0:g:*`| > >0:g1+0:p
>:0:g:*-#v_0:g\>$>:!#@_.v
> ^ ^ ," "< |
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)... | #Kotlin | Kotlin | import java.lang.Math.*
class Complex(val re: Double, val im: Double) {
operator infix fun plus(x: Complex) = Complex(re + x.re, im + x.im)
operator infix fun minus(x: Complex) = Complex(re - x.re, im - x.im)
operator infix fun times(x: Double) = Complex(re * x, im * x)
operator infix fun times(x: Com... |
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,... | #Octave | Octave | % test a bit; lsb is 1 (like built-in bit* ops)
function b = bittst(n, p)
b = bitand(n, 2^(p-1)) > 0;
endfunction
function f = Mfactor(p)
% msb is the index of the first non-zero bit
[b, msb] = max(bitand(p, 2 .^ [32:-1:1]) > 0);
maxk = floor(sqrt(intmax()) / p);
for k = 1 : maxk
q = 2*p*k + 1;
if ... |
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... | #Rust | Rust | #[derive(Copy, Clone)]
struct Fraction {
numerator: u32,
denominator: u32,
}
use std::fmt;
impl fmt::Display for Fraction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}/{}", self.numerator, self.denominator)
}
}
impl Fraction {
fn new(n: u32, d: u32) -> Frac... |
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... | #Scala | Scala |
object FareySequence {
def fareySequence(n: Int, start: (Int, Int), stop: (Int, Int)): LazyList[(Int, Int)] = {
val (nominator_l, denominator_l) = start
val (nominator_r, denominator_r) = stop
val mediant = ((nominator_l + nominator_r), (denominator_l + denominator_r))
if (mediant._2 <= n) far... |
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}}
... | #Java | Java | class Fibonacci
{
public static int[] lucas(int n, int numRequested)
{
if (n < 2)
throw new IllegalArgumentException("Fibonacci value must be at least 2");
return fibonacci((n == 2) ? new int[] { 2, 1 } : lucas(n - 1, n), numRequested);
}
public static int[] fibonacci(int n, int numRequested)
... |
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.
| #J | J | (#~ f) v |
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)
... | #Kamailio_Script | Kamailio Script | # FizzBuzz
log_stderror=yes
loadmodule "pv"
loadmodule "xlog"
route {
$var(i) = 1;
while ($var(i) <= 1000) {
if ($var(i) mod 15 == 0) {
xlog("FizzBuzz\n");
} else if ($var(i) mod 5 == 0) {
xlog("Buzz\n");
} else if ($var(i) mod 3 == 0) {
xlog("Fizz\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 ... | #PicoLisp | PicoLisp | (let V (in "input.txt" (till))
(out "output.txt" (prin V)) ) |
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 ... | #Pike | Pike |
object lines = Stdio.File("input.txt")->line_iterator();
object out = Stdio.File("output.txt", "cw");
foreach(lines; int line_number; string line)
out->write(line + "\n");
|
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 ... | #Arendelle | Arendelle | ( fibonacci , 1; 1 )
[ 98 , // 100 numbers of fibonacci
( fibonacci[ @fibonacci? ] ,
@fibonacci[ @fibonacci - 1 ] + @fibonacci[ @fibonacci - 2 ]
)
"Index: | @fibonacci? | => | @fibonacci[ @fibonacci? - 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 |... | #BQN | BQN | Factors ← (1+↕)⊸(⊣/˜0=|)
•Show Factors 12345
•Show Factors 729 |
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)... | #Lambdatalk | Lambdatalk |
1) the function fft
{def fft
{lambda {:s :x}
{if {= {list.length :x} 1}
then :x
else {let { {:s :s}
{:ev {fft :s {evens :x}} }
{:od {fft :s {odds :x}} } }
{let { {:ev :ev} {:t {rotate :s :od 0 {list.length :od}}} }
{list.append {list.map Cadd :ev :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,... | #PARI.2FGP | PARI/GP | factorMersenne(p)={
forstep(q=2*p+1,sqrt(2)<<(p\2),2*p,
[1,0,0,0,0,0,1][q%8] && Mod(2, q)^p==1 && return(q)
);
1<<p-1
};
factorMersenne(929) |
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,... | #Pascal | Pascal | program FactorsMersenneNumber(input, output);
function isPrime(n: longint): boolean;
var
d: longint;
begin
isPrime := true;
if (n mod 2) = 0 then
begin
isPrime := (n = 2);
exit;
end;
if (n mod 3) = 0 then
begin
isPrime := (n = 3);
exit;
end;
d := 5;
... |
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... | #Scheme | Scheme |
(import (scheme base)
(scheme write))
;; create a generator for Farey sequence n
;; using next term formula from https://en.wikipedia.org/wiki/Farey_sequence
(define (farey-generator n)
(let ((a #f) (b 1) (c #f) (d n))
(lambda ()
(cond ((not a) ; first item in sequence
(set! a 0)... |
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}}
... | #JavaScript | JavaScript | function fib(arity, len) {
return nacci(nacci([1,1], arity, arity), arity, len);
}
function lucas(arity, len) {
return nacci(nacci([2,1], arity, arity), arity, len);
}
function nacci(a, arity, len) {
while (a.length < len) {
var sum = 0;
for (var i = Math.max(0, a.length - arity); i < a.... |
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.
| #Java | Java | int[] array = {1, 2, 3, 4, 5 };
List<Integer> evensList = new ArrayList<Integer>();
for (int i: array) {
if (i % 2 == 0) evensList.add(i);
}
int[] evens = evensList.toArray(new int[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)
... | #Kaya | Kaya | // fizzbuzz in Kaya
program fizzbuzz;
Void fizzbuzz(Int size) {
for i in [1..size] {
if (i % 15 == 0) {
putStrLn("FizzBuzz");
} else if (i % 5 == 0) {
putStrLn("Buzz");
} else if (i % 3 == 0) {
putStrLn("Fizz");
} else {
putStrLn( str... |
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 ... | #PL.2FI | PL/I |
declare in file, out file;
open file (in) title ('/INPUT.TXT,type(text),recsize(100)') input;
open file (out) title ('/OUTPUT.TXT,type(text),recsize(100') output;
do forever;
get file (in) edit (line) (L);
put file (out) edit (line) (A);
end;
|
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 ... | #Pop11 | Pop11 | lvars i_stream = discin('input.txt');
lvars o_stream = discout('output.txt');
lvars c;
while (i_stream() ->> c) /= termin do
o_stream(c);
endwhile; |
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 ... | #ARM_Assembly | ARM Assembly | fibonacci:
push {r1-r3}
mov r1, #0
mov r2, #1
fibloop:
mov r3, r2
add r2, r1, r2
mov r1, r3
sub r0, r0, #1
cmp r0, #1
bne fibloop
mov r0, r2
pop {r1-r3}
mov pc, lr |
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 |... | #Burlesque | Burlesque | blsq ) 32767 fc
{1 7 31 151 217 1057 4681 32767} |
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)... | #Liberty_BASIC | Liberty BASIC |
P =8
S =int( log( P) /log( 2) +0.9999)
Pi =3.14159265
R1 =2^S
R =R1 -1
R2 =div( R1, 2)
R4 =div( R1, 4)
R3 =R4 +R2
Dim Re( R1), Im( R1), Co( R3)
for N =0 to P -1
read dummy: Re( N) =dummy
read dummy: Im( N) =dummy
next N
data 1, 0, 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,... | #Perl | Perl | use strict;
use utf8;
sub factors {
my $n = shift;
my $p = 2;
my @out;
while ($n >= $p * $p) {
while ($n % $p == 0) {
push @out, $p;
$n /= $p;
}
$p = next_prime($p);
}
push @out, $n if $n > 1 || !@out;
@out;
}
sub next_prime {
my $p = shift;
do { $p = $p == 2 ? 3 : $p + 2 } until is_prime($p)... |
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... | #Sidef | Sidef | func farey_count(n) { # A005728
1 + sum(1..n, {|k| euler_phi(k) })
}
func farey(n) {
var seq = [0]
var (a,b,c,d) = (0,1,1,n)
while (c <= n) {
var k = (n+b)//d
(a,b,c,d) = (c, d, k*c - a, k*d - b)
seq << a/b
}
return seq
}
say "Farey sequence for order 1 throug... |
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}}
... | #jq | jq | # Input: the initial array
def nacci(arity; len):
arity as $arity | len as $len
| reduce range(length; $len) as $i
(.;
([0, (length - $arity)] | max ) as $lower
| . + [ .[ ($lower) : length] | add] ) ;
def fib(arity; len):
arity as $arity | len as $len
| [1,1] | nacci($arity; $arity) | nac... |
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.
| #JavaFX_Script | JavaFX Script | def array = [1..100];
def evens = array[n | n mod 2 == 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)
... | #KL1 | KL1 |
:- module main.
main :-
nats(100, Nats),
fizzbuzz(Nats, Output),
display(Output).
nats(Max, Out) :-
nats(Max, 1, Out).
nats(Max, Count, Out) :- Count =< Max |
Out = [Count|NewOut],
NewCount := Count + 1,
nats(Max, NewCount, NewOut).
nats(Max, Count, Out) :- Count > Max |
Out = [].
... |
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 ... | #PowerShell | PowerShell | Get-Content $PWD\input.txt | Out-File $PWD\output.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 ... | #PureBasic | PureBasic | CopyFile("input.txt","output.txt") |
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 ... | #ArnoldC | ArnoldC | IT'S SHOWTIME
HEY CHRISTMAS TREE f1
YOU SET US UP @I LIED
TALK TO THE HAND f1
HEY CHRISTMAS TREE f2
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE f3
YOU SET US UP @I LIED
STICK AROUND @NO PROBLEMO
GET TO THE CHOPPER f3
HERE IS MY INVITATION f1
GET UP f2
ENOUGH TALK
TALK TO THE HAND f3
GET TO THE CHOPPER f1
... |
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 |... | #C | C | #include <stdio.h>
#include <stdlib.h>
typedef struct {
int *list;
short count;
} Factors;
void xferFactors( Factors *fctrs, int *flist, int flix )
{
int ix, ij;
int newSize = fctrs->count + flix;
if (newSize > flix) {
fctrs->list = realloc( fctrs->list, newSize * sizeof(int));
}
... |
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)... | #Lua | Lua | -- operations on complex number
complex = {__mt={} }
function complex.new (r, i)
local new={r=r, i=i or 0}
setmetatable(new,complex.__mt)
return new
end
function complex.__mt.__add (c1, c2)
return complex.new(c1.r + c2.r, c1.i + c2.i)
end
function complex.__mt.__sub (c1, c2)
return complex.new(c1.r - ... |
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,... | #Phix | Phix | with javascript_semantics
function modpow(atom x, atom n, atom m)
atom i = n,
y = 1,
z = x
while i do
if and_bits(i,1) then
y = mod(y*z,m)
end if
z = mod(z*z,m)
i = floor(i/2)
end while
return y
end function
function mersenne_factor(integer... |
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... | #Stata | Stata | mata
function totient(n_) {
n = n_
if (n<4) {
if (n<1) return(.)
else if (n>1) return(n-1)
else return(1)
}
else {
r = 1
if (mod(n,2)==0) {
n = floor(n/2)
while (mod(n,2)==0) {
n = floor(n/2)
r = r*2
}
}
for (k=3; k*k<=n; k=k+2) {
if (mod(n,k)==0) {
r = r*(k-1)
n = floor(n/... |
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... | #Swift | Swift | class Farey {
let n: Int
init(_ x: Int) {
n = x
}
//using algorithm from wikipedia
var sequence: [(Int,Int)] {
var a = 0
var b = 1
var c = 1
var d = n
var results = [(a, b)]
while c <= n {
let k = (n + b) / d
let old... |
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}}
... | #Julia | Julia |
type NFib{T<:Integer}
n::T
klim::T
seeder::Function
end
type FState
a::Array{BigInt,1}
adex::Integer
k::Integer
end
function Base.start{T<:Integer}(nf::NFib{T})
a = nf.seeder(nf.n)
adex = 1
k = 1
return FState(a, adex, k)
end
function Base.done{T<:Integer}(nf::NFib{T}, fs... |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #JavaScript | JavaScript | var arr = [1,2,3,4,5];
var evens = arr.filter(function(a) {return a % 2 == 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)
... | #Klong | Klong |
{:[0=x!15;:FizzBuzz:|0=x!5;:Buzz:|0=x!3;:Fizz;x]}'1+!100
|
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 ... | #Python | Python | import shutil
shutil.copyfile('input.txt', 'output.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 ... | #Quackery | Quackery | $ "input.txt" sharefile drop
temp put
temp share
$ "output.txt" putfile drop
|
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 ... | #Arturo | Arturo | fib: $[x][
if? x<2 [1]
else [(fib x-1) + (fib x-2)]
]
loop 1..25 [x][
print ["Fibonacci of" x "=" fib x]
] |
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 |... | #C.23 | C# | static void Main (string[] args) {
do {
Console.WriteLine ("Number:");
Int64 p = 0;
do {
try {
p = Convert.ToInt64 (Console.ReadLine ());
break;
} catch (Exception) { }
} while (true);
Console.WriteLine ("For 1 throu... |
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)... | #Maple | Maple |
with( DiscreteTransforms ):
FourierTransform( <1,1,1,1,0,0,0,0>, normalization=none );
|
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,... | #PHP | PHP | echo 'M929 has a factor: ', mersenneFactor(929), '</br>';
function mersenneFactor($p) {
$limit = sqrt(pow(2, $p) - 1);
for ($k = 1; 2 * $p * $k - 1 < $limit; $k++) {
$q = 2 * $p * $k + 1;
if (isPrime($q) && ($q % 8 == 1 || $q % 8 == 7) && bcpowmod("2", "$p", "$q") == "1") {
retur... |
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... | #Tcl | Tcl | package require Tcl 8.6
proc farey {n} {
set nums [lrepeat [expr {$n+1}] 1]
set result {{0 1}}
for {set found 1} {$found} {} {
set nj [lindex $nums [set j 1]]
for {set found 0;set i 1} {$i <= $n} {incr i} {
if {[lindex $nums $i]*$j < $nj*$i} {
set nj [lindex $nums [set j $i]]
set found 1
}... |
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}}
... | #Kotlin | Kotlin | // version 1.1.2
fun fibN(initial: IntArray, numTerms: Int) : IntArray {
val n = initial.size
require(n >= 2 && numTerms >= 0)
val fibs = initial.copyOf(numTerms)
if (numTerms <= n) return fibs
for (i in n until numTerms) {
var sum = 0
for (j in i - n until i) sum += fibs[j]
... |
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.
| #jq | jq | (1,2,3,4,5,6,7,8,9) | select(. % 2 == 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)
... | #Kotlin | Kotlin | fun fizzBuzz() {
for (number in 1..100) {
println(
when {
number % 15 == 0 -> "FizzBuzz"
number % 3 == 0 -> "Fizz"
number % 5 == 0 -> "Buzz"
else -> number
}
)
}
} |
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 ... | #R | R | src <- file("input.txt", "r")
dest <- file("output.txt", "w")
fc <- readLines(src, -1)
writeLines(fc, dest)
close(src); close(dest) |
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 ... | #Racket | Racket | #lang racket
(define file-content
(with-input-from-file "input.txt"
(lambda ()
(let loop ((lst null))
(define new (read-char))
(if (eof-object? new)
(apply string lst)
(loop (append lst (list new))))))))
(with-output-to-file "output.txt"
(lambda ()
(write file... |
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 ... | #AsciiDots | AsciiDots |
/--#$--\
| |
>-*>{+}/
| \+-/
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 |... | #C.2B.2B | C++ | #include <iostream>
#include <iomanip>
#include <vector>
#include <algorithm>
#include <iterator>
std::vector<int> GenerateFactors(int n) {
std::vector<int> factors = { 1, n };
for (int i = 2; i * i <= n; ++i) {
if (n % i == 0) {
factors.push_back(i);
if (i * i != n)
... |
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)... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
Fourier[{1,1,1,1,0,0,0,0}, FourierParameters->{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,... | #PicoLisp | PicoLisp | (de **Mod (X Y N)
(let M 1
(loop
(when (bit? 1 Y)
(setq M (% (* M X) N)) )
(T (=0 (setq Y (>> 1 Y)))
M )
(setq X (% (* X X) N)) ) ) )
(de prime? (N)
(or
(= N 2)
(and
(> N 1)
(bit? 1 N)
(let S (sqrt N)
(fo... |
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,... | #Prolog | Prolog |
mersenne_factor(P, F) :-
prime(P),
once((
between(1, 100_000, K), % Fail if we can't find a small factor
Q is 2*K*P + 1,
test_factor(Q, P, F))).
test_factor(Q, P, prime) :- Q*Q > (1 << P - 1), !.
test_factor(Q, P, Q) :-
R is Q /\ 7, member(R, [1, 7]),
prime(Q),
powm(2, P... |
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... | #Vala | Vala | struct Fraction {
public uint d;
public uint n;
}
void farey(uint n) {
Fraction f1 = {0, 1};
Fraction f2 = {1, n};
print("0/1 1/%u ", n);
while (f2.n > 1) {
var k = (n + f1.n) / f2.n;
var aux = f1;
f1 = f2;
f2 = {f2.d * k - aux.d, f2.n * k - aux.n};
print("%u/%u ", f2.d, f2.n);
}
p... |
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}}
... | #Lua | Lua | function nStepFibs (seq, limit)
local iMax, sum = #seq - 1
while #seq < limit do
sum = 0
for i = 0, iMax do sum = sum + seq[#seq - i] end
table.insert(seq, sum)
end
return seq
end
local fibSeqs = {
{name = "Fibonacci", values = {1, 1} },
{name = "Tribonacci", valu... |
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.
| #Julia | Julia | @show filter(iseven, 1:10) |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
... | #KQL | KQL |
range i from 1 to 100 step 1
| project Result =
case(
i % 15 == 0, "FizzBuzz",
i % 3 == 0, "Fizz",
i % 5 == 0, "Buzz",
tostring(i)
)
|
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 ... | #Raku | Raku | spurt "output.txt", slurp "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 ... | #RapidQ | RapidQ | $INCLUDE "rapidq.inc"
DIM File1 AS QFileStream
DIM File2 AS QFileStream
File1.Open("input.txt", fmOpenRead)
File2.Open("output.txt", fmCreate)
WHILE NOT File1.EOF
data$ = File1.ReadLine
File2.WriteLine(data$)
WEND
File1.Close
File2.Close |
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 ... | #ATS | ATS |
fun fib_rec(n: int): int =
if n >= 2 then fib_rec(n-1) + fib_rec(n-2) else n
|
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 |... | #Ceylon | Ceylon | shared void run() {
{Integer*} getFactors(Integer n) =>
(1..n).filter((Integer element) => element.divides(n));
for(Integer i in 1..100) {
print("the factors of ``i`` are ``getFactors(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)... | #MATLAB_.2F_Octave | MATLAB / Octave | fft([1,1,1,1,0,0,0,0]')
|
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,... | #Python | Python | def is_prime(number):
return True # code omitted - see Primality by Trial Division
def m_factor(p):
max_k = 16384 / p # arbitrary limit; since Python automatically uses long's, it doesn't overflow
for k in xrange(max_k):
q = 2*p*k + 1
if not is_prime(q):
continue
elif q... |
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,... | #Racket | Racket |
#lang racket
(define (number->digits n)
(map (compose1 string->number string)
(string->list (number->string n 2))))
(define (modpow exp base)
(for/fold ([square 1])
([d (number->digits exp)])
(modulo (* (if (= d 1) 2 1) square square) base)))
; Search through all integers from 1 on to find th... |
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... | #Vlang | Vlang | struct Frac {
num int
den int
}
fn (f Frac) str() string {
return "$f.num/$f.den"
}
fn f(l Frac, r Frac, n int) {
m := Frac{l.num + r.num, l.den + r.den}
if m.den <= n {
f(l, m, n)
print("$m ")
f(m, r, n)
}
}
fn main() {
// task 1. solution by recursive generat... |
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}}
... | #Maple | Maple | numSequence := proc(initValues :: Array)
local n, i, values;
n := numelems(initValues);
values := copy(initValues);
for i from (n+1) to 15 do
values(i) := add(values[i-n..i-1]);
end do;
return values;
end proc:
initValues := Array([1]):
for i from 2 to 10 do
initValues(i) := add(initValues):
printf ("nacci(... |
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.
| #K | K | / even is a boolean function
even:{0=x!2}
even 1 2 3 4 5
0 1 0 1 0
/ filtering the even numbers
a@&even'a:1+!10
2 4 6 8 10
/ as a function
evens:{x@&even'x}
a:10?100
45 5 79 77 44 15 83 88 33 99
evens a
44 88 |
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)
... | #KSI | KSI |
`plain
[1 100] `for pos : n ~
out = []
n `mod 3 == 0 ? out.# = 'Fizz' ;
n `mod 5 == 0 ? out.# = 'Buzz' ;
(out `or n) #write_ln #
;
|
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 ... | #Raven | Raven | 'input.txt' read 'output.txt' write |
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 ... | #REALbasic | REALbasic |
Sub WriteToFile(input As FolderItem, output As FolderItem)
Dim tis As TextInputStream
Dim tos As TextOutputStream
tis = tis.Open(input)
tos = tos.Create(output)
While Not tis.EOF
tos.WriteLine(tis.ReadLine)
Wend
tis.Close
tos.Close
End Sub
|
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 ... | #AutoHotkey | AutoHotkey | Loop, 5
MsgBox % fib(A_Index)
Return
fib(n)
{
If (n < 2)
Return n
i := last := this := 1
While (i <= n)
{
new := last + this
last := this
this := new
i++
}
Return this
} |
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 |... | #Chapel | Chapel | iter factors(n) {
for i in 1..floor(sqrt(n)):int {
if n % i == 0 then {
yield i;
yield n / 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)... | #Maxima | Maxima | load(fft)$
fft([1, 2, 3, 4]);
[2.5, -0.5 * %i - 0.5, -0.5, 0.5 * %i - 0.5] |
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,... | #Raku | Raku | sub mtest($bits, $p) {
my @bits = $bits.base(2).comb;
loop (my $sq = 1; @bits; $sq %= $p) {
$sq ×= $sq;
$sq += $sq if 1 == @bits.shift;
}
$sq == 1;
}
for flat 2 .. 60, 929 -> $m {
next unless is-prime($m);
my $f = 0;
my $x = 2**$m - 1;
my $q;
for 1..* -> $k {
... |
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... | #Wren | Wren | import "/math" for Int
import "/trait" for Stepped
import "/fmt" for Fmt
import "/rat" for Rat
var f //recursive
f = Fn.new { |l, r, n|
var m = Rat.new(l.num + r.num, l.den + r.den)
if (m.den <= n) {
f.call(l, m, n)
System.write("%(m) ")
f.call(m, r, n)
}
}
/* Task 1: solution by... |
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}}
... | #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language |
f2=Function[{l,k},
Module[{n=Length@l,m},
m=SparseArray[{{i_,j_}/;i==1||i==j+1->1},{n,n}];
NestList[m.#&,l,k]]];
Table[Last/@f2[{1,1}~Join~Table[0,{n-2}],15+n][[-18;;]],{n,2,10}]//TableForm
Table[Last/@f2[{1,2}~Join~Table[0,{n-2}],15+n][[-18;;]],{n,2,10}]//TableForm
|
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.
| #Kotlin | Kotlin | // version 1.0.5-2
fun main(args: Array<String>) {
val array = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9)
println(array.joinToString(" "))
val filteredArray = array.filter{ it % 2 == 0 }
println(filteredArray.joinToString(" "))
val mutableList = array.toMutableList()
mutableList.retainAll { it % 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)
... | #LabVIEW | LabVIEW |
1. direct:
{S.map
{lambda {:i}
{if {= {% :i 15} 0}
then fizzbuzz
else {if {= {% :i 3} 0}
then fizz
else {if {= {% :i 5} 0}
then buzz
else :i}}}}
{S.serie 1 100}}
-> 1 2 fizz 4 buzz fizz 7 8 fizz buzz 11 fizz 13 14 fizzbuzz 16 17 fizz 19 buzz fizz 22 23 fizz buzz 26 fizz 28 29 fizzbuzz 31... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.