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/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #Kotlin | Kotlin | // version 1.1.2
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
class Frac : Comparable<Frac> {
val num: Long
val denom: Long
companion object {
val ZERO = Frac(0, 1)
val ONE = Frac(1, 1)
}
constructor(n: Long, d: Long) {
require(d != 0L)
var nn = n
var dd = d
if (nn == 0L) {
dd = 1
}
else if (dd < 0) {
nn = -nn
dd = -dd
}
val g = Math.abs(gcd(nn, dd))
if (g > 1) {
nn /= g
dd /= g
}
num = nn
denom = dd
}
constructor(n: Int, d: Int) : this(n.toLong(), d.toLong())
operator fun plus(other: Frac) =
Frac(num * other.denom + denom * other.num, other.denom * denom)
operator fun unaryMinus() = Frac(-num, denom)
operator fun minus(other: Frac) = this + (-other)
operator fun times(other: Frac) = Frac(this.num * other.num, this.denom * other.denom)
fun abs() = if (num >= 0) this else -this
override fun compareTo(other: Frac): Int {
val diff = this.toDouble() - other.toDouble()
return when {
diff < 0.0 -> -1
diff > 0.0 -> +1
else -> 0
}
}
override fun equals(other: Any?): Boolean {
if (other == null || other !is Frac) return false
return this.compareTo(other) == 0
}
override fun toString() = if (denom == 1L) "$num" else "$num/$denom"
fun toDouble() = num.toDouble() / denom
}
fun bernoulli(n: Int): Frac {
require(n >= 0)
val a = Array<Frac>(n + 1) { Frac.ZERO }
for (m in 0..n) {
a[m] = Frac(1, m + 1)
for (j in m downTo 1) a[j - 1] = (a[j - 1] - a[j]) * Frac(j, 1)
}
return if (n != 1) a[0] else -a[0] // returns 'first' Bernoulli number
}
fun binomial(n: Int, k: Int): Int {
require(n >= 0 && k >= 0 && n >= k)
if (n == 0 || k == 0) return 1
val num = (k + 1..n).fold(1) { acc, i -> acc * i }
val den = (2..n - k).fold(1) { acc, i -> acc * i }
return num / den
}
fun faulhaber(p: Int) {
print("$p : ")
val q = Frac(1, p + 1)
var sign = -1
for (j in 0..p) {
sign *= -1
val coeff = q * Frac(sign, 1) * Frac(binomial(p + 1, j), 1) * bernoulli(j)
if (coeff == Frac.ZERO) continue
if (j == 0) {
print(when {
coeff == Frac.ONE -> ""
coeff == -Frac.ONE -> "-"
else -> "$coeff"
})
}
else {
print(when {
coeff == Frac.ONE -> " + "
coeff == -Frac.ONE -> " - "
coeff > Frac.ZERO -> " + $coeff"
else -> " - ${-coeff}"
})
}
val pwr = p + 1 - j
if (pwr > 1)
print("n^${p + 1 - j}")
else
print("n")
}
println()
}
fun main(args: Array<String>) {
for (i in 0..9) faulhaber(i)
} |
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
| #Clojure | Clojure | (defn nacci [init]
(letfn [(s [] (lazy-cat init (apply map + (map #(drop % (s)) (range (count init))))))]
(s)))
(let [show (fn [name init] (println "first 20" name (take 20 (nacci init))))]
(show "Fibonacci" [1 1])
(show "Tribonacci" [1 1 2])
(show "Tetranacci" [1 1 2 4])
(show "Lucas" [2 1])) |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #Wren | Wren | /* file_mod_time_wren */
import "./date" for Date
foreign class Stat {
construct new(fileName) {}
foreign atime
foreign mtime
}
foreign class Utimbuf {
construct new(actime, modtime) {}
foreign utime(fileName)
}
// gets a Date object from a Unix time in seconds
var UT2Date = Fn.new { |ut| Date.unixEpoch.addSeconds(ut) }
Date.default = "yyyy|-|mm|-|dd| |hh|:|MM|:|ss" // default format for printing
var fileName = "temp.txt"
var st = Stat.new(fileName)
System.print("'%(fileName)' was last modified on %(UT2Date.call(st.mtime)).")
var utb = Utimbuf.new(st.atime, 0) // atime unchanged, mtime = current time
if (utb.utime(fileName) < 0) {
System.print("There was an error changing the file modification time.")
return
}
st = Stat.new(fileName) // update info
System.print("File modification time changed to %(UT2Date.call(st.mtime)).") |
http://rosettacode.org/wiki/File_modification_time | File modification time | Task
Get and set the modification time of a file.
| #zkl | zkl | info:=File.info("input.txt");
// -->T(size,last status change time,last mod time,isDir,mode), from stat(2)
info.println();
Time.Date.ctime(info[2]).println();
File.setModTime("input.txt",Time.Clock.mktime(2014,2,1,0,0,0));
File.info("input.txt")[2] : Time.Date.ctime(_).println(); |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PowerShell | PowerShell |
<#
.Synopsis
Finds the deepest common directory path of files passed through the pipeline.
.Parameter File
PowerShell file object.
#>
function Get-CommonPath {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[System.IO.FileInfo] $File
)
process {
# Get the current file's path list
$PathList = $File.FullName -split "\$([IO.Path]::DirectorySeparatorChar)"
# Get the most common path list
if ($CommonPathList) {
$CommonPathList = (Compare-Object -ReferenceObject $CommonPathList -DifferenceObject $PathList -IncludeEqual `
-ExcludeDifferent -SyncWindow 0).InputObject
} else {
$CommonPathList = $PathList
}
}
end {
$CommonPathList -join [IO.Path]::DirectorySeparatorChar
}
}
|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Prolog | Prolog |
%! directory_prefix(PATHs,STOP0,PREFIX)
directory_prefix([],_STOP0_,'')
:-
!
.
directory_prefix(PATHs0,STOP0,PREFIX)
:-
prolog:once(longest_prefix(PATHs0,STOP0,LONGEST_PREFIX)) ->
prolog:atom_concat(PREFIX,STOP0,LONGEST_PREFIX) ;
PREFIX=''
.
%! longest_prefix(PATHs,STOP0,PREFIX)
longest_prefix(PATHs0,STOP0,PREFIX)
:-
QUERY=(shortest_prefix(PATHs0,STOP0,SHORTEST_PREFIX)) ,
prolog:findall(SHORTEST_PREFIX,QUERY,SHORTEST_PREFIXs) ,
lists:reverse(SHORTEST_PREFIXs,LONGEST_PREFIXs) ,
lists:member(PREFIX,LONGEST_PREFIXs)
.
%! shortest_prefix(PATHs,STOP0,PREFIX)
shortest_prefix([],_STOP0_,_PREFIX_) .
shortest_prefix([PATH0|PATHs0],STOP0,PREFIX)
:-
starts_with(PATH0,PREFIX) ,
ends_with(PREFIX,STOP0) ,
shortest_prefix(PATHs0,STOP0,PREFIX)
.
%! starts_with(TARGET,START)
starts_with(TARGET,START)
:-
prolog:atom_concat(START,_,TARGET)
.
%! ends_with(TARGET,END)
ends_with(TARGET,END)
:-
prolog:atom_concat(_,END,TARGET)
.
|
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.
| #EchoLisp | EchoLisp |
(iota 12) → { 0 1 2 3 4 5 6 7 8 9 10 11 }
;; lists
(filter even? (iota 12))
→ (0 2 4 6 8 10)
;; array (non destructive)
(vector-filter even? #(1 2 3 4 5 6 7 8 9 10 11 12 13))
→ #( 2 4 6 8 10 12)
;; sequence, infinite, lazy
(lib 'sequences)
(define evens (filter even? [0 ..]))
(take evens 12)
→ (0 2 4 6 8 10 12 14 16 18 20 22)
|
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Sidef | Sidef | func recurse(n) {
say n;
recurse(n+1);
}
recurse(0); |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Smalltalk | Smalltalk |
Object subclass: #RecursionTest
instanceVariableNames: ''
classVariableNames: ''
poolDictionaries: ''
category: 'RosettaCode'
|
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Standard_ML | Standard ML | fun recLimit () =
1 + recLimit ()
handle _ => 0
val () = print (Int.toString (recLimit ()) ^ "\n") |
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
| #HicEst | HicEst | DO i = 1, 100
IF( MOD(i, 15) == 0 ) THEN
WRITE() "FizzBuzz"
ELSEIF( MOD(i, 5) == 0 ) THEN
WRITE() "Buzz"
ELSEIF( MOD(i, 3) == 0 ) THEN
WRITE() "Fizz"
ELSE
WRITE() i
ENDIF
ENDDO |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #PowerShell | PowerShell | Get-ChildItem input.txt | Select-Object Name,Length
Get-ChildItem \input.txt | Select-Object Name,Length |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #PureBasic | PureBasic | Debug FileSize("input.txt")
Debug FileSize("/input.txt") |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Python | Python | import os
size = os.path.getsize('input.txt')
size = os.path.getsize('/input.txt') |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #i | i | software {
file = load("input.txt")
open("output.txt").write(file)
} |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Icon_and_Unicon | Icon and Unicon | procedure main()
in := open(f := "input.txt","r") | stop("Unable to open ",f)
out := open(f := "output.txt","w") | stop("Unable to open ",f)
while write(out,read(in))
end |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | entropy = (p - 1) Log[2, 1 - p] - p Log[2, p];
TableForm[
Table[{k, Fibonacci[k],
Quiet@Check[N[entropy /. {p -> Fibonacci[k - 1]/Fibonacci[k]}, 15],
0]}, {k, 37}],
TableHeadings -> {None, {"N", "Length", "Entropy"}}] |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #Nim | Nim | import math, strformat, strutils
func entropy(str: string): float =
## return the entropy of a fibword string.
if str.len <= 1: return 0.0
let strlen = str.len.toFloat
let count0 = str.count('0').toFloat
let count1 = strlen - count0
result = -(count0 / strlen * log2(count0 / strlen) + count1 / strlen * log2(count1 / strlen))
iterator fibword(): string =
## Yield the successive fibwords.
var a = "1"
var b = "0"
yield a
yield b
while true:
a = b & a
swap a, b
yield b
when isMainModule:
echo " n length entropy"
echo "————————————————————————————————"
var n = 0
for str in fibword():
inc n
echo fmt"{n:2} {str.len:8} {entropy(str):.16f}"
if n == 37: break |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #PicoLisp | PicoLisp | (de fasta (F)
(in F
(while (from ">")
(prin (line T) ": ")
(until (or (= ">" (peek)) (eof))
(prin (line T)) )
(prinl) ) ) )
(fasta "fasta.dat") |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #PowerShell | PowerShell |
$file = @'
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
'@
$lines = $file.Replace("`n","~").Split(">").ForEach({$_.TrimEnd("~").Split("`n",2,[StringSplitOptions]::RemoveEmptyEntries)})
$output = New-Object -TypeName PSObject
foreach ($line in $lines)
{
$name, $value = $line.Split("~",2).ForEach({$_.Replace("~","")})
$output | Add-Member -MemberType NoteProperty -Name $name -Value $value
}
$output | Format-List
|
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
| #68000_Assembly | 68000 Assembly | fib:
MOVEM.L D4-D5,-(SP)
MOVE.L D0,D4
MOVEQ #0,D5
CMP.L #2,D0
BCS .bar
MOVEQ #0,D5
.foo:
MOVE.L D4,D0
SUBQ.L #1,D0
JSR fib
SUBQ.L #2,D4
ADD.L D0,D5
CMP.L #1,D4
BHI .foo
.bar:
MOVE.L D5,D0
ADD.L D4,D0
MOVEM.L (SP)+,D4-D5
RTS |
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
| #Action.21 | Action! | PROC PrintFactors(CARD a)
BYTE notFirst
CARD p
p=1 notFirst=0
WHILE p<=a
DO
IF a MOD p=0 THEN
IF notFirst THEN
Print(", ")
FI
notFirst=1
PrintC(p)
FI
p==+1
OD
RETURN
PROC Test(CARD a)
PrintF("Factors of %U: ",a)
PrintFactors(a)
PutE()
RETURN
PROC Main()
Test(1)
Test(101)
Test(666)
Test(1977)
Test(2021)
Test(6502)
Test(12345)
RETURN |
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.
| #Crystal | Crystal | require "complex"
def fft(x : Array(Int32 | Float64)) #: Array(Complex)
return [x[0].to_c] if x.size <= 1
even = fft(Array.new(x.size // 2) { |k| x[2 * k] })
odd = fft(Array.new(x.size // 2) { |k| x[2 * k + 1] })
c = Array.new(x.size // 2) { |k| Math.exp((-2 * Math::PI * k / x.size).i) }
codd = Array.new(x.size // 2) { |k| c[k] * odd[k] }
return Array.new(x.size // 2) { |k| even[k] + codd[k] } + Array.new(x.size // 2) { |k| even[k] - codd[k] }
end
fft([1,1,1,1,0,0,0,0]).each{ |c| puts c }
|
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number | Factors of a Mersenne number | A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test.
There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1).
Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar).
The following is how to implement this modPow yourself:
For example, let's compute 223 mod 47.
Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it.
Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47.
Use the result of the modulo from the last step as the initial value of square in the next step:
remove optional
square top bit multiply by 2 mod 47
──────────── ─────── ───────────── ──────
1*1 = 1 1 0111 1*2 = 2 2
2*2 = 4 0 111 no 4
4*4 = 16 1 11 16*2 = 32 32
32*32 = 1024 1 1 1024*2 = 2048 27
27*27 = 729 1 729*2 = 1458 1
Since 223 mod 47 = 1, 47 is a factor of 2P-1.
(To see this, subtract 1 from both sides: 223-1 = 0 mod 47.)
Since we've shown that 47 is a factor, 223-1 is not prime.
Further properties of Mersenne numbers allow us to refine the process even more.
Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8.
Finally any potential factor q must be prime.
As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N).
These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1.
Task
Using the above method find a factor of 2929-1 (aka M929)
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
See also
Computers in 1948: 2127 - 1
(Note: This video is no longer available because the YouTube account associated with this video has been terminated.)
| #C.2B.2B | C++ | #include <iostream>
#include <cstdint>
typedef uint64_t integer;
integer bit_count(integer n) {
integer count = 0;
for (; n > 0; count++)
n >>= 1;
return count;
}
integer mod_pow(integer p, integer n) {
integer square = 1;
for (integer bits = bit_count(p); bits > 0; square %= n) {
square *= square;
if (p & (1 << --bits))
square <<= 1;
}
return square;
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
for (integer p = 3; p * p <= n; p += 2)
if (n % p == 0)
return false;
return true;
}
integer find_mersenne_factor(integer p) {
for (integer k = 0, q = 1;;) {
q = 2 * ++k * p + 1;
if ((q % 8 == 1 || q % 8 == 7) && mod_pow(p, q) == 1 && is_prime(q))
return q;
}
return 0;
}
int main() {
std::cout << find_mersenne_factor(929) << std::endl;
return 0;
} |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #EDSAC_order_code | EDSAC order code |
[Farey sequence for Rosetta Code website.
EDSAC program, Initial Orders 2.
Prints Farey sequences up to order 11
(or other limit determined by a simple edit).]
[Modification of library subroutine P6.
Prints number (absolute value <= 65535)
passed in 0F, without leading spaces.
41 locations.]
T 56 K
GKA3FT35@SFG11@UFS40@E10@O40@T4FE35@O@T4F
H38@VFT4DA13@TFH39@S16@T1FV4DU4DAFG36@TFTF
O5FA4DF4FS4FL4FT4DA1FS13@G19@EFSFE30@J995FJFPD
T 100 K
G K
[Maximum order to be printed. For convenience, entered as
an address, not an integer, e.g. 'P 11 F' not 'P 5 D'.]
[0] P 11 F [<--- edit here]
[Other constants]
[1] P D [1]
[2] # F [figure shift]
[3] X F [slash]
[4] ! F [space]
[5] @ F [carriage return]
[6] & F [line feed]
[7] K4096 F [teleprinter null]
[Variables]
[8] P F [n, order of current Farey sequence]
[9] P F [maximum n + 1, as integer]
[a/b and c/d are consecutive terms of the Farey sequence]
[10] P F [a]
[11] P F [b]
[12] P F [c]
[13] P F [d]
[14] P F [t, temporary store]
[Subroutine to print c/d]
[15] A 3 F [plant link for return]
T 26 @
A 12 @ [load c]
T F [to 0F for printing]
[19] A 19 @ [for subroutine return]
G 56 F [print c]
O 3 @ [print '/']
A 13 @ [load d]
T F [to 0F for printing]
[24] A 24 @ [for subroutine return]
G 56 F [print d]
[26] E F [return]
[Main routine.
Enter with accumulator = 0.]
[27] O 2 @ [set teleprinter to figures]
A @ [max order as address]
R D [shift 1 right to make integer]
A 1 @ [add 1]
T 9 @ [save for comparison]
A 1 @ [start with order 1]
[Here with next order (n) in the accumulator]
[33] S 9 @ [subtract (max order) + 1]
E 84 @ [exit if over maximum]
A 9 @ [restore after test]
T 8 @ [store]
[Prefix the Farey sequence with a formal term -1/0.
The second term is calculated from this and the first term.]
S 1 @ [acc := -1]
T 10 @ [a := -1]
T 11 @ [b := 0]
T 12 @ [c := 0]
A 1 @ [d := 1]
T 13 @
A 43 @ [for subroutine return]
G 15 @ [call subroutine to print c/d]
[Calculate next term; basically same as Wikipedia method]
[45] T F [clear acc]
A 10 @ [t := a]
T 14 @
A 12 @ [a := c;]
T 10 @
S 14 @ [c := -t]
T 12 @
A 11 @ [t := b]
T 14 @
A 13 @ [b := d]
T 11 @
S 14 @ [d := -t]
T 13 @
A 8 @ [t := n + t]
A 14 @
T 14 @
[Inner loop, get t div b by repeated subtraction]
[61] A 14 @ [t := t - b]
S 11 @
G 72 @ [jump out when t < 0]
T 14 @
A 12 @ [c := c + a]
A 10 @
T 12 @
A 13 @ [d := d + b]
A 11 @
T 13 @
E 61 @ [loop back (always, since acc = 0)]
[End of inner loop, print c/d preceded by space]
[72] O 4 @
T F
[74] A 74 @ [for subroutine return]
G 15 @ [call subroutine to print c/d]
A 1 @ [form 1 - d, to test for d = 1]
S 13 @
G 45 @ [if d > 1, loop for next term]
O 5 @ [else print end of line (CR LF)]
O 6 @
[Next Farey series.]
A 8 @ [load order]
A 1 @ [add 1]
E 33 @ [loop back]
[Here when finished]
[84] O 7 @ [output null to flush teleprinter buffer]
Z F [stop]
E 27 Z [define start of execution]
P F [start with accumulator = 0]
|
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #Factor | Factor | USING: formatting io kernel math math.primes.factors math.ranges
locals prettyprint sequences sequences.extras sets tools.time ;
IN: rosetta-code.farey-sequence
! Given the order n and a farey pair, calculate the next member
! of the sequence.
:: p/q ( n a/b c/d -- p/q )
a/b c/d [ >fraction ] bi@ :> ( a b c d )
n b + d / >integer [ c * a - ] [ d * b - ] bi / ;
: print-farey ( order -- )
[ "F(%-2d): " printf ] [ 0 1 pick / ] bi "0/1 " write
[ dup 1 = ] [ dup pprint bl 3dup p/q [ nip ] dip ] until
3drop "1/1" print ;
: φ ( n -- m ) ! Euler's totient function
[ factors members [ 1 swap recip - ] map-product ] [ * ] bi ;
: farey-length ( order -- length )
dup 1 = [ drop 2 ]
[ [ 1 - farey-length ] [ φ ] bi + ] if ;
: part1 ( -- ) 11 [1,b] [ print-farey ] each nl ;
: part2 ( -- )
100 1,000 100 <range>
[ dup farey-length "F(%-4d): %-6d members.\n" printf ] each ;
: main ( -- ) [ part1 part2 nl ] time ;
MAIN: main |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #Lua | Lua | function turn(base, n)
local sum = 0
while n ~= 0 do
local re = n % base
n = math.floor(n / base)
sum = sum + re
end
return sum % base
end
function fairShare(base, count)
io.write(string.format("Base %2d:", base))
for i=1,count do
local t = turn(base, i - 1)
io.write(string.format(" %2d", t))
end
print()
end
function turnCount(base, count)
local cnt = {}
for i=1,base do
cnt[i - 1] = 0
end
for i=1,count do
local t = turn(base, i - 1)
if cnt[t] ~= nil then
cnt[t] = cnt[t] + 1
else
cnt[t] = 1
end
end
local minTurn = count
local maxTurn = -count
local portion = 0
for _,num in pairs(cnt) do
if num > 0 then
portion = portion + 1
end
if num < minTurn then
minTurn = num
end
if maxTurn < num then
maxTurn = num
end
end
io.write(string.format(" With %d people: ", base))
if minTurn == 0 then
print(string.format("Only %d have a turn", portion))
elseif minTurn == maxTurn then
print(minTurn)
else
print(minTurn .. " or " .. maxTurn)
end
end
function main()
fairShare(2, 25)
fairShare(3, 25)
fairShare(5, 25)
fairShare(11, 25)
print("How many times does each get a turn in 50000 iterations?")
turnCount(191, 50000)
turnCount(1377, 50000)
turnCount(49999, 50000)
turnCount(50000, 50000)
turnCount(50001, 50000)
end
main() |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #jq | jq | include "Rational";
# Preliminaries
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
# for gojq
def idivide($j):
. as $i
| ($i % $j) as $mod
| ($i - $mod) / $j ;
# use idivide for precision
def binomial(n; k):
if k > n / 2 then binomial(n; n-k)
else reduce range(1; k+1) as $i (1; . * (n - $i + 1) | idivide($i))
end;
# Here we conform to the modern view that B(1) is 1 // 2
def bernoulli:
if type != "number" or . < 0 then "bernoulli must be given a non-negative number vs \(.)" | error
else . as $n
| reduce range(0; $n+1) as $i ([];
.[$i] = r(1; $i + 1)
| reduce range($i; 0; -1) as $j (.;
.[$j-1] = rmult($j; rminus(.[$j-1]; .[$j])) ) )
| .[0] # the modern view
end;
# Input: a non-negative integer, $p
# Output: an array of Rationals corresponding to the
# Faulhaber coefficients for row ($p + 1) (counting the first row as row 1).
def faulhabercoeffs:
def altBernoulli: # adjust B(1) for this task
bernoulli as $b
| if . == 1 then rmult(-1; $b) else $b end;
. as $p
| r(1; $p + 1) as $q
| { coeffs: [], sign: -1 }
| reduce range(0; $p+1) as $j (.;
.sign *= -1
| binomial($p + 1; $j) as $b
| .coeffs[$p - $j] = ([ .sign, $q, $b, ($j|altBernoulli) ] | rmult))
| .coeffs
;
# Calculate the sum for ($k|faulhabercoeffs)
def faulhabersum($n; $k):
($k|faulhabercoeffs) as $coe
| reduce range(0;$k+1) as $i ({sum: 0, power: 1};
.power *= $n
| .sum = radd(.sum; rmult(.power; $coe[$i]))
)
| .sum;
# pretty print a Rational assumed to have the {n,d} form
def rpp:
if .n == 0 then "0"
elif .d == 1 then .n | tostring
else "\(.n)/\(.d)"
end;
def testfaulhaber:
(range(0; 10) as $i
| ($i | faulhabercoeffs | map(rpp | lpad(6)) | join(" "))),
"\nfaulhabersum(1000; 17):",
(faulhabersum(1000; 17) | rpp) ;
testfaulhaber |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #Lua | Lua | function binomial(n,k)
if n<0 or k<0 or n<k then return -1 end
if n==0 or k==0 then return 1 end
local num = 1
for i=k+1,n do
num = num * i
end
local denom = 1
for i=2,n-k do
denom = denom * i
end
return num / denom
end
function gcd(a,b)
while b ~= 0 do
local temp = a % b
a = b
b = temp
end
return a
end
function makeFrac(n,d)
local result = {}
if d==0 then
result.num = 0
result.denom = 0
return result
end
if n==0 then
d = 1
elseif d < 0 then
n = -n
d = -d
end
local g = math.abs(gcd(n, d))
if g>1 then
n = n / g
d = d / g
end
result.num = n
result.denom = d
return result
end
function negateFrac(f)
return makeFrac(-f.num, f.denom)
end
function subFrac(lhs, rhs)
return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom)
end
function multFrac(lhs, rhs)
return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom)
end
function equalFrac(lhs, rhs)
return (lhs.num == rhs.num) and (lhs.denom == rhs.denom)
end
function lessFrac(lhs, rhs)
return (lhs.num * rhs.denom) < (rhs.num * lhs.denom)
end
function printFrac(f)
io.write(f.num)
if f.denom ~= 1 then
io.write("/"..f.denom)
end
return nil
end
function bernoulli(n)
if n<0 then
return {num=0, denom=0}
end
local a = {}
for m=0,n do
a[m] = makeFrac(1, m+1)
for j=m,1,-1 do
a[j-1] = multFrac(subFrac(a[j-1], a[j]), makeFrac(j, 1))
end
end
if n~=1 then
return a[0]
end
return negateFrac(a[0])
end
function faulhaber(p)
io.write(p.." : ")
local q = makeFrac(1, p+1)
local sign = -1
for j=0,p do
sign = -1 * sign
local coeff = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j))
if not equalFrac(coeff, makeFrac(0, 1)) then
if j==0 then
if not equalFrac(coeff, makeFrac(1, 1)) then
if equalFrac(coeff, makeFrac(-1, 1)) then
io.write("-")
else
printFrac(coeff)
end
end
else
if equalFrac(coeff, makeFrac(1, 1)) then
io.write(" + ")
elseif equalFrac(coeff, makeFrac(-1, 1)) then
io.write(" - ")
elseif lessFrac(makeFrac(0, 1), coeff) then
io.write(" + ")
printFrac(coeff)
else
io.write(" - ")
printFrac(negateFrac(coeff))
end
end
local pwr = p + 1 - j
if pwr>1 then
io.write("n^"..pwr)
else
io.write("n")
end
end
end
print()
return nil
end
-- main
for i=0,9 do
faulhaber(i)
end |
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
| #CLU | CLU | % Find the Nth element of a given n-step sequence
n_step = proc (seq: sequence[int], n: int) returns (int)
a: array[int] := sequence[int]$s2a(seq)
for i: int in int$from_to(1,n) do
sum: int := 0
for x: int in array[int]$elements(a) do
sum := sum + x
end
array[int]$reml(a)
array[int]$addh(a,sum)
end
return(array[int]$bottom(a))
end n_step
% Generate the initial sequence for the Fibonacci n-step sequence of length N
anynacci = proc (n: int) returns (sequence[int])
a: array[int] := array[int]$[1]
for i: int in int$from_to(0,n-2) do
array[int]$addh(a, 2**i)
end
return(sequence[int]$a2s(a))
end anynacci
% Given an initial sequence, print the first N elements
print_n = proc (seq: sequence[int], n: int)
po: stream := stream$primary_output()
for i: int in int$from_to(0, n-1) do
stream$putright(po, int$unparse(n_step(seq, i)), 4)
end
stream$putl(po, "")
end print_n
start_up = proc ()
s = struct[name: string, seq: sequence[int]]
po: stream := stream$primary_output()
seqs: array[s] := array[s]$[
s${name: "Fibonacci", seq: anynacci(2)},
s${name: "Tribonacci", seq: anynacci(3)},
s${name: "Tetranacci", seq: anynacci(4)},
s${name: "Lucas", seq: sequence[int]$[2,1]}
]
for seq: s in array[s]$elements(seqs) do
stream$putleft(po, seq.name, 12)
print_n(seq.seq, 10)
end
end start_up |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PureBasic | PureBasic | Procedure.s CommonPath(Array InPaths.s(1),separator.s="/")
Protected SOut$=""
Protected i, j, toggle
If ArraySize(InPaths())=0
ProcedureReturn InPaths(0) ; Special case, only one path
EndIf
Repeat
i+1
toggle=#False
For j=1 To ArraySize(InPaths())
If (StringField(InPaths(j-1),i,separator)=StringField(InPaths(j),i,separator))
If Not toggle
SOut$+StringField(InPaths(j-1),i,separator)+separator
toggle=#True
EndIf
Else
ProcedureReturn SOut$
EndIf
Next
ForEver
EndProcedure |
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.
| #Ela | Ela | open list
evenList = filter' (\x -> x % 2 == 0) [1..] |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Swift | Swift | var n = 1
func recurse() {
print(n)
n += 1
recurse()
}
recurse() |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Tcl | Tcl | proc recur i {
puts "This is depth [incr i]"
catch {recur $i}; # Trap error from going too deep
}
recur 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
| #HolyC | HolyC | U8 i;
for (i = 1; i <= 100; i++) {
if (!(i % 15))
Print("FizzBuzz");
else if (!(i % 3))
Print("Fizz");
else if (!(i % 5))
Print("Buzz");
else
Print("%d", i);
Print("\n");
} |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #R | R | sizeinwd <- file.info('input.txt')[["size"]]
sizeinroot <- file.info('/input.txt')[["size"]] |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Racket | Racket | #lang racket
(file-size "input.txt")
(file-size "/input.txt") |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Raku | Raku | say 'input.txt'.IO.s;
say '/input.txt'.IO.s; |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #IDL | IDL | ; open two LUNs
openw,unit1,'output.txt,/get
openr,unit2,'input.txt',/get
; how many bytes to read
fs = fstat(unit2)
; make buffer
buff = bytarr(fs.size)
; transfer content
readu,unit2,buff
writeu,unit1,buff
; that's all
close,/all |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Io | Io | inf := File with("input.txt") openForReading
outf := File with("output.txt") openForUpdating
while(l := inf readLine,
outf write(l, "\n")
)
inf close
outf close
|
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #Objeck | Objeck | use Collection;
class FibonacciWord {
function : native : GetEntropy(result : String) ~ Float {
frequencies := IntMap->New();
each(i : result) {
c := result->Get(i);
if(frequencies->Has(c)) {
count := frequencies->Find(c)->As(IntHolder);
count->Set(count->Get() + 1);
}
else {
frequencies->Insert(c, IntHolder->New(1));
};
};
length := result->Size();
entropy := 0.0;
counts := frequencies->GetValues();
each(i : counts) {
count := counts->Get(i)->As(IntHolder)->Get();
freq := count->As(Float) / length;
entropy += freq * (freq->Log() / 2.0->Log());
};
return -1 * entropy;
}
function : native : PrintLine(n : Int, result : String) ~ Nil {
n->Print();
'\t'->Print();
result->Size()->Print();
"\t\t"->Print();
GetEntropy(result)->PrintLine();
}
function : Main(args : String[]) ~ Nil {
firstString := "1";
n := 1;
PrintLine( n, firstString );
secondString := "0";
n += 1;
PrintLine( n, secondString );
while(n < 37) {
resultString := "{$secondString}{$firstString}";
firstString := secondString;
secondString := resultString;
n += 1;
PrintLine( n, resultString );
};
}
} |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #PureBasic | PureBasic | EnableExplicit
Define Hdl_File.i,
Frm_File.i,
c.c,
header.b
Hdl_File=ReadFile(#PB_Any,"c:\code_pb\rosettacode\data\FASTA_TEST.txt")
If Not IsFile(Hdl_File) : End -1 : EndIf
Frm_File=ReadStringFormat(Hdl_File)
If OpenConsole("FASTA format")
While Not Eof(Hdl_File)
c=ReadCharacter(Hdl_File,Frm_File)
Select c
Case '>'
header=#True
PrintN("")
Case #LF, #CR
If header
Print(": ")
header=#False
EndIf
Default
Print(Chr(c))
EndSelect
Wend
CloseFile(Hdl_File)
Input()
EndIf |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Python | Python | import io
FASTA='''\
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED'''
infile = io.StringIO(FASTA)
def fasta_parse(infile):
key = ''
for line in infile:
if line.startswith('>'):
if key:
yield key, val
key, val = line[1:].rstrip().split()[0], ''
elif key:
val += line.rstrip()
if key:
yield key, val
print('\n'.join('%s: %s' % keyval for keyval in fasta_parse(infile))) |
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
| #8080_Assembly | 8080 Assembly | FIBNCI: MOV C, A ; C will store the counter
DCR C ; decrement, because we know f(1) already
MVI A, 1
MVI B, 0
LOOP: MOV D, A
ADD B ; A := A + B
MOV B, D
DCR C
JNZ LOOP ; jump if not zero
RET ; return from subroutine |
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
| #ActionScript | ActionScript | function factor(n:uint):Vector.<uint>
{
var factors:Vector.<uint> = new Vector.<uint>();
for(var i:uint = 1; i <= n; i++)
if(n % i == 0)factors.push(i);
return 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.
| #D | D | void main() {
import std.stdio, std.numeric;
[1.0, 1, 1, 1, 0, 0, 0, 0].fft.writeln;
} |
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number | Factors of a Mersenne number | A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test.
There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1).
Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar).
The following is how to implement this modPow yourself:
For example, let's compute 223 mod 47.
Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it.
Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47.
Use the result of the modulo from the last step as the initial value of square in the next step:
remove optional
square top bit multiply by 2 mod 47
──────────── ─────── ───────────── ──────
1*1 = 1 1 0111 1*2 = 2 2
2*2 = 4 0 111 no 4
4*4 = 16 1 11 16*2 = 32 32
32*32 = 1024 1 1 1024*2 = 2048 27
27*27 = 729 1 729*2 = 1458 1
Since 223 mod 47 = 1, 47 is a factor of 2P-1.
(To see this, subtract 1 from both sides: 223-1 = 0 mod 47.)
Since we've shown that 47 is a factor, 223-1 is not prime.
Further properties of Mersenne numbers allow us to refine the process even more.
Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8.
Finally any potential factor q must be prime.
As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N).
These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1.
Task
Using the above method find a factor of 2929-1 (aka M929)
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
See also
Computers in 1948: 2127 - 1
(Note: This video is no longer available because the YouTube account associated with this video has been terminated.)
| #Clojure | Clojure | (ns mersennenumber
(:gen-class))
(defn m* [p q m]
" Computes (p*q) mod m "
(mod (*' p q) m))
(defn power
"modular exponentiation (i.e. b^e mod m"
[b e m]
(loop [b b, e e, x 1]
(if (zero? e)
x
(if (even? e) (recur (m* b b m) (quot e 2) x)
(recur (m* b b m) (quot e 2) (m* b x m))))))
(defn divides? [k n]
" checks if k divides n "
(= (rem n k) 0))
(defn is-prime? [n]
" checks if n is prime "
(cond
(< n 2) false ; 0, 1 not prime (i.e. primes are greater than one)
(= n 2) true ; 2 is prime
(= 0 (mod n 2)) false ; all other evens are not prime
:else ; check for divisors up to sqrt(n)
(empty? (filter #(divides? % n) (take-while #(<= (* % %) n) (range 2 n))))))
;; Max k to check
(def MAX-K 16384)
(defn trial-factor [p k]
" check if k satisfies 2*k*P + 1 divides 2^p - 1 "
(let [q (+ (* 2 p k) 1)
mq (mod q 8)]
(cond
(not (is-prime? q)) nil
(and (not= 1 mq)
(not= 7 mq)) nil
(= 1 (power 2 p q)) q
:else nil)))
(defn m-factor [p]
" searches for k-factor "
(some #(trial-factor p %) (range 16384)))
(defn -main [p]
(if-not (is-prime? p)
(format "M%d = 2^%d - 1 exponent is not prime" p p)
(if-let [factor (m-factor p)]
(format "M%d = 2^%d - 1 is composite with factor %d" p p factor)
(format "M%d = 2^%d - 1 is prime" p p))))
;; Tests different p values
(doseq [p [2,3,4,5,7,11,13,17,19,23,29,31,37,41,43,47,53,929]
:let [s (-main p)]]
(println s))
|
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #FreeBASIC | FreeBASIC | ' version 05-04-2017
' compile with: fbc -s console
' TRUE/FALSE are built-in constants since FreeBASIC 1.04
' But we have to define them for older versions.
#Ifndef TRUE
#Define FALSE 0
#Define TRUE Not FALSE
#EndIf
Function farey(n As ULong, descending As Long) As ULong
Dim As Long a, b = 1, c = 1, d = n, k
Dim As Long aa, bb, cc, dd, count
If descending = TRUE Then
a = 1 : c = n -1
End If
count += 1
If n < 12 Then Print Str(a); "/"; Str(b); " ";
While ((c <= n) And Not descending) Or ((a > 0) And descending)
aa = a : bb = b : cc = c : dd = d
k = (n + b) \ d
a = cc : b = dd : c = k * cc - aa : d = k * dd - bb
count += 1
If n < 12 Then Print Str(a); "/"; Str(b); " ";
Wend
If n < 12 Then Print
Return count
End Function
' ------=< MAIN >=------
For i As Long = 1 To 11
Print "F"; Str(i); " = ";
farey(i, FALSE)
Next
Print
For i As Long= 100 To 1000 Step 100
Print "F";Str(i);
Print iif(i <> 1000, " ", ""); " = ";
Print Using "######"; farey(i, FALSE)
Next
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Fairshare]
Fairshare[n_List, b_Integer : 2] := Fairshare[#, b] & /@ n
Fairshare[n_Integer, b_Integer : 2] := Mod[Total[IntegerDigits[n, b]], b]
Fairshare[Range[0, 24], 2]
Fairshare[Range[0, 24], 3]
Fairshare[Range[0, 24], 5]
Fairshare[Range[0, 24], 11] |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #Nim | Nim | import math, strutils
#---------------------------------------------------------------------------------------------------
iterator countInBase(b: Positive): seq[Natural] =
## Yield the successive integers in base "b" as a sequence of digits.
var value = @[Natural 0]
yield value
while true:
# Add one to current value.
var c = 1
for i in countdown(value.high, 0):
let val = value[i] + c
if val < b:
value[i] = val
c = 0
else:
value[i] = val - b
c = 1
if c == 1:
# Add a new digit at the beginning.
# In this case, for better performances, we could have add it at the end.
value.insert(c, 0)
yield value
#---------------------------------------------------------------------------------------------------
func thueMorse(b: Positive; count: Natural): seq[Natural] =
## Return the "count" first elements of Thue-Morse sequence for base "b".
var count = count
for n in countInBase(b):
result.add(sum(n) mod b)
dec count
if count == 0: break
#———————————————————————————————————————————————————————————————————————————————————————————————————
for base in [2, 3, 5, 11]:
echo "Base ", ($base & ": ").alignLeft(4), thueMorse(base, 25).join(" ") |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #Perl | Perl | use strict;
use warnings;
use Math::AnyNum qw(sum polymod);
sub fairshare {
my($b, $n) = @_;
sprintf '%3d'x$n, map { sum ( polymod($_, $b, $b )) % $b } 0 .. $n-1;
}
for (<2 3 5 11>) {
printf "%3s:%s\n", $_, fairshare($_, 25);
} |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #Julia | Julia | function bernoulli(n)
A = Vector{Rational{BigInt}}(undef, n + 1)
for i in 0:n
A[i + 1] = 1 // (i + 1)
for j = i:-1:1
A[j] = j * (A[j] - A[j + 1])
end
end
return n == 1 ? -A[1] : A[1]
end
function faulhabercoeffs(p)
coeffs = Vector{Rational{BigInt}}(undef, p + 1)
q = Rational{BigInt}(1, p + 1)
sign = -1
for j in 0:p
sign *= -1
coeffs[p - j + 1] = bernoulli(j) * (q * sign) * Rational{BigInt}(binomial(p + 1, j), 1)
end
coeffs
end
faulhabersum(n, k) = begin coe = faulhabercoeffs(k); mapreduce(i -> BigInt(n)^i * coe[i], +, 1:k+1) end
prettyfrac(x) = (x.num == 0 ? "0" : x.den == 1 ? string(x.num) : replace(string(x), "//" => "/"))
function testfaulhaber()
for i in 0:9
for c in faulhabercoeffs(i)
print(prettyfrac(c), "\t")
end
println()
end
println("\n", prettyfrac(faulhabersum(1000, 17)))
end
testfaulhaber()
|
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #Kotlin | Kotlin | // version 1.1.2
import java.math.BigDecimal
import java.math.MathContext
val mc = MathContext(256)
fun gcd(a: Long, b: Long): Long = if (b == 0L) a else gcd(b, a % b)
class Frac : Comparable<Frac> {
val num: Long
val denom: Long
companion object {
val ZERO = Frac(0, 1)
val ONE = Frac(1, 1)
}
constructor(n: Long, d: Long) {
require(d != 0L)
var nn = n
var dd = d
if (nn == 0L) {
dd = 1
}
else if (dd < 0) {
nn = -nn
dd = -dd
}
val g = Math.abs(gcd(nn, dd))
if (g > 1) {
nn /= g
dd /= g
}
num = nn
denom = dd
}
constructor(n: Int, d: Int) : this(n.toLong(), d.toLong())
operator fun plus(other: Frac) =
Frac(num * other.denom + denom * other.num, other.denom * denom)
operator fun unaryMinus() = Frac(-num, denom)
operator fun minus(other: Frac) = this + (-other)
operator fun times(other: Frac) = Frac(this.num * other.num, this.denom * other.denom)
fun abs() = if (num >= 0) this else -this
override fun compareTo(other: Frac): Int {
val diff = this.toDouble() - other.toDouble()
return when {
diff < 0.0 -> -1
diff > 0.0 -> +1
else -> 0
}
}
override fun equals(other: Any?): Boolean {
if (other == null || other !is Frac) return false
return this.compareTo(other) == 0
}
override fun toString() = if (denom == 1L) "$num" else "$num/$denom"
fun toDouble() = num.toDouble() / denom
fun toBigDecimal() = BigDecimal(num).divide(BigDecimal(denom), mc)
}
fun bernoulli(n: Int): Frac {
require(n >= 0)
val a = Array(n + 1) { Frac.ZERO }
for (m in 0..n) {
a[m] = Frac(1, m + 1)
for (j in m downTo 1) a[j - 1] = (a[j - 1] - a[j]) * Frac(j, 1)
}
return if (n != 1) a[0] else -a[0] // returns 'first' Bernoulli number
}
fun binomial(n: Int, k: Int): Long {
require(n >= 0 && k >= 0 && n >= k)
if (n == 0 || k == 0) return 1
val num = (k + 1..n).fold(1L) { acc, i -> acc * i }
val den = (2..n - k).fold(1L) { acc, i -> acc * i }
return num / den
}
fun faulhaberTriangle(p: Int): Array<Frac> {
val coeffs = Array(p + 1) { Frac.ZERO }
val q = Frac(1, p + 1)
var sign = -1
for (j in 0..p) {
sign *= -1
coeffs[p - j] = q * Frac(sign, 1) * Frac(binomial(p + 1, j), 1) * bernoulli(j)
}
return coeffs
}
fun main(args: Array<String>) {
for (i in 0..9){
val coeffs = faulhaberTriangle(i)
for (coeff in coeffs) print("${coeff.toString().padStart(5)} ")
println()
}
println()
// get coeffs for (k + 1)th row
val k = 17
val cc = faulhaberTriangle(k)
val n = 1000
val nn = BigDecimal(n)
var np = BigDecimal.ONE
var sum = BigDecimal.ZERO
for (c in cc) {
np *= nn
sum += np * c.toBigDecimal()
}
println(sum.toBigInteger())
} |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | ClearAll[Faulhaber]
Faulhaber[n_, 0] := n
Faulhaber[n_, p_] := n^(p + 1)/(p + 1) + 1/2 n^p + Sum[BernoulliB[k]/k! p!/(p - k + 1)! n^(p - k + 1), {k, 2, p}]
Table[{p, Faulhaber[n, p]}, {p, 0, 9}] // Grid |
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
| #Common_Lisp | Common Lisp |
(defun gen-fib (lst m)
"Return the first m members of a generalized Fibonacci sequence using lst as initial values
and the length of lst as step."
(let ((l (- (length lst) 1)))
(do* ((fib-list (reverse lst) (cons (loop for i from 0 to l sum (nth i fib-list)) fib-list))
(c (+ l 2) (+ c 1)))
((> c m) (reverse fib-list)))))
(defun initial-values (n)
"Return the initial values of the Fibonacci n-step sequence"
(cons 1
(loop for i from 0 to (- n 2)
collect (expt 2 i))))
(defun start ()
(format t "Lucas series: ~a~%" (gen-fib '(2 1) 10))
(loop for i from 2 to 4
do (format t "Fibonacci ~a-step sequence: ~a~%" i (gen-fib (initial-values i) 10)))) |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Python | Python | >>> import os
>>> os.path.commonpath(['/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator', '/home/user1/tmp/coven/members'])
'/home/user1/tmp' |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #R | R |
get_common_dir <- function(paths, delim = "/")
{
path_chunks <- strsplit(paths, delim)
i <- 1
repeat({
current_chunk <- sapply(path_chunks, function(x) x[i])
if(any(current_chunk != current_chunk[1])) break
i <- i + 1
})
paste(path_chunks[[1]][seq_len(i - 1)], collapse = delim)
}
# Example Usage:
paths <- c(
'/home/user1/tmp/coverage/test',
'/home/user1/tmp/covert/operator',
'/home/user1/tmp/coven/members')
get_common_dir(paths) # "/home/user1/tmp"
|
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.
| #Elena | Elena | import system'routines;
import system'math;
import extensions;
import extensions'routines;
public program()
{
auto array := new int[]{1,2,3,4,5};
var evens := array.filterBy:(n => n.mod:2 == 0).toArray();
evens.forEach:printingLn
} |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #TSE_SAL | TSE SAL |
// library: program: run: recursion: limit <description>will stop at 3616</description> <version>1.0.0.0.3</version> <version control></version control> (filenamemacro=runprrli.s) [kn, ri, su, 25-12-2011 23:12:02]
PROC PROCProgramRunRecursionLimit( INTEGER I )
Message( I )
PROCProgramRunRecursionLimit( I + 1 )
END
PROC Main()
PROCProgramRunRecursionLimit( 1 )
END
|
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #TXR | TXR | (set-sig-handler sig-segv
(lambda (signal async-p) (throw 'out)))
(defvar *count* 0)
(defun recurse ()
(inc *count*)
(recurse))
(catch (recurse)
(out () (put-line `caught segfault!\nreached depth: @{*count*}`))) |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #UNIX_Shell | UNIX Shell | recurse()
{
# since the example runs slowly, the following
# if-elif avoid unuseful output; the elif was
# added after a first run ended with a segmentation
# fault after printing "10000"
if [[ $(($1 % 5000)) -eq 0 ]]; then
echo $1;
elif [[ $1 -gt 10000 ]]; then
echo $1
fi
recurse $(($1 + 1))
}
recurse 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
| #Hoon | Hoon | :- %say
|= [^ ~ ~]
:- %noun
%+ turn (gulf [1 101])
|= a=@
=+ q=[=(0 (mod a 3)) =(0 (mod a 5))]
?+ q <a>
[& &] "FizzBuzz"
[& |] "Fizz"
[| &] "Buzz"
== |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #RapidQ | RapidQ | $INCLUDE "rapidq.inc"
DIM file AS QFileStream
FUNCTION fileSize(name$) AS Integer
file.Open(name$, fmOpenRead)
Result = file.Size
file.Close
END FUNCTION
PRINT "Size of input.txt is "; fileSize("input.txt")
PRINT "Size of \input.txt is "; fileSize("\input.txt") |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Raven | Raven | 'input.txt' status.size
'/input.txt' status.size |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #REBOL | REBOL | size? %info.txt
size? %/info.txt
size? ftp://username:[email protected]/info.txt
size? http://rosettacode.org |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #J | J | 'output.txt' (1!:2~ 1!:1)&< 'input.txt' |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #Java | Java | import java.io.*;
public class FileIODemo {
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("input.txt");
FileOutputStream out = new FileOutputStream("ouput.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
} |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #Oforth | Oforth | : entropy(s) -- f
| freq sz |
s size dup ifZero: [ return ] asFloat ->sz
ListBuffer initValue(255, 0) ->freq
s apply( #[ dup freq at 1+ freq put ] )
0.0 freq applyIf( #[ 0 <> ], #[ sz / dup ln * - ] ) Ln2 / ;
: FWords(n)
| ws i |
ListBuffer new dup add("1") dup add("0") dup ->ws
3 n for: i [ i 1- ws at i 2 - ws at + ws add ]
dup map(#[ dup size swap entropy Pair new]) apply(#println) ; |
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #ooRexx | ooRexx | /* REXX ---------------------------------------------------------------
* 09.08.2014 Walter Pachl 'copied' from REXX
* lists the # of chars in fibonacci words and the words' entropy
* as well as (part of) the Fibonacci word and the number of 0's and 1's
* Note: ooRexx allows for computing up to 47 Fibonacci words
*--------------------------------------------------------------------*/
Numeric Digits 20 /* use more precision, default=9.*/
Parse Arg n fw.1 fw.2 . /* get optional args from the C.L.*/
If n=='' Then n=50 /* Not specified? Then use default*/
If fw.1=='' Then fw.1=1 /* " " " " " */
If fw.2=='' Then fw.2=0 /* " " " " " */
hdr1=' N length Entropy Fibonacci word ',
'# of zeroes # of ones'
hdr2='-- ---------- ---------------------- --------------------',
'--------- ---------'
Say hdr1
Say hdr2
Do j=1 For n /* display N fibonacci words. */
j1=j-1
j2=j-2
If j>2 Then /* calculate FIBword if we need to*/
fw.j=fw.j1||fw.j2
If length(fw.j)<20 Then
fwd=left(fw.j,20) /* display the Fibonacci word */
Else
fwd=left(fw.j,5)'...'right(fw.j,12) /* display parts thereof */
Say right(j,2)' 'right(length(fw.j),9)' 'entropy(fw.j)' 'fwd,
right(aa.0,9) right(aa.1,9)
End
Say hdr2
Say hdr1
Exit
entropy: Procedure Expose aa.
Parse Arg dd
l=length(dd)
d=digits()
aa.0=l-length(space(translate(dd,,0),0)) /*fast way to count zeroes*/
aa.1=l-aa.0 /* and figure the number of ones. */
If l==1 Then
Return left(0,d+2) /* handle special case of one char*/
s=0 /* [?] calc entropy for each char */
do i=1 for 2
_=i-1 /* construct a chr from the ether.*/
p=aa._/l /* 'probability of aa-_ in fw */
s=s-p*rxmlog(p,d,2) /* add (negatively) the entropies.*/
End
If s=1 Then
Return left(1,d+2) /* return a left-justified "1". */
Return format(s,,d) /* normalize the number (sum or S)*/
::requires rxm.cls |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #R | R |
library("seqinr")
data <- c(">Rosetta_Example_1","THERECANBENOSPACE",">Rosetta_Example_2","THERECANBESEVERAL","LINESBUTTHEYALLMUST","BECONCATENATED")
fname <- "rosettacode.fasta"
f <- file(fname,"w+")
writeLines(data,f)
close(f)
fasta <- read.fasta(file = fname, as.string = TRUE, seqtype = "AA")
for (aline in fasta) {
cat(attr(aline, 'Annot'), ":", aline, "\n")
}
|
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Racket | Racket |
#lang racket
(let loop ([m #t])
(when m
(when (regexp-try-match #rx"^>" (current-input-port))
(unless (eq? #t m) (newline))
(printf "~a: " (read-line)))
(loop (regexp-match #rx"\n" (current-input-port) 0 #f
(current-output-port)))))
(newline)
|
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Raku | Raku | grammar FASTA {
rule TOP { <entry>+ }
rule entry { \> <title> <sequence> }
token title { <.alnum>+ }
token sequence { ( <.alnum>+ )+ % \n { make $0.join } }
}
FASTA.parse: q:to /§/;
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
§
for $/<entry>[] {
say ~.<title>, " : ", .<sequence>.made;
} |
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
| #8086_Assembly | 8086 Assembly | fib:
; WRITTEN IN C WITH X86-64 CLANG 3.3 AND DOWNGRADED TO 16-BIT X86
; INPUT: DI = THE NUMBER YOU WISH TO CALC THE FIBONACCI NUMBER FOR.
; OUTPUTS TO AX
push BP
push BX
push AX
mov BX, DI ;COPY INPUT TO BX
xor AX, AX ;MOV AX,0
test BX, BX ;SET FLAGS ACCORDING TO BX
je LBB0_4 ;IF BX == 0 RETURN 0
cmp BX, 1 ;IF BX == 1 RETURN 1
jne LBB0_3
mov AX, 1 ;ELSE, SET AX = 1 AND RETURN
jmp LBB0_4
LBB0_3:
lea DI, WORD PTR [BX - 1] ;DI = BX - 1
call fib ;RETURN FIB(BX-1)
mov BP, AX ;STORE THIS IN BP
add BX, -2
mov DI, BX
call fib ;GET FIB(DI - 2)
add AX, BP ;RETURN FIB(DI - 1) + FIB(DI - 2)
LBB0_4:
add sp,2
pop BX
pop BP
ret |
http://rosettacode.org/wiki/Factors_of_an_integer | Factors of an integer |
Basic Data Operation
This is a basic data operation. It represents a fundamental action on a basic data type.
You may see other such operations in the Basic Data Operations category, or:
Integer Operations
Arithmetic |
Comparison
Boolean Operations
Bitwise |
Logical
String Operations
Concatenation |
Interpolation |
Comparison |
Matching
Memory Operations
Pointers & references |
Addresses
Task
Compute the factors of a positive integer.
These factors are the positive integers by which the number being factored can be divided to yield a positive integer result.
(Though the concepts function correctly for zero and negative integers, the set of factors of zero has countably infinite members, and the factors of negative integers can be obtained from the factors of related positive numbers without difficulty; this task does not require handling of either of these cases).
Note that every prime number has two factors: 1 and itself.
Related tasks
count in factors
prime decomposition
Sieve of Eratosthenes
primality by trial division
factors of a Mersenne number
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
sequence: smallest number greater than previous term with exactly n divisors
| #Ada | Ada | with Ada.Text_IO;
with Ada.Command_Line;
procedure Factors is
Number : Positive;
Test_Nr : Positive := 1;
begin
if Ada.Command_Line.Argument_Count /= 1 then
Ada.Text_IO.Put (Ada.Text_IO.Standard_Error, "Missing argument!");
Ada.Command_Line.Set_Exit_Status (Ada.Command_Line.Failure);
return;
end if;
Number := Positive'Value (Ada.Command_Line.Argument (1));
Ada.Text_IO.Put ("Factors of" & Positive'Image (Number) & ": ");
loop
if Number mod Test_Nr = 0 then
Ada.Text_IO.Put (Positive'Image (Test_Nr) & ",");
end if;
exit when Test_Nr ** 2 >= Number;
Test_Nr := Test_Nr + 1;
end loop;
Ada.Text_IO.Put_Line (Positive'Image (Number) & ".");
end 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.
| #Delphi | Delphi |
program Fast_Fourier_transform;
{$APPTYPE CONSOLE}
uses
System.SysUtils,
System.VarCmplx,
System.Math;
function BitReverse(n: UInt64; bits: Integer): UInt64;
var
count, reversedN: UInt64;
begin
reversedN := n;
count := bits - 1;
n := n shr 1;
while n > 0 do
begin
reversedN := (reversedN shl 1) or (n and 1);
dec(count);
n := n shr 1;
end;
Result := ((reversedN shl count) and ((1 shl bits) - 1));
end;
procedure FFT(var buffer: TArray<Variant>);
var
j, bits: Integer;
tmp: Variant;
begin
bits := Trunc(Log2(length(buffer)));
for j := 1 to High(buffer) do
begin
var swapPos := BitReverse(j, bits);
if swapPos <= j then
Continue;
tmp := buffer[j];
buffer[j] := buffer[swapPos];
buffer[swapPos] := tmp;
end;
var N := 2;
while N <= Length(buffer) do
begin
var i := 0;
while i < Length(buffer) do
begin
for var k := 0 to N div 2 - 1 do
begin
var evenIndex := i + k;
var oddIndex := i + k + (N div 2);
var _even := buffer[evenIndex];
var _odd := buffer[oddIndex];
var term := -2 * PI * k / N;
var _exp := VarComplexCreate(Cos(term), Sin(term)) * _odd;
buffer[evenIndex] := _even + _exp;
buffer[oddIndex] := _even - _exp;
end;
i := i + N;
end;
N := N shl 1;
end;
end;
const
input: array of Double = [1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0];
var
inputc: TArray<Variant>;
begin
SetLength(inputc, length(input));
for var i := 0 to High(input) do
inputc[i] := VarComplexCreate(input[i]);
FFT(inputc);
for var c in inputc do
writeln(c);
readln;
end. |
http://rosettacode.org/wiki/Factors_of_a_Mersenne_number | Factors of a Mersenne number | A Mersenne number is a number in the form of 2P-1.
If P is prime, the Mersenne number may be a Mersenne prime
(if P is not prime, the Mersenne number is also not prime).
In the search for Mersenne prime numbers it is advantageous to eliminate exponents by finding a small factor before starting a, potentially lengthy, Lucas-Lehmer test.
There are very efficient algorithms for determining if a number divides 2P-1 (or equivalently, if 2P mod (the number) = 1).
Some languages already have built-in implementations of this exponent-and-mod operation (called modPow or similar).
The following is how to implement this modPow yourself:
For example, let's compute 223 mod 47.
Convert the exponent 23 to binary, you get 10111. Starting with square = 1, repeatedly square it.
Remove the top bit of the exponent, and if it's 1 multiply square by the base of the exponentiation (2), then compute square modulo 47.
Use the result of the modulo from the last step as the initial value of square in the next step:
remove optional
square top bit multiply by 2 mod 47
──────────── ─────── ───────────── ──────
1*1 = 1 1 0111 1*2 = 2 2
2*2 = 4 0 111 no 4
4*4 = 16 1 11 16*2 = 32 32
32*32 = 1024 1 1 1024*2 = 2048 27
27*27 = 729 1 729*2 = 1458 1
Since 223 mod 47 = 1, 47 is a factor of 2P-1.
(To see this, subtract 1 from both sides: 223-1 = 0 mod 47.)
Since we've shown that 47 is a factor, 223-1 is not prime.
Further properties of Mersenne numbers allow us to refine the process even more.
Any factor q of 2P-1 must be of the form 2kP+1, k being a positive integer or zero. Furthermore, q must be 1 or 7 mod 8.
Finally any potential factor q must be prime.
As in other trial division algorithms, the algorithm stops when 2kP+1 > sqrt(N).
These primality tests only work on Mersenne numbers where P is prime. For example, M4=15 yields no factors using these techniques, but factors into 3 and 5, neither of which fit 2kP+1.
Task
Using the above method find a factor of 2929-1 (aka M929)
Related tasks
count in factors
prime decomposition
factors of an integer
Sieve of Eratosthenes
primality by trial division
trial factoring of a Mersenne number
partition an integer X into N primes
sequence of primes by Trial Division
See also
Computers in 1948: 2127 - 1
(Note: This video is no longer available because the YouTube account associated with this video has been terminated.)
| #CoffeeScript | CoffeeScript | mersenneFactor = (p) ->
limit = Math.sqrt(Math.pow(2,p) - 1)
k = 1
while (2*k*p - 1) < limit
q = 2*k*p + 1
if isPrime(q) and (q % 8 == 1 or q % 8 == 7) and trialFactor(2,p,q)
return q
k++
return null
isPrime = (value) ->
for i in [2...value]
return false if value % i == 0
return true if value % i != 0
trialFactor = (base, exp, mod) ->
square = 1
bits = exp.toString(2).split('')
for bit in bits
square = Math.pow(square, 2) * (if +bit is 1 then base else 1) % mod
return square == 1
checkMersenne = (p) ->
factor = mersenneFactor(+p)
console.log "M#{p} = 2^#{p}-1 is #{if factor is null then "prime" else "composite with #{factor}"}"
checkMersenne(prime) for prime in ["2","3","4","5","7","11","13","17","19","23","29","31","37","41","43","47","53","929"]
|
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #FunL | FunL | def farey( n ) =
res = seq()
a, b, c, d = 0, 1, 1, n
res += "$a/$b"
while c <= n
k = (n + b)\d
a, b, c, d = c, d, k*c - a, k*d - b
res += "$a/$b"
for i <- 1..11
println( "$i: ${farey(i).mkString(', ')}" )
for i <- 100..1000 by 100
println( "$i: ${farey(i).length()}" ) |
http://rosettacode.org/wiki/Farey_sequence | Farey sequence | The Farey sequence Fn of order n is the sequence of completely reduced fractions between 0 and 1 which, when in lowest terms, have denominators less than or equal to n, arranged in order of increasing size.
The Farey sequence is sometimes incorrectly called a Farey series.
Each Farey sequence:
starts with the value 0 (zero), denoted by the fraction
0
1
{\displaystyle {\frac {0}{1}}}
ends with the value 1 (unity), denoted by the fraction
1
1
{\displaystyle {\frac {1}{1}}}
.
The Farey sequences of orders 1 to 5 are:
F
1
=
0
1
,
1
1
{\displaystyle {\bf {\it {F}}}_{1}={\frac {0}{1}},{\frac {1}{1}}}
F
2
=
0
1
,
1
2
,
1
1
{\displaystyle {\bf {\it {F}}}_{2}={\frac {0}{1}},{\frac {1}{2}},{\frac {1}{1}}}
F
3
=
0
1
,
1
3
,
1
2
,
2
3
,
1
1
{\displaystyle {\bf {\it {F}}}_{3}={\frac {0}{1}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {1}{1}}}
F
4
=
0
1
,
1
4
,
1
3
,
1
2
,
2
3
,
3
4
,
1
1
{\displaystyle {\bf {\it {F}}}_{4}={\frac {0}{1}},{\frac {1}{4}},{\frac {1}{3}},{\frac {1}{2}},{\frac {2}{3}},{\frac {3}{4}},{\frac {1}{1}}}
F
5
=
0
1
,
1
5
,
1
4
,
1
3
,
2
5
,
1
2
,
3
5
,
2
3
,
3
4
,
4
5
,
1
1
{\displaystyle {\bf {\it {F}}}_{5}={\frac {0}{1}},{\frac {1}{5}},{\frac {1}{4}},{\frac {1}{3}},{\frac {2}{5}},{\frac {1}{2}},{\frac {3}{5}},{\frac {2}{3}},{\frac {3}{4}},{\frac {4}{5}},{\frac {1}{1}}}
Task
Compute and show the Farey sequence for orders 1 through 11 (inclusive).
Compute and display the number of fractions in the Farey sequence for order 100 through 1,000 (inclusive) by hundreds.
Show the fractions as n/d (using the solidus [or slash] to separate the numerator from the denominator).
The length (the number of fractions) of a Farey sequence asymptotically approaches:
3 × n2 ÷
π
{\displaystyle \pi }
2
See also
OEIS sequence A006842 numerators of Farey series of order 1, 2, ···
OEIS sequence A006843 denominators of Farey series of order 1, 2, ···
OEIS sequence A005728 number of fractions in Farey series of order n
MathWorld entry Farey sequence
Wikipedia entry Farey sequence
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import "fmt"
type frac struct{ num, den int }
func (f frac) String() string {
return fmt.Sprintf("%d/%d", f.num, f.den)
}
func f(l, r frac, n int) {
m := frac{l.num + r.num, l.den + r.den}
if m.den <= n {
f(l, m, n)
fmt.Print(m, " ")
f(m, r, n)
}
}
func main() {
// task 1. solution by recursive generation of mediants
for n := 1; n <= 11; n++ {
l := frac{0, 1}
r := frac{1, 1}
fmt.Printf("F(%d): %s ", n, l)
f(l, r, n)
fmt.Println(r)
}
// task 2. direct solution by summing totient function
// 2.1 generate primes to 1000
var composite [1001]bool
for _, p := range []int{2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31} {
for n := p * 2; n <= 1000; n += p {
composite[n] = true
}
}
// 2.2 generate totients to 1000
var tot [1001]int
for i := range tot {
tot[i] = 1
}
for n := 2; n <= 1000; n++ {
if !composite[n] {
tot[n] = n - 1
for a := n * 2; a <= 1000; a += n {
f := n - 1
for r := a / n; r%n == 0; r /= n {
f *= n
}
tot[a] *= f
}
}
}
// 2.3 sum totients
for n, sum := 1, 1; n <= 1000; n++ {
sum += tot[n]
if n%100 == 0 {
fmt.Printf("|F(%d)|: %d\n", n, sum)
}
}
} |
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #Phix | Phix | function fairshare(integer n, base)
sequence res = repeat(0,n)
for i=1 to n do
integer j = i-1,
t = 0
while j>0 do
t += remainder(j,base)
j = floor(j/base)
end while
res[i] = remainder(t,base)
end for
return {base,res}
end function
constant tests = {2,3,5,11}
for i=1 to length(tests) do
printf(1,"%2d : %v\n", fairshare(25, tests[i]))
end for
|
http://rosettacode.org/wiki/Fairshare_between_two_and_more | Fairshare between two and more | The Thue-Morse sequence is a sequence of ones and zeros that if two people
take turns in the given order, the first persons turn for every '0' in the
sequence, the second for every '1'; then this is shown to give a fairer, more
equitable sharing of resources. (Football penalty shoot-outs for example, might
not favour the team that goes first as much if the penalty takers take turns
according to the Thue-Morse sequence and took 2^n penalties)
The Thue-Morse sequence of ones-and-zeroes can be generated by:
"When counting in binary, the digit sum modulo 2 is the Thue-Morse sequence"
Sharing fairly between two or more
Use this method:
When counting base b, the digit sum modulo b is the Thue-Morse sequence of fairer sharing between b people.
Task
Counting from zero; using a function/method/routine to express an integer count in base b,
sum the digits modulo b to produce the next member of the Thue-Morse fairshare series for b people.
Show the first 25 terms of the fairshare sequence:
For two people:
For three people
For five people
For eleven people
Related tasks
Non-decimal radices/Convert
Thue-Morse
See also
A010060, A053838, A053840: The On-Line Encyclopedia of Integer Sequences® (OEIS®)
| #Python | Python | from itertools import count, islice
def _basechange_int(num, b):
"""
Return list of ints representing positive num in base b
>>> b = 3
>>> print(b, [_basechange_int(num, b) for num in range(11)])
3 [[0], [1], [2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [1, 0, 0], [1, 0, 1]]
>>>
"""
if num == 0:
return [0]
result = []
while num != 0:
num, d = divmod(num, b)
result.append(d)
return result[::-1]
def fairshare(b=2):
for i in count():
yield sum(_basechange_int(i, b)) % b
if __name__ == '__main__':
for b in (2, 3, 5, 11):
print(f"{b:>2}: {str(list(islice(fairshare(b), 25)))[1:-1]}") |
http://rosettacode.org/wiki/Faulhaber%27s_triangle | Faulhaber's triangle | Named after Johann Faulhaber, the rows of Faulhaber's triangle are the coefficients of polynomials that represent sums of integer powers, which are extracted from Faulhaber's formula:
∑
k
=
1
n
k
p
=
1
p
+
1
∑
j
=
0
p
(
p
+
1
j
)
B
j
n
p
+
1
−
j
{\displaystyle \sum _{k=1}^{n}k^{p}={1 \over p+1}\sum _{j=0}^{p}{p+1 \choose j}B_{j}n^{p+1-j}}
where
B
n
{\displaystyle B_{n}}
is the nth-Bernoulli number.
The first 5 rows of Faulhaber's triangle, are:
1
1/2 1/2
1/6 1/2 1/3
0 1/4 1/2 1/4
-1/30 0 1/3 1/2 1/5
Using the third row of the triangle, we have:
∑
k
=
1
n
k
2
=
1
6
n
+
1
2
n
2
+
1
3
n
3
{\displaystyle \sum _{k=1}^{n}k^{2}={1 \over 6}n+{1 \over 2}n^{2}+{1 \over 3}n^{3}}
Task
show the first 10 rows of Faulhaber's triangle.
using the 18th row of Faulhaber's triangle, compute the sum:
∑
k
=
1
1000
k
17
{\displaystyle \sum _{k=1}^{1000}k^{17}}
(extra credit).
See also
Bernoulli numbers
Evaluate binomial coefficients
Faulhaber's formula (Wikipedia)
Faulhaber's triangle (PDF)
| #Lua | Lua | function binomial(n,k)
if n<0 or k<0 or n<k then return -1 end
if n==0 or k==0 then return 1 end
local num = 1
for i=k+1,n do
num = num * i
end
local denom = 1
for i=2,n-k do
denom = denom * i
end
return num / denom
end
function gcd(a,b)
while b ~= 0 do
local temp = a % b
a = b
b = temp
end
return a
end
function makeFrac(n,d)
local result = {}
if d==0 then
result.num = 0
result.denom = 0
return result
end
if n==0 then
d = 1
elseif d < 0 then
n = -n
d = -d
end
local g = math.abs(gcd(n, d))
if g>1 then
n = n / g
d = d / g
end
result.num = n
result.denom = d
return result
end
function negateFrac(f)
return makeFrac(-f.num, f.denom)
end
function subFrac(lhs, rhs)
return makeFrac(lhs.num * rhs.denom - lhs.denom * rhs.num, rhs.denom * lhs.denom)
end
function multFrac(lhs, rhs)
return makeFrac(lhs.num * rhs.num, lhs.denom * rhs.denom)
end
function equalFrac(lhs, rhs)
return (lhs.num == rhs.num) and (lhs.denom == rhs.denom)
end
function lessFrac(lhs, rhs)
return (lhs.num * rhs.denom) < (rhs.num * lhs.denom)
end
function printFrac(f)
local str = tostring(f.num)
if f.denom ~= 1 then
str = str.."/"..f.denom
end
for i=1, 7 - string.len(str) do
io.write(" ")
end
io.write(str)
return nil
end
function bernoulli(n)
if n<0 then
return {num=0, denom=0}
end
local a = {}
for m=0,n do
a[m] = makeFrac(1, m+1)
for j=m,1,-1 do
a[j-1] = multFrac(subFrac(a[j-1], a[j]), makeFrac(j, 1))
end
end
if n~=1 then
return a[0]
end
return negateFrac(a[0])
end
function faulhaber(p)
local q = makeFrac(1, p+1)
local sign = -1
local coeffs = {}
for j=0,p do
sign = -1 * sign
coeffs[p-j] = multFrac(multFrac(multFrac(q, makeFrac(sign, 1)), makeFrac(binomial(p + 1, j), 1)), bernoulli(j))
end
for j=0,p do
printFrac(coeffs[j])
end
print()
return nil
end
-- main
for i=0,9 do
faulhaber(i)
end |
http://rosettacode.org/wiki/Faulhaber%27s_formula | Faulhaber's formula | In mathematics, Faulhaber's formula, named after Johann Faulhaber, expresses the sum of the p-th powers of the first n positive integers as a (p + 1)th-degree polynomial function of n, the coefficients involving Bernoulli numbers.
Task
Generate the first 10 closed-form expressions, starting with p = 0.
Related tasks
Bernoulli numbers.
evaluate binomial coefficients.
See also
The Wikipedia entry: Faulhaber's formula.
The Wikipedia entry: Bernoulli numbers.
The Wikipedia entry: binomial coefficients.
| #Maxima | Maxima | sum1(p):=sum(stirling2(p,k)*pochhammer(n-k+1,k+1)/(k+1),k,0,p)$
sum2(p):=sum((-1)^j*binomial(p+1,j)*bern(j)*n^(p-j+1),j,0,p)/(p+1)$
makelist(expand(sum1(p)-sum2(p)),p,1,10);
[0,0,0,0,0,0,0,0,0,0]
for p from 0 thru 9 do print(expand(sum2(p))); |
http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences | Fibonacci n-step number sequences | These number series are an expansion of the ordinary Fibonacci sequence where:
For
n
=
2
{\displaystyle n=2}
we have the Fibonacci sequence; with initial values
[
1
,
1
]
{\displaystyle [1,1]}
and
F
k
2
=
F
k
−
1
2
+
F
k
−
2
2
{\displaystyle F_{k}^{2}=F_{k-1}^{2}+F_{k-2}^{2}}
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
| #D | D | void main() {
import std.stdio, std.algorithm, std.range, std.conv;
const(int)[] memo;
size_t addNum;
void setHead(int[] head) nothrow @safe {
memo = head;
addNum = head.length;
}
int fibber(in size_t n) nothrow @safe {
if (n >= memo.length)
memo ~= iota(n - addNum, n).map!fibber.sum;
return memo[n];
}
setHead([1, 1]);
10.iota.map!fibber.writeln;
setHead([2, 1]);
10.iota.map!fibber.writeln;
const prefixes = "fibo tribo tetra penta hexa hepta octo nona deca";
foreach (immutable n, const name; prefixes.split.enumerate(2)) {
setHead(1 ~ iota(n - 1).map!q{2 ^^ a}.array);
writefln("n=%2d, %5snacci -> %(%d %) ...", n, name,
15.iota.map!fibber);
}
} |
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Racket | Racket |
#lang racket
(define (common-directory path . paths)
(string-join
(let loop ([path (string-split path "/" #:trim? #f)]
[paths (map (λ(p) (string-split p "/" #:trim? #f)) paths)])
(if (and (pair? path)
(andmap (λ(p) (and (pair? p) (equal? (car p) (car path))))
paths))
(cons (car path) (loop (cdr path) (map cdr paths)))
'()))
"/"))
(common-directory
"/home/user1/tmp/coverage/test"
"/home/user1/tmp/covert/operator"
"/home/user1/tmp/coven/members")
;; --> "/home/user1/tmp"
|
http://rosettacode.org/wiki/Find_common_directory_path | Find common directory path | Create a routine that, given a set of strings representing directory paths and a single character directory separator, will return a string representing that part of the directory tree that is common to all the directories.
Test your routine using the forward slash '/' character as the directory separator and the following three strings as input paths:
'/home/user1/tmp/coverage/test'
'/home/user1/tmp/covert/operator'
'/home/user1/tmp/coven/members'
Note: The resultant path should be the valid directory '/home/user1/tmp' and not the longest common string '/home/user1/tmp/cove'.
If your language has a routine that performs this function (even if it does not have a changeable separator character), then mention it as part of the task.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Raku | Raku | my $sep = '/';
my @dirs = </home/user1/tmp/coverage/test
/home/user1/tmp/covert/operator
/home/user1/tmp/coven/members>;
my @comps = @dirs.map: { [ .comb(/ $sep [ <!before $sep> . ]* /) ] };
my $prefix = '';
while all(@comps[*]»[0]) eq @comps[0][0] {
$prefix ~= @comps[0][0] // last;
@comps».shift;
}
say "The longest common path is $prefix";
|
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.
| #Elixir | Elixir | iex(10)> numbers = Enum.to_list(1..9)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
iex(11)> Enum.filter(numbers, fn x -> rem(x,2)==0 end)
[2, 4, 6, 8]
iex(12)> for x <- numbers, rem(x,2)==0, do: x # comprehension
[2, 4, 6, 8] |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Ursa | Ursa | def recurse (int counter)
try
recurse (+ counter 1)
catch recursionerror
out "the limit of recursion was " counter endl console
end try
end
recurse 1 |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #Vala | Vala | void recur(uint64 v ) {
print (@"$v\n");
recur( v + 1);
}
void main() {
recur(0);
} |
http://rosettacode.org/wiki/Find_limit_of_recursion | Find limit of recursion | Find limit of recursion is part of Short Circuit's Console Program Basics selection.
Task
Find the limit of recursion.
| #VBA | VBA |
Option Explicit
Sub Main()
Debug.Print "The limit is : " & Limite_Recursivite(0)
End Sub
Function Limite_Recursivite(Cpt As Long) As Long
Cpt = Cpt + 1 'Count
On Error Resume Next
Limite_Recursivite Cpt 'recurse
On Error GoTo 0
Limite_Recursivite = Cpt 'return
End Function
|
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
| #Huginn | Huginn | import Algorithms as algo;
main( argv_ ) {
if ( size( argv_ ) < 2 ) {
throw Exception( "usage: fizzbuzz {NUM}" );
}
top = integer( argv_[1] );
for ( i : algo.range( 1, top + 1 ) ) {
by3 = ( i % 3 ) == 0;
by5 = ( i % 5 ) == 0;
if ( by3 ) {
print( "fizz" );
}
if ( by5 ) {
print( "buzz" );
}
if ( ! ( by3 || by5 ) ) {
print( i );
}
print( "\n" );
}
return ( 0 );
} |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Red | Red | >> size? %input.txt
== 39244
>> size? %/c/input.txt
== 39244 |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #Retro | Retro | with files'
"input.txt" :R open &size sip close drop putn
"/input.txt" :R open &size sip close drop putn |
http://rosettacode.org/wiki/File_size | File size | Verify the size of a file called input.txt for a file in the current working directory, and another one in the file system root.
| #REXX | REXX | /*REXX program determines a file's size (by reading all the data) in current dir & root.*/
parse arg iFID . /*allow the user specify the file ID. */
if iFID=='' | iFID=="," then iFID='input.txt' /*Not specified? Then use the default.*/
say 'size of 'iFID "=" fSize(iFID) 'bytes' /*the current directory.*/
say 'size of \..\'iFID "=" fSize('\..\'iFID) 'bytes' /* " root " */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
fSize: parse arg f; $=0; do while chars(f)\==0; $ = $ + length( charin( f, , 1e4) )
end /*while*/; call lineout f /*close file.*/
return $ |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #JavaScript | JavaScript | var fso = new ActiveXObject("Scripting.FileSystemObject");
var ForReading = 1, ForWriting = 2;
var f_in = fso.OpenTextFile('input.txt', ForReading);
var f_out = fso.OpenTextFile('output.txt', ForWriting, true);
// for small files:
// f_out.Write( f_in.ReadAll() );
while ( ! f_in.AtEndOfStream) {
// ReadLine() does not include the newline char
f_out.WriteLine( f_in.ReadLine() );
}
f_in.Close();
f_out.Close(); |
http://rosettacode.org/wiki/File_input/output | File input/output | File input/output is part of Short Circuit's Console Program Basics selection.
Task
Create a file called "output.txt", and place in it the contents of the file "input.txt", via an intermediate variable.
In other words, your program will demonstrate:
how to read from a file into a variable
how to write a variable's contents into a file
Oneliners that skip the intermediate variable are of secondary interest — operating systems have copy commands for that.
| #jq | jq | jq -M --raw-input --raw-output '. as $line | $line' input.txt > output.txt
|
http://rosettacode.org/wiki/Fibonacci_word | Fibonacci word | The Fibonacci Word may be created in a manner analogous to the Fibonacci Sequence as described here:
Define F_Word1 as 1
Define F_Word2 as 0
Form F_Word3 as F_Word2 concatenated with F_Word1 i.e.: 01
Form F_Wordn as F_Wordn-1 concatenated with F_wordn-2
Task
Perform the above steps for n = 37.
You may display the first few but not the larger values of n.
{Doing so will get the task's author into trouble with them what be (again!).}
Instead, create a table for F_Words 1 to 37 which shows:
The number of characters in the word
The word's Entropy
Related tasks
Fibonacci word/fractal
Entropy
Entropy/Narcissist
| #PARI.2FGP | PARI/GP | ent(a,b)=[a,b]=[a,b]/(a+b);(a*log(if(a,a,1))+b*log(if(b,b,1)))/log(1/2)
allocatemem(75<<20) \\ Allocate 75 MB stack space
F=vector(37);F[1]="1";F[2]="0";for(n=3,37,F[n]=Str(F[n-1],F[n-2]))
for(n=1,37,print(n" "fibonacci(n)" "ent(fibonacci(n-1),fibonacci(n-2)))) |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #REXX | REXX | /*REXX program reads a (bio-informational) FASTA file and displays the contents. */
parse arg iFID . /*iFID: the input file to be read. */
if iFID=='' then iFID='FASTA.IN' /*Not specified? Then use the default.*/
name= /*the name of an output file (so far). */
$= /*the value of the output file's stuff.*/
do while lines(iFID)\==0 /*process the FASTA file contents. */
x=strip( linein(iFID), 'T') /*read a line (a record) from the file,*/
/*───────── and strip trailing blanks. */
if left(x, 1)=='>' then do
if $\=='' then say name':' $
name=substr(x, 2)
$=
end
else $=$ || x
end /*j*/ /* [↓] show output of last file used. */
if $\=='' then say name':' $ /*stick a fork in it, we're all done. */ |
http://rosettacode.org/wiki/FASTA_format | FASTA format | In bioinformatics, long character strings are often encoded in a format called FASTA.
A FASTA file can contain several strings, each identified by a name marked by a > (greater than) character at the beginning of the line.
Task
Write a program that reads a FASTA file such as:
>Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED
Output:
Rosetta_Example_1: THERECANBENOSPACE
Rosetta_Example_2: THERECANBESEVERALLINESBUTTHEYALLMUSTBECONCATENATED
Note that a high-quality implementation will not hold the entire file in memory at once; real FASTA files can be multiple gigabytes in size.
| #Ring | Ring |
# Project : FAST format
a = ">Rosetta_Example_1
THERECANBENOSPACE
>Rosetta_Example_2
THERECANBESEVERAL
LINESBUTTHEYALLMUST
BECONCATENATED"
i = 1
while i <= len(a)
if substr(a,i,17) = ">Rosetta_Example_"
see nl
see substr(a,i,18) + ": " + nl
i = i + 17
else
if ascii(substr(a,i,1)) > 20
see a[i]
ok
ok
i = i + 1
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
| #8th | 8th |
: fibon \ n -- fib(n)
>r 0 1
( tuck n:+ ) \ fib(n-2) fib(n-1) -- fib(n-1) fib(n)
r> n:1- times ;
: fib \ n -- fib(n)
dup 1 n:= if 1 ;; then
fibon nip ;
|
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
| #Aikido | Aikido | import math
function factor (n:int) {
var result = []
function append (v) {
if (!(v in result)) {
result.append (v)
}
}
var sqrt = cast<int>(Math.sqrt (n))
append (1)
for (var i = n-1 ; i >= sqrt ; i--) {
if ((n % i) == 0) {
append (i)
append (n/i)
}
}
append (n)
return result.sort()
}
function printvec (vec) {
var comma = ""
print ("[")
foreach v vec {
print (comma + v)
comma = ", "
}
println ("]")
}
printvec (factor (45))
printvec (factor (25))
printvec (factor (100)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.