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/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)) of the complex result.
The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| #Tcl | Tcl | package require math::constants
package require math::fourier
math::constants::constants pi
# Helper functions
proc wave {samples cycles} {
global pi
set wave {}
set factor [expr {2*$pi * $cycles / $samples}]
for {set i 0} {$i < $samples} {incr i} {
lappend wave [expr {sin($factor * $i)}]
}
return $wave
}
proc printwave {waveName {format "%7.3f"}} {
upvar 1 $waveName wave
set out [format "%-6s" ${waveName}:]
foreach value $wave {
append out [format $format $value]
}
puts $out
}
proc waveMagnitude {wave} {
set out {}
foreach value $wave {
lassign $value re im
lappend out [expr {hypot($re, $im)}]
}
return $out
}
set wave [wave 16 3]
printwave wave
# Uses FFT if input length is power of 2, and a less efficient algorithm otherwise
set fft [math::fourier::dft $wave]
# Convert to magnitudes for printing
set fft2 [waveMagnitude $fft]
printwave fft2 |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Sidef | Sidef | func fib(n, xs=[1], k=20) {
loop {
var len = xs.len
len >= k && break
xs << xs.ft(max(0, len - n)).sum
}
return xs
}
for i in (2..10) {
say fib(i).join(' ')
}
say fib(2, [2, 1]).join(' ') |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Nim | Nim | import sequtils
let values = toSeq(0..9)
# Filtering by returning a new sequence.
# - using an explicit filtering procedure.
echo "Even values: ", values.filter(proc(x: int): bool = x mod 2 == 0)
# - using a predicate.
echo "Odd values: ", values.filterIt(it mod 2 == 1)
# Filtering by modifying the sequence.
# - using an explicit filtering procedure.
var v1 = toSeq(0..9)
v1.keepIf(proc(x: int): bool = x mod 2 == 0)
echo "Even values: ", v1
# - using a predicate.
var v2 = toSeq(0..9)
v2.keepItIf(it mod 2 != 0)
echo "Odd values: ", v2 |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #MEL | MEL | for($i=1; $i<=100; $i++)
{
if($i % 15 == 0)
print "FizzBuzz\n";
else if ($i % 3 == 0)
print "Fizz\n";
else if ($i % 5 == 0)
print "Buzz\n";
else
print ($i + "\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 and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Chapel | Chapel | iter fib() {
var a = 0, b = 1;
while true {
yield a;
(a, b) = (b, b + a);
}
} |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Forth | Forth | : factors dup 2/ 1+ 1 do dup i mod 0= if i swap then loop ;
: .factors factors begin dup dup . 1 <> while drop repeat drop cr ;
45 .factors
53 .factors
64 .factors
100 .factors |
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)) of the complex result.
The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| #Ursala | Ursala | #import nat
#import flo
f = <1+0j,1+0j,1+0j,1+0j,0+0j,0+0j,0+0j,0+0j> # complex sequence of 4 1's and 4 0's
g = c..mul^*D(sqrt+ float+ length,..u_fw_dft) f # its fft
#cast %jLW
t = (f,g) |
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)) of the complex result.
The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| #Vlang | Vlang | import math.complex
import math
fn ditfft2(x []f64, mut y []Complex, n int, s int) {
if n == 1 {
y[0] = complex(x[0], 0)
return
}
ditfft2(x, mut y, n/2, 2*s)
ditfft2(x[s..], mut y[n/2..], n/2, 2*s)
for k := 0; k < n/2; k++ {
tf := cmplx.Rect(1, -2*math.pi*f64(k)/f64(n)) * y[k+n/2]
y[k], y[k+n/2] = y[k]+tf, y[k]-tf
}
}
fn main() {
x := [f64(1), 1, 1, 1, 0, 0, 0, 0]
mut y := []Complex{len: x.len}
ditfft2(x, mut y, x.len, 1)
for c in y {
println("${c:8.4f}")
}
} |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Tailspin | Tailspin |
templates fibonacciNstep&{N:}
templates next
@: $(1);
$(2..last)... -> @: $ + $@;
[ $(2..last)..., $@ ] !
end next
@: $;
1..$N -> #
<>
$@(1) !
@: $@ -> next;
end fibonacciNstep
[1,1] -> fibonacciNstep&{N:10} -> '$; ' -> !OUT::write
'
' -> !OUT::write
[1,1,2] -> fibonacciNstep&{N:10} -> '$; ' -> !OUT::write
'
' -> !OUT::write
[1,1,2,4] -> fibonacciNstep&{N:10} -> '$; ' -> !OUT::write
'
' -> !OUT::write
[2,1] -> fibonacciNstep&{N:10} -> '$; ' -> !OUT::write
'
' -> !OUT::write
|
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.
| #Objeck | Objeck |
use Structure;
bundle Default {
class Evens {
function : Main(args : String[]) ~ Nil {
values := IntVector->New([1, 2, 3, 4, 5]);
f := Filter(Int) ~ Bool;
evens := values->Filter(f);
each(i : evens) {
evens->Get(i)->PrintLine();
};
}
function : Filter(v : Int) ~ Bool {
return v % 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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Mercury | Mercury | :- module fizzbuzz.
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
:- implementation.
:- import_module int, string, bool.
:- func fizz(int) = bool.
fizz(N) = ( if N mod 3 = 0 then yes else no ).
:- func buzz(int) = bool.
buzz(N) = ( if N mod 5 = 0 then yes else no ).
% N 3? 5?
:- func fizzbuzz(int, bool, bool) = string.
fizzbuzz(_, yes, yes) = "FizzBuzz".
fizzbuzz(_, yes, no) = "Fizz".
fizzbuzz(_, no, yes) = "Buzz".
fizzbuzz(N, no, no) = from_int(N).
main(!IO) :- main(1, 100, !IO).
:- pred main(int::in, int::in, io::di, io::uo) is det.
main(N, To, !IO) :-
io.write_string(fizzbuzz(N, fizz(N), buzz(N)), !IO),
io.nl(!IO),
( if N < To then
main(N + 1, To, !IO)
else
true
). |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Chef | Chef | Stir-Fried Fibonacci Sequence.
An unobfuscated iterative implementation.
It prints the first N + 1 Fibonacci numbers,
where N is taken from standard input.
Ingredients.
0 g last
1 g this
0 g new
0 g input
Method.
Take input from refrigerator.
Put this into 4th mixing bowl.
Loop the input.
Clean the 3rd mixing bowl.
Put last into 3rd mixing bowl.
Add this into 3rd mixing bowl.
Fold new into 3rd mixing bowl.
Clean the 1st mixing bowl.
Put this into 1st mixing bowl.
Fold last into 1st mixing bowl.
Clean the 2nd mixing bowl.
Put new into 2nd mixing bowl.
Fold this into 2nd mixing bowl.
Put new into 4th mixing bowl.
Endloop input until looped.
Pour contents of the 4th mixing bowl into baking dish.
Serves 1. |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Fortran | Fortran | program Factors
implicit none
integer :: i, number
write(*,*) "Enter a number between 1 and 2147483647"
read*, number
do i = 1, int(sqrt(real(number))) - 1
if (mod(number, i) == 0) write (*,*) i, number/i
end do
! Check to see if number is a square
i = int(sqrt(real(number)))
if (i*i == number) then
write (*,*) i
else if (mod(number, i) == 0) then
write (*,*) i, number/i
end if
end program |
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)) of the complex result.
The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| #Wren | Wren | import "/complex" for Complex
import "/fmt" for Fmt
var ditfft2 // recursive
ditfft2 = Fn.new {|x, y, n, s|
if (n == 1) {
y[0] = Complex.new(x[0], 0)
return
}
var hn = (n/2).floor
ditfft2.call(x, y, hn, 2*s)
var z = y[hn..-1]
ditfft2.call(x[s..-1], z, hn, 2*s)
for (i in hn...y.count) y[i] = z[i-hn]
for (k in 0...hn) {
var tf = Complex.fromPolar(1, -2 * Num.pi * k / n) * y[k + hn]
var t = y[k]
y[k] = y[k] + tf
y[k + hn] = t - tf
}
}
var x = [1, 1, 1, 1, 0, 0, 0, 0]
var y = List.filled(x.count, null)
for (i in 0...y.count) y[i] = Complex.zero
ditfft2.call(x, y, x.count, 1)
for (c in y) Fmt.print("$6.4z", c) |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Tcl | Tcl | package require Tcl 8.6
proc fibber {args} {
coroutine fib[incr ::fibs]=[join $args ","] apply {fn {
set n [info coroutine]
foreach f $fn {
if {![yield $n]} return
set n $f
}
while {[yield $n]} {
set fn [linsert [lreplace $fn 0 0] end [set n [+ {*}$fn]]]
}
} ::tcl::mathop} $args
}
proc print10 cr {
for {set i 1} {$i <= 10} {incr i} {
lappend out [$cr true]
}
puts \[[join [lappend out ...] ", "]\]
$cr false
}
puts "FIBONACCI"
print10 [fibber 1 1]
puts "TRIBONACCI"
print10 [fibber 1 1 2]
puts "TETRANACCI"
print10 [fibber 1 1 2 4]
puts "LUCAS"
print10 [fibber 2 1] |
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.
| #Objective-C | Objective-C | NSArray *numbers = [NSArray arrayWithObjects:[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:3],
[NSNumber numberWithInt:4],
[NSNumber numberWithInt:5], nil];
NSArray *evens = [numbers objectsAtIndexes:[numbers indexesOfObjectsPassingTest:
^BOOL(id obj, NSUInteger idx, BOOL *stop) { return [obj intValue] % 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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Metafont | Metafont | for i := 1 upto 100:
message if i mod 15 = 0: "FizzBuzz" &
elseif i mod 3 = 0: "Fizz" &
elseif i mod 5 = 0: "Buzz" &
else: decimal i & fi "";
endfor
end |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Clio | Clio | fn fib n:
if n < 2: n
else: (n - 1 -> fib) + (n - 2 -> fib)
[0:100] -> * fib -> * print |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Sub printFactors(n As Integer)
If n < 1 Then Return
Print n; " =>";
For i As Integer = 1 To n / 2
If n Mod i = 0 Then Print i; " ";
Next i
Print n
End Sub
printFactors(11)
printFactors(21)
printFactors(32)
printFactors(45)
printFactors(67)
printFactors(96)
Print
Print "Press any key to quit"
Sleep |
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)) of the complex result.
The classic version is the recursive Cooley–Tukey FFT. Wikipedia has pseudo-code for that.
Further optimizations are possible but not required.
| #zkl | zkl | var [const] GSL=Import("zklGSL"); // libGSL (GNU Scientific Library)
v:=GSL.ZVector(8).set(1,1,1,1);
GSL.FFT(v).toList().concat("\n").println(); // in place |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #VBA | VBA | Option Explicit
Sub Main()
Dim temp$, T() As Long, i&
'Fibonacci:
T = Fibonacci_Step(1, 15, 1)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Fibonacci: " & Mid(temp, 3)
temp = ""
'Tribonacci:
T = Fibonacci_Step(1, 15, 2)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Tribonacci: " & Mid(temp, 3)
temp = ""
'Tetranacci:
T = Fibonacci_Step(1, 15, 3)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Tetranacci: " & Mid(temp, 3)
temp = ""
'Lucas:
T = Fibonacci_Step(1, 15, 1, 2)
For i = LBound(T) To UBound(T)
temp = temp & ", " & T(i)
Next
Debug.Print "Lucas: " & Mid(temp, 3)
temp = ""
End Sub
Private Function Fibonacci_Step(First As Long, Count As Long, S As Long, Optional Second As Long) As Long()
Dim T() As Long, R() As Long, i As Long, Su As Long, C As Long
If Second <> 0 Then S = 1
ReDim T(1 - S To Count)
For i = LBound(T) To 0
T(i) = 0
Next i
T(1) = IIf(Second <> 0, Second, 1)
T(2) = 1
For i = 3 To Count
Su = 0
C = S + 1
Do While C >= 0
Su = Su + T(i - C)
C = C - 1
Loop
T(i) = Su
Next
ReDim R(1 To Count)
For i = 1 To Count
R(i) = T(i)
Next
Fibonacci_Step = R
End Function |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #OCaml | OCaml | let lst = [1;2;3;4;5;6]
let even_lst = List.filter (fun x -> x mod 2 = 0) lst |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Microsoft_Small_Basic | Microsoft Small Basic |
For n = 1 To 100
op = ""
If Math.Remainder(n, 3) = 0 Then
op = "Fizz"
EndIf
IF Math.Remainder(n, 5) = 0 Then
op = text.Append(op, "Buzz")
EndIf
If op = "" Then
TextWindow.WriteLine(n)
Else
TextWindow.WriteLine(op)
EndIf
EndFor
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Clojure | Clojure | (defn fibs []
(map first (iterate (fn [[a b]] [b (+ a b)]) [0 1]))) |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Frink | Frink | allFactors[n] |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #VBScript | VBScript |
'function arguments:
'init - initial series of the sequence(e.g. "1,1")
'rep - how many times the sequence repeats - init
Function generate_seq(init,rep)
token = Split(init,",")
step_count = UBound(token)
rep = rep - (UBound(token) + 1)
out = init
For i = 1 To rep
sum = 0
n = step_count
Do While n >= 0
sum = sum + token(UBound(token)-n)
n = n - 1
Loop
'add the next number to the sequence
ReDim Preserve token(UBound(token) + 1)
token(UBound(token)) = sum
out = out & "," & sum
Next
generate_seq = out
End Function
WScript.StdOut.Write "fibonacci: " & generate_seq("1,1",15)
WScript.StdOut.WriteLine
WScript.StdOut.Write "tribonacci: " & generate_seq("1,1,2",15)
WScript.StdOut.WriteLine
WScript.StdOut.Write "tetranacci: " & generate_seq("1,1,2,4",15)
WScript.StdOut.WriteLine
WScript.StdOut.Write "lucas: " & generate_seq("2,1",15)
WScript.StdOut.WriteLine
|
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.
| #Octave | Octave | arr = [1:100];
evennums = arr( mod(arr, 2) == 0 );
disp(evennums); |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #min | min | 0 (
succ false :hit
(3 mod 0 ==) ("Fizz" print! true @hit) when
(5 mod 0 ==) ("Buzz" print! true @hit) when
(hit) (print) unless newline
) 100 times |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #CLU | CLU | % Generate Fibonacci numbers
fib = iter () yields (int)
a: int := 0
b: int := 1
while true do
yield (a)
a, b := b, a+b
end
end fib
% Grab the n'th value from an iterator
nth = proc [T: type] (g: itertype () yields (T), n: int) returns (T)
for v: T in g() do
if n<=0 then return (v) end
n := n-1
end
end nth
% Print a few values
start_up = proc ()
po: stream := stream$primary_output()
% print values coming out of the fibonacci iterator
% (which are generated one after the other without delay)
count: int := 0
for f: int in fib() do
stream$putl(po, "F(" || int$unparse(count) || ") = " || int$unparse(f))
count := count + 1
if count = 15 then break end
end
% print a few random fibonacci numbers
% (to do this it has to restart at the beginning for each
% number, making it O(N))
fibs: sequence[int] := sequence[int]$[20,30,50]
for n: int in sequence[int]$elements(fibs) do
stream$putl(po, "F(" || int$unparse(n) || ") = "
|| int$unparse(nth[int](fib, n)))
end
end start_up |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #FunL | FunL | def factors( n ) = {d | d <- 1..n if d|n} |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Visual_Basic_.NET | Visual Basic .NET | ' Fibonacci n-step number sequences - VB.Net
Public Class FibonacciNstep
Const nmax = 20
Sub Main()
Dim bonacci As String() = {"", "", "Fibo", "tribo", "tetra", "penta", "hexa"}
Dim i As Integer
'Fibonacci:
For i = 2 To 6
Debug.Print(bonacci(i) & "nacci: " & FibonacciN(i, nmax))
Next i
'Lucas:
Debug.Print("Lucas: " & FibonacciN(2, nmax, 2))
End Sub 'Main
Private Function FibonacciN(iStep As Long, Count As Long, Optional First As Long = 0) As String
Dim i, j As Integer, Sigma As Long, c As String
Dim T(nmax) As Long
T(1) = IIf(First = 0, 1, First)
T(2) = 1
For i = 3 To Count
Sigma = 0
For j = i - 1 To i - iStep Step -1
If j > 0 Then
Sigma += T(j)
End If
Next j
T(i) = Sigma
Next i
c = ""
For i = 1 To nmax
c &= ", " & T(i)
Next i
Return Mid(c, 3)
End Function 'FibonacciN
End Class 'FibonacciNstep |
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.
| #Oforth | Oforth | 100 seq filter(#isEven) |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #MiniScript | MiniScript | for i in range(1,100)
if i % 15 == 0 then
print "FizzBuzz"
else if i % 3 == 0 then
print "Fizz"
else if i % 5 == 0 then
print "Buzz"
else
print i
end if
end for |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #CMake | CMake | set_property(GLOBAL PROPERTY fibonacci_0 0)
set_property(GLOBAL PROPERTY fibonacci_1 1)
set_property(GLOBAL PROPERTY fibonacci_next 2)
# var = nth number in Fibonacci sequence.
function(fibonacci var n)
# If the sequence is too short, compute more Fibonacci numbers.
get_property(next GLOBAL PROPERTY fibonacci_next)
if(NOT next GREATER ${n})
# a, b = last 2 Fibonacci numbers
math(EXPR i "${next} - 2")
get_property(a GLOBAL PROPERTY fibonacci_${i})
math(EXPR i "${next} - 1")
get_property(b GLOBAL PROPERTY fibonacci_${i})
while(NOT next GREATER ${n})
math(EXPR i "${a} + ${b}") # i = next Fibonacci number
set_property(GLOBAL PROPERTY fibonacci_${next} ${i})
set(a ${b})
set(b ${i})
math(EXPR next "${next} + 1")
endwhile()
set_property(GLOBAL PROPERTY fibonacci_next ${next})
endif()
get_property(answer GLOBAL PROPERTY fibonacci_${n})
set(${var} ${answer} PARENT_SCOPE)
endfunction(fibonacci) |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #FutureBasic | FutureBasic | window 1, @"Factors of an Integer", (0,0,1000,270)
clear local mode
local fn IntegerFactors( f as long ) as CFStringRef
long i, s, l(100), c = 0
CFStringRef factorStr = @""
for i = 1 to sqr(f)
if ( f mod i == 0 )
l(c) = i
c++
if ( f != i ^ 2 )
l(c) = ( f / i )
c++
end if
end if
next i
s = 1
while ( s = 1 )
s = 0
for i = 0 to c-1
if l(i) > l(i+1) and l(i+1) != 0
swap l(i), l(i+1)
s = 1
end if
next i
wend
for i = 0 to c - 1
if ( i < c - 1 )
factorStr = fn StringWithFormat( @"%@ %ld, ", factorStr, l(i) )
else
factorStr = fn StringWithFormat( @"%@ %ld", factorStr, l(i) )
end if
next
end fn = factorStr
print @"Factors of 25 are:"; fn IntegerFactors( 25 )
print @"Factors of 45 are:"; fn IntegerFactors( 45 )
print @"Factors of 103 are:"; fn IntegerFactors( 103 )
print @"Factors of 760 are:"; fn IntegerFactors( 760 )
print @"Factors of 12345 are:"; fn IntegerFactors( 12345 )
print @"Factors of 32766 are:"; fn IntegerFactors( 32766 )
print @"Factors of 32767 are:"; fn IntegerFactors( 32767 )
print @"Factors of 57097 are:"; fn IntegerFactors( 57097 )
print @"Factors of 12345678 are:"; fn IntegerFactors( 12345678 )
print @"Factors of 32434243 are:"; fn IntegerFactors( 32434243 )
HandleEvents |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Vlang | Vlang | fn fib_n(initial []int, num_terms int) []int {
n := initial.len
if n < 2 || num_terms < 0 {panic("Invalid argument(s).")}
if num_terms <= n {return initial}
mut fibs := []int{len:num_terms}
for i in 0..n {
fibs[i] = initial[i]
}
for i in n..num_terms {
mut sum := 0
for j in i-n..i {
sum = sum + fibs[j]
}
fibs[i] = sum
}
return fibs
}
fn main(){
names := [
"fibonacci", "tribonacci", "tetranacci", "pentanacci", "hexanacci",
"heptanacci", "octonacci", "nonanacci", "decanacci"
]
initial := [1, 1, 2, 4, 8, 16, 32, 64, 128, 256]
println(" n name values")
mut values := fib_n([2, 1], 15)
print(" 2 ${'lucas':-10}")
println(values.map('${it:4}').join(' '))
for i in 0..names.len {
values = fib_n(initial[0..i + 2], 15)
print("${i+2:2} ${names[i]:-10}")
println(values.map('${it:4}').join(' '))
}
} |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Ol | Ol |
(filter even? '(1 2 3 4 5 6 7 8 9 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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #MIPS_Assembly | MIPS Assembly |
#################################
# Fizz Buzz #
# MIPS Assembly targetings MARS #
# By Keith Stellyes #
# August 24, 2016 #
#################################
# $a0 left alone for printing
# $a1 stores our counter
# $a2 is 1 if not evenly divisible
.data
fizz: .asciiz "Fizz\n"
buzz: .asciiz "Buzz\n"
fizzbuzz: .asciiz "FizzBuzz\n"
newline: .asciiz "\n"
.text
loop:
beq $a1,100,exit
add $a1,$a1,1
#test for counter mod 15 ("FIZZBUZZ")
div $a2,$a1,15
mfhi $a2
bnez $a2,loop_not_fb #jump past the fizzbuzz print logic if NOT MOD 15
#### PRINT FIZZBUZZ: ####
li $v0,4 #set syscall arg to PRINT_STRING
la $a0,fizzbuzz #set the PRINT_STRING arg to fizzbuzz
syscall #call PRINT_STRING
j loop #return to start
#### END PRINT FIZZBUZZ ####
loop_not_fb:
div $a2,$a1,3 #divide $a1 (our counter) by 3 and store remainder in HI
mfhi $a2 #retrieve remainder (result of MOD)
bnez $a2, loop_not_f #jump past the fizz print logic if NOT MOD 3
#### PRINT FIZZ ####
li $v0,4
la $a0,fizz
syscall
j loop
#### END PRINT FIZZ ####
loop_not_f:
div $a2,$a1,5
mfhi $a2
bnez $a2,loop_not_b
#### PRINT BUZZ ####
li $v0,4
la $a0,buzz
syscall
j loop
#### END PRINT BUZZ ####
loop_not_b:
#### PRINT THE INTEGER ####
li $v0,1 #set syscall arg to PRINT_INTEGER
move $a0,$a1 #set PRINT_INTEGER arg to contents of $a1
syscall #call PRINT_INTEGER
### PRINT THE NEWLINE CHAR ###
li $v0,4 #set syscall arg to PRINT_STRING
la $a0,newline
syscall
j loop #return to beginning
exit:
li $v0,10
syscall
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #COBOL | COBOL | Program-ID. Fibonacci-Sequence.
Data Division.
Working-Storage Section.
01 FIBONACCI-PROCESSING.
05 FIBONACCI-NUMBER PIC 9(36) VALUE 0.
05 FIB-ONE PIC 9(36) VALUE 0.
05 FIB-TWO PIC 9(36) VALUE 1.
01 DESIRED-COUNT PIC 9(4).
01 FORMATTING.
05 INTERM-RESULT PIC Z(35)9.
05 FORMATTED-RESULT PIC X(36).
05 FORMATTED-SPACE PIC x(35).
Procedure Division.
000-START-PROGRAM.
Display "What place of the Fibonacci Sequence would you like (<173)? " with no advancing.
Accept DESIRED-COUNT.
If DESIRED-COUNT is less than 1
Stop run.
If DESIRED-COUNT is less than 2
Move FIBONACCI-NUMBER to INTERM-RESULT
Move INTERM-RESULT to FORMATTED-RESULT
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT
Display FORMATTED-RESULT
Stop run.
Subtract 1 from DESIRED-COUNT.
Move FIBONACCI-NUMBER to INTERM-RESULT.
Move INTERM-RESULT to FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
Display FORMATTED-RESULT.
Perform 100-COMPUTE-FIBONACCI until DESIRED-COUNT = zero.
Stop run.
100-COMPUTE-FIBONACCI.
Compute FIBONACCI-NUMBER = FIB-ONE + FIB-TWO.
Move FIB-TWO to FIB-ONE.
Move FIBONACCI-NUMBER to FIB-TWO.
Subtract 1 from DESIRED-COUNT.
Move FIBONACCI-NUMBER to INTERM-RESULT.
Move INTERM-RESULT to FORMATTED-RESULT.
Unstring FORMATTED-RESULT delimited by all spaces into FORMATTED-SPACE,FORMATTED-RESULT.
Display FORMATTED-RESULT. |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #GAP | GAP | # Built-in function
DivisorsInt(Factorial(5));
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]
# A possible implementation, not suitable to large n
div := n -> Filtered([1 .. n], k -> n mod k = 0);
div(Factorial(5));
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ]
# Another implementation, usable for large n (if n can be factored quickly)
div2 := function(n)
local f, p;
f := Collected(FactorsInt(n));
p := List(f, v -> List([0 .. v[2]], k -> v[1]^k));
return SortedList(List(Cartesian(p), Product));
end;
div2(Factorial(5));
# [ 1, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 120 ] |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Wren | Wren | import "/fmt" for Fmt
var fibN = Fn.new { |initial, numTerms|
var n = initial.count
if (n < 2 || numTerms < 0) Fiber.abort("Invalid argument(s).")
if (numTerms <= n) return initial.toList
var fibs = List.filled(numTerms, 0)
for (i in 0...n) fibs[i] = initial[i]
for (i in n...numTerms) {
var sum = 0
for (j in i-n...i) sum = sum + fibs[j]
fibs[i] = sum
}
return fibs
}
var names = [
"fibonacci", "tribonacci", "tetranacci", "pentanacci", "hexanacci",
"heptanacci", "octonacci", "nonanacci", "decanacci"
]
var initial = [1, 1, 2, 4, 8, 16, 32, 64, 128, 256]
System.print(" n name values")
var values = fibN.call([2, 1], 15)
Fmt.write("$2d $-10s", 2, "lucas")
Fmt.aprint(values, 4, 0, "")
for (i in 0..8) {
values = fibN.call(initial[0...i + 2], 15)
Fmt.write("$2d $-10s", i + 2, names[i])
Fmt.aprint(values, 4, 0, "")
} |
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.
| #ooRexx | ooRexx | Call random ,,1234567
a=.array~new
b=.array~new
Do i=1 To 10
a[i]=random(1,9999)
End
Say 'Unfiltered values:' a~makestring(line,' ')
/* copy even numbers to array b */
j=0
Do i=1 to 10
If filter(a[i]) Then Do
j = j + 1
b[j]=a[i]
End
end
Say 'Filtered values (in second array): ' b~makestring(line,' ')
/* destructive filtering: copy within array a */
j=0
Do i=1 to 10
If filter(a[i]) Then Do
j = j + 1
a[j]=a[i]
End
end
/* destructive filtering: delete the remaining elements */
Do i=10 To j+1 By -1
a~delete(i)
End
Say 'Filtered values (destructive filtering):' a~makestring(line,' ')
Exit
filter: Return arg(1)//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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Mirah | Mirah | 1.upto(100) do |n|
print "Fizz" if a = ((n % 3) == 0)
print "Buzz" if b = ((n % 5) == 0)
print n unless (a || b)
print "\n"
end |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #CoffeeScript | CoffeeScript | fib_ana = (n) ->
sqrt = Math.sqrt
phi = ((1 + sqrt(5))/2)
Math.round((Math.pow(phi, n)/sqrt(5))) |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Go | Go | package main
import "fmt"
func main() {
printFactors(-1)
printFactors(0)
printFactors(1)
printFactors(2)
printFactors(3)
printFactors(53)
printFactors(45)
printFactors(64)
printFactors(600851475143)
printFactors(999999999999999989)
}
func printFactors(nr int64) {
if nr < 1 {
fmt.Println("\nFactors of", nr, "not computed")
return
}
fmt.Printf("\nFactors of %d: ", nr)
fs := make([]int64, 1)
fs[0] = 1
apf := func(p int64, e int) {
n := len(fs)
for i, pp := 0, p; i < e; i, pp = i+1, pp*p {
for j := 0; j < n; j++ {
fs = append(fs, fs[j]*pp)
}
}
}
e := 0
for ; nr & 1 == 0; e++ {
nr >>= 1
}
apf(2, e)
for d := int64(3); nr > 1; d += 2 {
if d*d > nr {
d = nr
}
for e = 0; nr%d == 0; e++ {
nr /= d
}
if e > 0 {
apf(d, e)
}
}
fmt.Println(fs)
fmt.Println("Number of factors =", len(fs))
} |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
proc Nacci(N, F0); \Generate Fibonacci N-step sequence
int N, \step size
F0; \array of first N values
int I, J;
def M = 10; \number of members in the sequence
int F(M); \Fibonacci sequence
[for I:= 0 to M-1 do \for all the members of the sequence...
[if I < N then F(I):= F0(I) \initialize sequence
else [F(I):= 0; \sum previous members to get member I
for J:= 1 to N do F(I):= F(I) + F(I-J);
];
IntOut(0, F(I)); ChOut(0, ^ );
];
CrLf(0);
];
[Text(0, " Fibonacci: "); Nacci(2, [1, 1]);
Text(0, "Tribonacci: "); Nacci(3, [1, 1, 2]);
Text(0, "Tetranacci: "); Nacci(4, [1, 1, 2, 4]);
Text(0, " Lucas: "); Nacci(2, [2, 1]);
] |
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.
| #Oz | Oz | declare
Lst = [1 2 3 4 5]
LstEven = {Filter Lst IsEven} |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #ML | ML | local
fun fbstr i =
case (i mod 3 = 0, i mod 5 = 0) of
(true , true ) => "FizzBuzz"
| (true , false) => "Fizz"
| (false, true ) => "Buzz"
| (false, false) => Int.toString i
fun fizzbuzz' (n, j) =
if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1))
in
fun fizzbuzz n = fizzbuzz' (n, 1)
val _ = fizzbuzz 100
end |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Comefrom0x10 | Comefrom0x10 | stop = 6
a = 1
i = 1 # start
a # print result
fib
comefrom if i is 1 # start
b = 1
comefrom fib # start of loop
i = i + 1
next_b = a + b
a = b
b = next_b
comefrom fib if i > stop |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Gosu | Gosu | var numbers = {11, 21, 32, 45, 67, 96}
numbers.each(\ number -> printFactors(number))
function printFactors(n: int) {
if (n < 1) return
var result ="${n} => "
(1 .. n/2).each(\ i -> {result += n % i == 0 ? "${i} " : ""})
print("${result}${n}")
} |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Yabasic | Yabasic | sub nStepFibs$(seq$, limit)
local iMax, sum, numb$(1), lim, i
lim = token(seq$, numb$(), ",")
redim numb$(limit)
seq$ = ""
iMax = lim - 1
while(lim < limit)
sum = 0
for i = 0 to iMax : sum = sum + val(numb$(lim - i)) : next
lim = lim + 1
numb$(lim) = str$(sum)
wend
for i = 0 to lim : seq$ = seq$ + " " + numb$(i) : next
return seq$
end sub
print "Fibonacci:", nStepFibs$("1,1", 10)
print "Tribonacci:", nStepFibs$("1,1,2", 10)
print "Tetranacci:", nStepFibs$("1,1,2,4", 10)
print "Lucas:", nStepFibs$("2,1", 10) |
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.
| #PARI.2FGP | PARI/GP | iseven(n)=n%2==0
select(iseven, [2, 3, 4, 5, 7, 8, 9, 11, 13, 16, 17]) |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #MMIX | MMIX | t IS $255
Ja IS $127
LOC Data_Segment
data GREG @
fizz IS @-Data_Segment
BYTE "Fizz",0,0,0,0
buzz IS @-Data_Segment
BYTE "Buzz",0,0,0,0
nl IS @-Data_Segment
BYTE #a,0,0,0,0,0,0,0
buffer IS @-Data_Segment
LOC #1000
GREG @
% "usual" print integer subroutine
printnum LOC @
OR $1,$0,0
SETL $2,buffer+64
ADDU $2,$2,data
XOR $3,$3,$3
STBU $3,$2,1
loop DIV $1,$1,10
GET $3,rR
ADDU $3,$3,'0'
STBU $3,$2,0
SUBU $2,$2,1
PBNZ $1,loop
ADDU t,$2,1
TRAP 0,Fputs,StdOut
GO Ja,Ja,0
Main SETL $0,1 % i = 1
1H SETL $2,0 % fizz not taken
CMP $1,$0,100 % i <= 100
BP $1,4F % if no, go to end
DIV $1,$0,3
GET $1,rR % $1 = mod(i,3)
CSZ $2,$1,1 % $2 = Fizz taken?
BNZ $1,2F % $1 != 0? yes, then skip
ADDU t,data,fizz
TRAP 0,Fputs,StdOut % print "Fizz"
2H DIV $1,$0,5
GET $1,rR % $1 = mod(i,5)
BNZ $1,3F % $1 != 0? yes, then skip
ADDU t,data,buzz
TRAP 0,Fputs,StdOut % print "Buzz"
JMP 5F % skip print i
3H BP $2,5F % skip if Fizz was taken
GO Ja,printnum % print i
5H ADDU t,data,nl
TRAP 0,Fputs,StdOut % print newline
ADDU $0,$0,1
JMP 1B % repeat for next i
4H XOR t,t,t
TRAP 0,Halt,0 % exit(0) |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Common_Lisp | Common Lisp | (defun fibonacci-iterative (n &aux (f0 0) (f1 1))
(case n
(0 f0)
(1 f1)
(t (loop for n from 2 to n
for a = f0 then b and b = f1 then result
for result = (+ a b)
finally (return result))))) |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Groovy | Groovy | def factorize = { long target ->
if (target == 1) return [1L]
if (target < 4) return [1L, target]
def targetSqrt = Math.sqrt(target)
def lowfactors = (2L..targetSqrt).grep { (target % it) == 0 }
if (lowfactors == []) return [1L, target]
def nhalf = lowfactors.size() - ((lowfactors[-1] == targetSqrt) ? 1 : 0)
[1] + lowfactors + (0..<nhalf).collect { target.intdiv(lowfactors[it]) }.reverse() + [target]
} |
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}}
For
n
=
3
{\displaystyle n=3}
we have the tribonacci sequence; with initial values
[
1
,
1
,
2
]
{\displaystyle [1,1,2]}
and
F
k
3
=
F
k
−
1
3
+
F
k
−
2
3
+
F
k
−
3
3
{\displaystyle F_{k}^{3}=F_{k-1}^{3}+F_{k-2}^{3}+F_{k-3}^{3}}
For
n
=
4
{\displaystyle n=4}
we have the tetranacci sequence; with initial values
[
1
,
1
,
2
,
4
]
{\displaystyle [1,1,2,4]}
and
F
k
4
=
F
k
−
1
4
+
F
k
−
2
4
+
F
k
−
3
4
+
F
k
−
4
4
{\displaystyle F_{k}^{4}=F_{k-1}^{4}+F_{k-2}^{4}+F_{k-3}^{4}+F_{k-4}^{4}}
...
For general
n
>
2
{\displaystyle n>2}
we have the Fibonacci
n
{\displaystyle n}
-step sequence -
F
k
n
{\displaystyle F_{k}^{n}}
; with initial values of the first
n
{\displaystyle n}
values of the
(
n
−
1
)
{\displaystyle (n-1)}
'th Fibonacci
n
{\displaystyle n}
-step sequence
F
k
n
−
1
{\displaystyle F_{k}^{n-1}}
; and
k
{\displaystyle k}
'th value of this
n
{\displaystyle n}
'th sequence being
F
k
n
=
∑
i
=
1
(
n
)
F
k
−
i
(
n
)
{\displaystyle F_{k}^{n}=\sum _{i=1}^{(n)}{F_{k-i}^{(n)}}}
For small values of
n
{\displaystyle n}
, Greek numeric prefixes are sometimes used to individually name each series.
Fibonacci
n
{\displaystyle n}
-step sequences
n
{\displaystyle n}
Series name
Values
2
fibonacci
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 ...
3
tribonacci
1 1 2 4 7 13 24 44 81 149 274 504 927 1705 3136 ...
4
tetranacci
1 1 2 4 8 15 29 56 108 208 401 773 1490 2872 5536 ...
5
pentanacci
1 1 2 4 8 16 31 61 120 236 464 912 1793 3525 6930 ...
6
hexanacci
1 1 2 4 8 16 32 63 125 248 492 976 1936 3840 7617 ...
7
heptanacci
1 1 2 4 8 16 32 64 127 253 504 1004 2000 3984 7936 ...
8
octonacci
1 1 2 4 8 16 32 64 128 255 509 1016 2028 4048 8080 ...
9
nonanacci
1 1 2 4 8 16 32 64 128 256 511 1021 2040 4076 8144 ...
10
decanacci
1 1 2 4 8 16 32 64 128 256 512 1023 2045 4088 8172 ...
Allied sequences can be generated where the initial values are changed:
The Lucas series sums the two preceding values like the fibonacci series for
n
=
2
{\displaystyle n=2}
but uses
[
2
,
1
]
{\displaystyle [2,1]}
as its initial values.
Task
Write a function to generate Fibonacci
n
{\displaystyle n}
-step number sequences given its initial values and assuming the number of initial values determines how many previous values are summed to make the next number of the series.
Use this to print and show here at least the first ten members of the Fibo/tribo/tetra-nacci and Lucas sequences.
Related tasks
Fibonacci sequence
Wolfram Mathworld
Hofstadter Q sequence
Leonardo numbers
Also see
Lucas Numbers - Numberphile (Video)
Tribonacci Numbers (and the Rauzy Fractal) - Numberphile (Video)
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #zkl | zkl | fcn fibN(ns){ fcn(ns){ ns.append(ns.sum()).pop(0) }.fp(vm.arglist.copy()); } |
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.
| #Pascal | Pascal | const
numbers:array[0..9] of integer = (0,1,2,3,4,5,6,7,8,9);
for x = 1 to 10 do
if odd(numbers[x]) then
writeln( 'The number ',numbers[x],' is odd.');
else
writeln( 'The number ',numbers[x],' is even.'); |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Modula-2 | Modula-2 | MODULE Fizzbuzz;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
TYPE CB = PROCEDURE(INTEGER);
PROCEDURE Fizz(n : INTEGER);
BEGIN
IF n MOD 3 = 0 THEN
WriteString("Fizz");
Buzz(n,Newline)
ELSE
Buzz(n,WriteInt)
END
END Fizz;
PROCEDURE Buzz(n : INTEGER; f : CB);
BEGIN
IF n MOD 5 = 0 THEN
WriteString("Buzz");
WriteLn
ELSE
f(n)
END
END Buzz;
PROCEDURE WriteInt(n : INTEGER);
VAR buf : ARRAY[0..9] OF CHAR;
BEGIN
FormatString("%i\n", buf, n);
WriteString(buf)
END WriteInt;
PROCEDURE Newline(n : INTEGER);
BEGIN
WriteLn
END Newline;
VAR i : INTEGER;
BEGIN
FOR i:=1 TO 30 DO
Fizz(i)
END;
ReadChar
END Fizzbuzz. |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Computer.2Fzero_Assembly | Computer/zero Assembly | loop: LDA y ; higher No.
STA temp
ADD x ; lower No.
STA y
LDA temp
STA x
LDA count
SUB one
BRZ done
STA count
JMP loop
done: LDA y
STP
one: 1
count: 8 ; n = 10
x: 1
y: 1
temp: 0 |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Haskell | Haskell | import HFM.Primes (primePowerFactors)
import Control.Monad (mapM)
import Data.List (product)
-- primePowerFactors :: Integer -> [(Integer,Int)]
factors = map product .
mapM (\(p,m)-> [p^i | i<-[0..m]]) . primePowerFactors |
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.
| #Peloton | Peloton | <@ LETCNWLSTLIT>numbers|1 2 3 4 5 6 7 8 9 10 11 12</@>
<@ DEFLST>evens</@>
<@ ENULSTLIT>numbers|
<@ TSTEVEELTLST>...</@>
<@ IFF>
<@ LETLSTELTLST>evens|...</@>
</@>
</@> |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Modula-3 | Modula-3 | MODULE Fizzbuzz EXPORTS Main;
IMPORT IO;
BEGIN
FOR i := 1 TO 100 DO
IF i MOD 15 = 0 THEN
IO.Put("FizzBuzz\n");
ELSIF i MOD 5 = 0 THEN
IO.Put("Buzz\n");
ELSIF i MOD 3 = 0 THEN
IO.Put("Fizz\n");
ELSE
IO.PutInt(i);
IO.Put("\n");
END;
END;
END Fizzbuzz. |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Corescript | Corescript | print Fibonacci Sequence:
var previous = 1
var number = 0
var temp = (blank)
:fib
if number > 50000000000:kill
print (number)
set temp = (add number previous)
set previous = (number)
set number = (temp)
goto fib
:kill
stop |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #HicEst | HicEst | DLG(NameEdit=N, TItle='Enter an integer')
DO i = 1, N^0.5
IF( MOD(N,i) == 0) WRITE() i, N/i
ENDDO
END |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Perl | Perl | my @a = (1, 2, 3, 4, 5, 6);
my @even = grep { $_%2 == 0 } @a; |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Monte | Monte | def fizzBuzz(top):
var t := 1
while (t < top):
if ((t % 3 == 0) || (t % 5 == 0)):
if (t % 15 == 0):
traceln(`$t FizzBuzz`)
else if (t % 3 == 0):
traceln(`$t Fizz`)
else:
traceln(`$t Buzz`)
t += 1
fizzBuzz(100)
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Cowgol | Cowgol | include "cowgol.coh";
sub fibonacci(n: uint32): (a: uint32) is
a := 0;
var b: uint32 := 1;
while n > 0 loop
var c := a + b;
a := b;
b := c;
n := n - 1;
end loop;
end sub;
# test
var i: uint32 := 0;
while i < 20 loop
print_i32(fibonacci(i));
print_char(' ');
i := i + 1;
end loop;
print_nl(); |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
numbers := arglist ||| [ 32767, 45, 53, 64, 100] # combine command line provided and default set of values
every writes(lf,"factors of ",i := !numbers,"=") & writes(divisors(i)," ") do lf := "\n"
end
link factors |
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.
| #Phix | Phix | function even(integer i)
return remainder(i,2)=0
end function
?filter(tagset(10),even)
|
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #MontiLang | MontiLang | &DEFINE LOOP 100&
1 VAR i .
FOR LOOP
|| VAR ln .
i 5 % 0 ==
IF : .
ln |Buzz| + VAR ln .
ENDIF
i 3 % 0 ==
IF : .
ln |Fizz| + VAR ln .
ENDIF
ln || ==
IF : .
i PRINT .
ENDIF
ln || !=
IF : .
ln PRINT .
ENDIF
i 1 + VAR i .
ENDFOR |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Crystal | Crystal | def fib(n)
n < 2 ? n : fib(n - 1) + fib(n - 2)
end |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #J | J | foi=: [: I. 0 = (|~ i.@>:) |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #PHL | PHL | module var;
extern printf;
@Integer main [
var arr = 1..9;
var evens = arr.filter(#(i) i % 2 == 0);
printf("%s\n", evens::str);
return 0;
] |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #MoonScript | MoonScript | for i = 1,100
print ((a) -> a == "" and i or a) table.concat {
i % 3 == 0 and "Fizz" or ""
i % 5 == 0 and "Buzz" or ""} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #D | D | import std.stdio, std.conv, std.algorithm, std.math;
long sgn(alias unsignedFib)(int n) { // break sign manipulation apart
immutable uint m = (n >= 0) ? n : -n;
if (n < 0 && (n % 2 == 0))
return -unsignedFib(m);
else
return unsignedFib(m);
}
long fibD(uint m) { // Direct Calculation, correct for abs(m) <= 84
enum sqrt5r = 1.0L / sqrt(5.0L); // 1 / sqrt(5)
enum golden = (1.0L + sqrt(5.0L)) / 2.0L; // (1 + sqrt(5)) / 2
return roundTo!long(pow(golden, m) * sqrt5r);
}
long fibI(in uint m) pure nothrow { // Iterative
long thisFib = 0;
long nextFib = 1;
foreach (i; 0 .. m) {
long tmp = nextFib;
nextFib += thisFib;
thisFib = tmp;
}
return thisFib;
}
long fibR(uint m) { // Recursive
return (m < 2) ? m : fibR(m - 1) + fibR(m - 2);
}
long fibM(uint m) { // memoized Recursive
static long[] fib = [0, 1];
while (m >= fib.length )
fib ~= fibM(m - 2) + fibM(m - 1);
return fib[m];
}
alias sgn!fibD sfibD;
alias sgn!fibI sfibI;
alias sgn!fibR sfibR;
alias sgn!fibM sfibM;
auto fibG(in int m) { // generator(?)
immutable int sign = (m < 0) ? -1 : 1;
long yield;
return new class {
final int opApply(int delegate(ref int, ref long) dg) {
int idx = -sign; // prepare for pre-increment
foreach (f; this)
if (dg(idx += sign, f))
break;
return 0;
}
final int opApply(int delegate(ref long) dg) {
long f0, f1 = 1;
foreach (p; 0 .. m * sign + 1) {
if (sign == -1 && (p % 2 == 0))
yield = -f0;
else
yield = f0;
if (dg(yield)) break;
auto temp = f1;
f1 = f0 + f1;
f0 = temp;
}
return 0;
}
};
}
void main(in string[] args) {
int k = args.length > 1 ? to!int(args[1]) : 10;
writefln("Fib(%3d) = ", k);
writefln("D : %20d <- %20d + %20d",
sfibD(k), sfibD(k - 1), sfibD(k - 2));
writefln("I : %20d <- %20d + %20d",
sfibI(k), sfibI(k - 1), sfibI(k - 2));
if (abs(k) < 36 || args.length > 2)
// set a limit for recursive version
writefln("R : %20d <- %20d + %20d",
sfibR(k), sfibM(k - 1), sfibM(k - 2));
writefln("O : %20d <- %20d + %20d",
sfibM(k), sfibM(k - 1), sfibM(k - 2));
foreach (i, f; fibG(-9))
writef("%d:%d | ", i, 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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Java | Java | public static TreeSet<Long> factors(long n)
{
TreeSet<Long> factors = new TreeSet<Long>();
factors.add(n);
factors.add(1L);
for(long test = n - 1; test >= Math.sqrt(n); test--)
if(n % test == 0)
{
factors.add(test);
factors.add(n / test);
}
return factors;
} |
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.
| #PHP | PHP | $arr = range(1,5);
$evens = array();
foreach ($arr as $val){
if ($val % 2 == 0) $evens[] = $val);
}
print_r($evens); |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #MUMPS | MUMPS | FIZZBUZZ
NEW I
FOR I=1:1:100 WRITE !,$SELECT(('(I#3)&'(I#5)):"FizzBuzz",'(I#5):"Buzz",'(I#3):"Fizz",1:I)
KILL I
QUIT |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Dart | Dart | int fib(int n) {
if (n==0 || n==1) {
return n;
}
var prev=1;
var current=1;
for (var i=2; i<n; i++) {
var next = prev + current;
prev = current;
current = next;
}
return current;
}
int fibRec(int n) => n==0 || n==1 ? n : fibRec(n-1) + fibRec(n-2);
main() {
print(fib(11));
print(fibRec(11));
} |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #JavaScript | JavaScript | function factors(num)
{
var
n_factors = [],
i;
for (i = 1; i <= Math.floor(Math.sqrt(num)); i += 1)
if (num % i === 0)
{
n_factors.push(i);
if (num / i !== i)
n_factors.push(num / i);
}
n_factors.sort(function(a, b){return a - b;}); // numeric sort
return n_factors;
}
factors(45); // [1,3,5,9,15,45]
factors(53); // [1,53]
factors(64); // [1,2,4,8,16,32,64] |
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #Picat | Picat | [I : I in 1..20, I 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)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Nanoquery | Nanoquery | for i in range(1, 100)
if ((i % 3) = 0) and ((i % 5) = 0)
println "FizzBuzz"
else if i % 3 = 0
println "Fizz"
else if i % 5 = 0
println "Buzz"
else
println i
end
end |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Datalog | Datalog | .decl Fib(i:number, x:number)
Fib(0, 0).
Fib(1, 1).
Fib(i+2,x+y) :- Fib(i+1, x), Fib(i, y), i+2<=40, i+2>=2.
Fib(i-2,y-x) :- Fib(i-1, x), Fib(i, y), i-2>=-40, i-2<0. |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #jq | jq | # This implementation uses "sort" for tidiness
def factors:
. as $num
| reduce range(1; 1 + sqrt|floor) as $i
([];
if ($num % $i) == 0 then
($num / $i) as $r
| if $i == $r then . + [$i] else . + [$i, $r] end
else .
end )
| sort;
def task:
(45, 53, 64) | "\(.): \(factors)" ;
task |
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.
| #PicoLisp | PicoLisp | (filter '((N) (not (bit? 1 N)))
(1 2 3 4 5 6 7 8 9) ) |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #NATURAL | NATURAL |
DEFINE DATA
LOCAL
1 #I (I4)
1 #MODULO (I4)
1 #DIVISOR (I4)
1 #OUT (A10)
END-DEFINE
*
FOR #I := 1 TO 100
#DIVISOR := 15
#OUT := 'FizzBuzz'
PERFORM MODULO
*
#DIVISOR := 5
#OUT := 'Buzz'
PERFORM MODULO
*
#DIVISOR := 3
#OUT := 'Fizz'
PERFORM MODULO
*
WRITE #I
END-FOR
*
DEFINE SUBROUTINE MODULO
#MODULO := #I - (#I / #DIVISOR) * #DIVISOR
IF #MODULO = 0
WRITE NOTITLE #OUT
ESCAPE TOP
END-IF
END-SUBROUTINE
*
END
|
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #DBL | DBL | ;
; Fibonacci sequence for DBL version 4 by Dario B.
;
RECORD
FIB1, D10
FIB2, D10
FIBN, D10
J, D5
A2, A2
A5, A5
PROC
;----------------------------------------------------------------
XCALL FLAGS (0007000000,1) ;Suppress STOP message
OPEN (1,O,'TT:')
DISPLAY (1,'First 10 Fibonacci Numbers:',10)
FIB2=1
FOR J=1 UNTIL 10
DO BEGIN
FIBN=FIB1+FIB2
A2=J,'ZX'
A5=FIBN,'ZZZZX'
DISPLAY (1,A2,' : ',A5,10)
FIB1=FIB2
FIB2=FIBN
END
CLOSE 1
END |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Julia | Julia | using Primes
function factors(n)
f = [one(n)]
for (p,e) in factor(n)
f = reduce(vcat, [f*p^j for j in 1:e], init=f)
end
return length(f) == 1 ? [one(n), n] : sort!(f)
end
const examples = [28, 45, 53, 64, 6435789435768]
for n in examples
@time println("The factors of $n are: $(factors(n))")
end
|
http://rosettacode.org/wiki/Filter | Filter | Task
Select certain elements from an Array into a new Array in a generic way.
To demonstrate, select all even numbers from an Array.
As an option, give a second solution which filters destructively,
by modifying the original Array rather than creating a new Array.
| #PL.2FI | PL/I | (subscriptrange):
filter_values: procedure options (main); /* 15 November 2013 */
declare a(20) fixed, b(*) fixed controlled;
declare (i, j, n) fixed binary;
a = random()*99999; /* fill the array with random elements from 0-99998 */
put list ('Unfiltered values:');
put skip edit (a) (f(6));
/* Loop to count the number of elements that will be filtered */
n = 0;
do i = 1 to hbound(a);
n = n + filter(a(i));
end;
allocate b(n);
j = 0;
do i = 1 to hbound(a);
if filter(a(i)) then do; j = j + 1; b(j) = a(i); end;
end;
put skip list ('Filtered values:');
put skip edit (b) (f(6));
filter: procedure (value) returns (bit(1));
declare value fixed;
return (iand(abs(value), 1) = 0);
end filter;
end filter_values; |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Neko | Neko | var i = 1
while(i < 100) {
if(i % 15 == 0) {
$print("FizzBuzz\n");
} else if(i % 3 == 0) {
$print("Fizz\n");
} else if(i % 5 == 0) {
$print("Buzz\n");
} else {
$print(i + "\n");
}
i ++= 1
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Dc | Dc | [ # todo: n(<2) -- 1 and break 2 levels
d - # 0
1 + # 1
q
] s1
[ # todo: n(>-1) -- F(n)
d 0=1 # n(!=0)
d 1=1 # n(!in {0,1})
2 - d 1 + # (n-2) (n-1)
lF x # (n-2) F(n-1)
r # F(n-1) (n-2)
lF x # F(n-1)+F(n-2)
+
] sF
33 lF x 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 |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #K | K | f:{i:{y[&x=y*x div y]}[x;1+!_sqrt x];?i,x div|i}
equivalent to:
q)f:{i:{y where x=y*x div y}[x ; 1+ til floor sqrt x]; distinct i,x div reverse i}
f 120
1 2 3 4 5 6 8 10 12 15 20 24 30 40 60 120
f 1024
1 2 4 8 16 32 64 128 256 512 1024
f 600851475143
1 71 839 1471 6857 59569 104441 486847 1234169 5753023 10086647 87625999 408464633 716151937 8462696833 600851475143
#f 3491888400 / has 1920 factors
1920
/ Number of factors for 3491888400 .. 3491888409
#:'f' 3491888400+!10
1920 16 4 4 12 16 32 16 8 24 |
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.
| #Pop11 | Pop11 | ;;; Generic filtering procedure which selects from ar elements
;;; satisfying pred
define filter_array(ar, pred);
lvars i, k;
stacklength() -> k;
for i from 1 to length(ar) do
;;; if element satisfies pred we leave it on the stack
if pred(ar(i)) then ar(i) endif;
endfor;
;;; Collect elements from the stack into a vector
return (consvector(stacklength() - k));
enddefine;
;;; Use it
filter_array({1, 2, 3, 4, 5},
procedure(x); not(testbit(x, 0)); endprocedure) => |
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #Nemerle | Nemerle | using System;
using System.Console;
module FizzBuzz
{
FizzBuzz(x : int) : string
{
|x when x % 15 == 0 => "FizzBuzz"
|x when x % 5 == 0 => "Buzz"
|x when x % 3 == 0 => "Fizz"
|_ => $"$x"
}
Main() : void
{
foreach (i in [1 .. 100])
WriteLine($"$(FizzBuzz(i))")
}
} |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #Delphi | Delphi |
function FibonacciI(N: Word): UInt64;
var
Last, New: UInt64;
I: Word;
begin
if N < 2 then
Result := N
else begin
Last := 0;
Result := 1;
for I := 2 to N do
begin
New := Last + Result;
Last := Result;
Result := New;
end;
end;
end;
|
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Kotlin | Kotlin | fun printFactors(n: Int) {
if (n < 1) return
print("$n => ")
(1..n / 2)
.filter { n % it == 0 }
.forEach { print("$it ") }
println(n)
}
fun main(args: Array<String>) {
val numbers = intArrayOf(11, 21, 32, 45, 67, 96)
for (number in numbers) printFactors(number)
} |
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.
| #PostScript | PostScript |
[1 2 3 4 5 6 7 8 9 10] {2 mod 0 eq} find
|
http://rosettacode.org/wiki/FizzBuzz | FizzBuzz | Task
Write a program that prints the integers from 1 to 100 (inclusive).
But:
for multiples of three, print Fizz (instead of the number)
for multiples of five, print Buzz (instead of the number)
for multiples of both three and five, print FizzBuzz (instead of the number)
The FizzBuzz problem was presented as the lowest level of comprehension required to illustrate adequacy.
Also see
(a blog) dont-overthink-fizzbuzz
(a blog) fizzbuzz-the-programmers-stairway-to-heaven
| #NetRexx | NetRexx | loop j=1 for 100
select
when j//15==0 then say 'FizzBuzz'
when j//5==0 then say 'Buzz'
when j//3==0 then say 'Fizz'
otherwise say j.right(4)
end
end |
http://rosettacode.org/wiki/Fibonacci_sequence | Fibonacci sequence | The Fibonacci sequence is a sequence Fn of natural numbers defined recursively:
F0 = 0
F1 = 1
Fn = Fn-1 + Fn-2, if n>1
Task
Write a function to generate the nth Fibonacci number.
Solutions can be iterative or recursive (though recursive solutions are generally considered too slow and are mostly used as an exercise in recursion).
The sequence is sometimes extended into negative numbers by using a straightforward inverse of the positive definition:
Fn = Fn+2 - Fn+1, if n<0
support for negative n in the solution is optional.
Related tasks
Fibonacci n-step number sequences
Leonardo numbers
References
Wikipedia, Fibonacci number
Wikipedia, Lucas number
MathWorld, Fibonacci Number
Some identities for r-Fibonacci numbers
OEIS Fibonacci numbers
OEIS Lucas numbers
| #DIBOL-11 | DIBOL-11 |
START ;First 10 Fibonacci NUmbers
RECORD
FIB1, D10, 0
FIB2, D10, 1
FIBNEW, D10
LOOPCNT, D2, 1
RECORD HEADER
, A32, "First 10 Fibonacci Numbers."
RECORD OUTPUT
LOOPOUT, A2
, A3, " : "
FIBOUT, A10
PROC
OPEN(8,O,'TT:')
WRITES(8,HEADER)
LOOP,
FIBNEW = FIB1 + FIB2
LOOPOUT = LOOPCNT, 'ZX'
FIBOUT = FIBNEW, 'ZZZZZZZZZX'
WRITES(8,OUTPUT)
FIB1 = FIB2
FIB2 = FIBNEW
LOOPCNT = LOOPCNT + 1
IF LOOPCNT .LE. 10 GOTO LOOP
CLOSE 8
END
|
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Lambdatalk | Lambdatalk |
{def factors
{def factors.r
{lambda {:num :i :N}
{if {> :i :N}
then
else {if {= {% :num :i} 0}
then :i
{if {not {= {/ :num :i} :i}}
then {/ :num :i}
else}
else}
{factors.r :num {+ :i 1} :N} }}}
{lambda {:n}
{S.sort < {factors.r :n 1 {sqrt :n}}}}}
-> factors
{factors 45}
-> 1 3 5 9 15 45
{factors 53}
-> 1 53
{factors 64}
-> 1 2 4 8 16 32 64
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.