Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
2
Task/Fusc-sequence/00-META.yaml
Normal file
2
Task/Fusc-sequence/00-META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Fusc_sequence
|
||||
46
Task/Fusc-sequence/00-TASK.txt
Normal file
46
Task/Fusc-sequence/00-TASK.txt
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
;Definitions:
|
||||
The '''fusc''' integer sequence is defined as:
|
||||
::* fusc(0) = 0
|
||||
::* fusc(1) = 1
|
||||
::* for '''n'''>1, the '''n'''<sup>th</sup> term is defined as:
|
||||
::::* if '''n''' is even; fusc(n) = fusc(n/2)
|
||||
::::* if '''n''' is odd; fusc(n) = fusc<big>(</big>(n-1)/2<big>)</big> <big>+</big> fusc<big>(</big>(n+1)/2<big>)</big>
|
||||
|
||||
|
||||
Note that MathWorld's definition starts with unity, not zero. This task will be using the OEIS' version (above).
|
||||
|
||||
|
||||
|
||||
;An observation:
|
||||
:::::* fusc(A) = fusc(B)
|
||||
|
||||
where '''A''' is some non-negative integer expressed in binary, and
|
||||
where '''B''' is the binary value of '''A''' reversed.
|
||||
|
||||
|
||||
|
||||
Fusc numbers are also known as:
|
||||
::* fusc function (named by Dijkstra, 1982)
|
||||
::* Stern's Diatomic series (although it starts with unity, not zero)
|
||||
::* Stern-Brocot sequence (although it starts with unity, not zero)
|
||||
|
||||
|
||||
|
||||
;Task:
|
||||
::* show the first '''61''' fusc numbers (starting at zero) in a horizontal format.
|
||||
::* show the fusc number (and its index) whose length is greater than any previous fusc number length.
|
||||
::::* (the length is the number of decimal digits when the fusc number is expressed in base ten.)
|
||||
::* show all numbers with commas (if appropriate).
|
||||
::* show all output here.
|
||||
|
||||
|
||||
;Related task:
|
||||
::* [[Stern-Brocot_sequence|RosettaCode Stern-Brocot sequence]]
|
||||
<!-- This is similar as "generate primes by trial division", and "generate primes via a sieve". Both Rosetta Code tasks have their uses and methods of generation. !~-->
|
||||
|
||||
|
||||
;Also see:
|
||||
::* the MathWorld entry: [http://mathworld.wolfram.com/SternsDiatomicSeries.html Stern's Diatomic Series].
|
||||
::* the OEIS entry: [http://oeis.org/A2487 A2487].
|
||||
<br><br>
|
||||
|
||||
18
Task/Fusc-sequence/11l/fusc-sequence.11l
Normal file
18
Task/Fusc-sequence/11l/fusc-sequence.11l
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
F fusc(n)
|
||||
V res = [0] * n
|
||||
res[1] = 1
|
||||
L(i) 2 .< n
|
||||
res[i] = I i % 2 == 0 {res[i I/ 2]} E res[(i-1) I/ 2] + res[(i+1) I/ 2]
|
||||
R res
|
||||
|
||||
print(‘First 61 terms:’)
|
||||
print(fusc(61))
|
||||
|
||||
print()
|
||||
print(‘Points in the sequence where an item has more digits than any previous items:’)
|
||||
V f = fusc(20'000'000)
|
||||
V max_len = 0
|
||||
L(i) 0 .< f.len
|
||||
I String(f[i]).len > max_len
|
||||
max_len = String(f[i]).len
|
||||
print((i, f[i]))
|
||||
40
Task/Fusc-sequence/ALGOL-68/fusc-sequence.alg
Normal file
40
Task/Fusc-sequence/ALGOL-68/fusc-sequence.alg
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
BEGIN
|
||||
# calculate some members of the fusc sequence #
|
||||
# f0 = 0, f1 = 1, fn = f(n/2) if n even #
|
||||
# = f(n-1)/2) + f((n+1)/2) if n odd #
|
||||
|
||||
# constructs an array of the first n elements of the fusc sequence #
|
||||
PROC fusc sequence = ( INT n )[]INT:
|
||||
BEGIN
|
||||
[ 0 : n ]INT a;
|
||||
IF n > 0 THEN
|
||||
a[ 0 ] := 0;
|
||||
IF n > 1 THEN
|
||||
a[ 1 ] := 1;
|
||||
INT i2 := 1;
|
||||
FOR i FROM 2 BY 2 TO n - 1 DO
|
||||
a[ i ] := a[ i2 ];
|
||||
a[ i + 1 ] := a[ # j - i # i2 ] + a[ # ( j + 1 ) OVER 2 # i2 + 1 ];
|
||||
i2 +:= 1
|
||||
OD
|
||||
FI
|
||||
FI;
|
||||
a[ 0 : n - 1 AT 0 ]
|
||||
END ; # fusc #
|
||||
|
||||
[]INT f = fusc sequence( 800 000 );
|
||||
FOR i FROM 0 TO 60 DO print( ( " ", whole( f[ i ], 0 ) ) ) OD;
|
||||
print( ( newline ) );
|
||||
# find the lowest elements of the sequence that have 1, 2, 3, etc. digits #
|
||||
print( ( "Sequence elements where number of digits of the value increase:", newline ) );
|
||||
print( ( " n fusc(n)", newline ) );
|
||||
INT digit power := 0;
|
||||
FOR i FROM LWB f TO UPB f DO
|
||||
IF f[ i ] >= digit power THEN
|
||||
# found the first number with this many digits #
|
||||
print( ( whole( i, -8 ), " ", whole( f[ i ], -10 ), newline ) );
|
||||
IF digit power = 0 THEN digit power := 1 FI;
|
||||
digit power *:= 10
|
||||
FI
|
||||
OD
|
||||
END
|
||||
50
Task/Fusc-sequence/AWK/fusc-sequence.awk
Normal file
50
Task/Fusc-sequence/AWK/fusc-sequence.awk
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
# syntax: GAWK -f FUSC_SEQUENCE.AWK
|
||||
# converted from C
|
||||
BEGIN {
|
||||
for (i=0; i<61; i++) {
|
||||
printf("%d ",fusc(i))
|
||||
}
|
||||
printf("\n")
|
||||
print("fusc numbers whose length is greater than any previous fusc number length")
|
||||
printf("%9s %9s\n","fusc","index")
|
||||
for (i=0; i<=700000; i++) {
|
||||
f = fusc(i)
|
||||
leng = num_leng(f)
|
||||
if (leng > max_leng) {
|
||||
max_leng = leng
|
||||
printf("%9s %9s\n",commatize(f),commatize(i))
|
||||
}
|
||||
}
|
||||
exit(0)
|
||||
}
|
||||
function commatize(x, num) {
|
||||
if (x < 0) {
|
||||
return "-" commatize(-x)
|
||||
}
|
||||
x = int(x)
|
||||
num = sprintf("%d.",x)
|
||||
while (num ~ /^[0-9][0-9][0-9][0-9]/) {
|
||||
sub(/[0-9][0-9][0-9][,.]/,",&",num)
|
||||
}
|
||||
sub(/\.$/,"",num)
|
||||
return(num)
|
||||
}
|
||||
function fusc(n) {
|
||||
if (n == 0 || n == 1) {
|
||||
return(n)
|
||||
}
|
||||
else if (n % 2 == 0) {
|
||||
return fusc(n/2)
|
||||
}
|
||||
else {
|
||||
return fusc((n-1)/2) + fusc((n+1)/2)
|
||||
}
|
||||
}
|
||||
function num_leng(n, sum) {
|
||||
sum = 1
|
||||
while (n > 9) {
|
||||
n = int(n/10)
|
||||
sum++
|
||||
}
|
||||
return(sum)
|
||||
}
|
||||
96
Task/Fusc-sequence/Ada/fusc-sequence.ada
Normal file
96
Task/Fusc-sequence/Ada/fusc-sequence.ada
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
with Ada.Text_IO;
|
||||
with Ada.Integer_Text_IO;
|
||||
|
||||
procedure Show_Fusc is
|
||||
|
||||
generic
|
||||
Precalculate : Natural;
|
||||
package Fusc_Sequences is
|
||||
function Fusc (N : in Natural) return Natural;
|
||||
end Fusc_Sequences;
|
||||
|
||||
package body Fusc_Sequences is
|
||||
|
||||
Precalculated_Fusc : array (0 .. Precalculate) of Natural;
|
||||
|
||||
function Fusc_Slow (N : in Natural) return Natural is
|
||||
begin
|
||||
if N = 0 or N = 1 then
|
||||
return N;
|
||||
elsif N mod 2 = 0 then
|
||||
return Fusc_Slow (N / 2);
|
||||
else
|
||||
return Fusc_Slow ((N - 1) / 2) + Fusc_Slow ((N + 1) / 2);
|
||||
end if;
|
||||
end Fusc_Slow;
|
||||
|
||||
function Fusc (N : in Natural) return Natural is
|
||||
begin
|
||||
if N <= Precalculate then
|
||||
return Precalculated_Fusc (N);
|
||||
elsif N mod 2 = 0 then
|
||||
return Fusc (N / 2);
|
||||
else
|
||||
return Fusc ((N - 1) / 2) + Fusc ((N + 1) / 2);
|
||||
end if;
|
||||
end Fusc;
|
||||
|
||||
begin
|
||||
for N in Precalculated_Fusc'Range loop
|
||||
Precalculated_Fusc (N) := Fusc_Slow (N);
|
||||
end loop;
|
||||
end Fusc_Sequences;
|
||||
|
||||
|
||||
package Fusc_Sequence is
|
||||
new Fusc_Sequences (Precalculate => 200_000);
|
||||
|
||||
function Fusc (N : in Natural) return Natural
|
||||
renames Fusc_Sequence.Fusc;
|
||||
|
||||
|
||||
procedure Print_Small_Fuscs is
|
||||
use Ada.Text_IO;
|
||||
begin
|
||||
Put_Line ("First 61 numbers in the fusc sequence:");
|
||||
for N in 0 .. 60 loop
|
||||
Put (Fusc (N)'Image);
|
||||
Put (" ");
|
||||
end loop;
|
||||
New_Line;
|
||||
end Print_Small_Fuscs;
|
||||
|
||||
|
||||
procedure Print_Large_Fuscs (High : in Natural) is
|
||||
use Ada.Text_IO;
|
||||
use Ada.Integer_Text_IO;
|
||||
subtype N_Range is Natural range Natural'First .. High;
|
||||
F : Natural;
|
||||
Len : Natural;
|
||||
Max_Len : Natural := 0;
|
||||
Placeholder : String := " n fusc(n)";
|
||||
Image_N : String renames Placeholder (1 .. 8);
|
||||
Image_Fusc : String renames Placeholder (10 .. Placeholder'Last);
|
||||
begin
|
||||
New_Line;
|
||||
Put_Line ("Printing all largest Fusc numbers upto " & High'Image);
|
||||
Put_Line (Placeholder);
|
||||
|
||||
for N in N_Range loop
|
||||
F := Fusc (N);
|
||||
Len := F'Image'Length;
|
||||
|
||||
if Len > Max_Len then
|
||||
Max_Len := Len;
|
||||
Put (Image_N, N);
|
||||
Put (Image_Fusc, F);
|
||||
Put (Placeholder);
|
||||
New_Line;
|
||||
end if;
|
||||
end loop;
|
||||
end Print_Large_Fuscs;
|
||||
|
||||
begin
|
||||
Print_Small_Fuscs;
|
||||
Print_Large_Fuscs (High => 20_000_000);
|
||||
end Show_Fusc;
|
||||
24
Task/Fusc-sequence/AppleScript/fusc-sequence-1.applescript
Normal file
24
Task/Fusc-sequence/AppleScript/fusc-sequence-1.applescript
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
on fusc(n)
|
||||
if (n < 2) then
|
||||
return n
|
||||
else if (n mod 2 is 0) then
|
||||
return fusc(n div 2)
|
||||
else
|
||||
return fusc((n - 1) div 2) + fusc((n + 1) div 2)
|
||||
end if
|
||||
end fusc
|
||||
|
||||
set sequence to {}
|
||||
set longestSoFar to 0
|
||||
repeat with i from 0 to 60
|
||||
set fuscNumber to fusc(i)
|
||||
set end of sequence to fuscNumber
|
||||
set len to (count (fuscNumber as text))
|
||||
if (len > longestSoFar) then
|
||||
set longestSoFar to len
|
||||
set firstLongest to fuscNumber
|
||||
set indexThereof to i + 1 -- AppleScript indices are 1-based.
|
||||
end if
|
||||
end repeat
|
||||
|
||||
return {sequence:sequence, firstLongest:firstLongest, indexThereof:indexThereof}
|
||||
265
Task/Fusc-sequence/AppleScript/fusc-sequence-2.applescript
Normal file
265
Task/Fusc-sequence/AppleScript/fusc-sequence-2.applescript
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
-- fusc :: [Int]
|
||||
on fusc()
|
||||
-- Terms of the Fusc sequence
|
||||
-- OEIS A2487
|
||||
|
||||
script go
|
||||
on |λ|(step)
|
||||
set {isEven, n, xxs} to step
|
||||
set x to item 1 of xxs
|
||||
|
||||
if isEven then
|
||||
set nxt to n + x
|
||||
{not isEven, nxt, xxs & {nxt}}
|
||||
else
|
||||
{not isEven, x, rest of xxs & {x}}
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
appendGen(gen({0, 1}), ¬
|
||||
fmapGen(my snd, iterate(go, {true, 1, {1}})))
|
||||
end fusc
|
||||
|
||||
-------------------------- TEST ---------------------------
|
||||
on run
|
||||
unlines({¬
|
||||
"First 61 terms:", ¬
|
||||
showList(take(61, fusc())), ¬
|
||||
"", ¬
|
||||
"First term of each decimal magnitude:", ¬
|
||||
"(Index, Term):"} & ¬
|
||||
map(showTuple, take(4, firstFuscOfEachMagnitude())))
|
||||
end run
|
||||
|
||||
|
||||
---------- FIRST FUSC OF EACH DECIMAL MAGNITUDE -----------
|
||||
|
||||
-- firstFuscOfEachMagnitude :: [(Int, Int)]
|
||||
on firstFuscOfEachMagnitude()
|
||||
-- [(Index, Term)] list of of the first Fusc
|
||||
-- terms of each decimal magnitude.
|
||||
script
|
||||
property e : -1
|
||||
property i : 0
|
||||
on |λ|()
|
||||
set e to 1 + e
|
||||
set p to 10 ^ e
|
||||
set v to fuscTerm(i)
|
||||
repeat until p ≤ v
|
||||
set i to 1 + i
|
||||
set v to fuscTerm(i)
|
||||
end repeat
|
||||
{i, v}
|
||||
end |λ|
|
||||
end script
|
||||
end firstFuscOfEachMagnitude
|
||||
|
||||
|
||||
-- fuscTerm :: Int -> Int
|
||||
on fuscTerm(n)
|
||||
-- Nth term (zero-indexed) of the Fusc series.
|
||||
script go
|
||||
on |λ|(i)
|
||||
if 0 = i then
|
||||
{1, 0}
|
||||
else
|
||||
set {x, y} to |λ|(i div 2)
|
||||
if 0 = i mod 2 then
|
||||
{x + y, y}
|
||||
else
|
||||
{x, x + y}
|
||||
end if
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
|
||||
tell go
|
||||
if 1 > n then
|
||||
0
|
||||
else
|
||||
item 1 of |λ|(n - 1)
|
||||
end if
|
||||
end tell
|
||||
end fuscTerm
|
||||
|
||||
|
||||
|
||||
-------------------- GENERIC FUNCTIONS --------------------
|
||||
|
||||
-- appendGen (++) :: Gen [a] -> Gen [a] -> Gen [a]
|
||||
on appendGen(xs, ys)
|
||||
script
|
||||
property vs : xs
|
||||
on |λ|()
|
||||
set v to |λ|() of vs
|
||||
if missing value is not v then
|
||||
v
|
||||
else
|
||||
set vs to ys
|
||||
|λ|() of ys
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
end appendGen
|
||||
|
||||
|
||||
-- fmapGen <$> :: (a -> b) -> Gen [a] -> Gen [b]
|
||||
on fmapGen(f, gen)
|
||||
script
|
||||
property g : mReturn(f)
|
||||
on |λ|()
|
||||
set v to gen's |λ|()
|
||||
if v is missing value then
|
||||
v
|
||||
else
|
||||
g's |λ|(v)
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
end fmapGen
|
||||
|
||||
|
||||
-- intercalate :: String -> [String] -> String
|
||||
on intercalate(delim, xs)
|
||||
set {dlm, my text item delimiters} to ¬
|
||||
{my text item delimiters, delim}
|
||||
set s to xs as text
|
||||
set my text item delimiters to dlm
|
||||
s
|
||||
end intercalate
|
||||
|
||||
|
||||
-- iterate :: (a -> a) -> a -> Gen [a]
|
||||
on iterate(f, x)
|
||||
script
|
||||
property v : missing value
|
||||
property g : mReturn(f)'s |λ|
|
||||
on |λ|()
|
||||
if missing value is v then
|
||||
set v to x
|
||||
else
|
||||
set v to g(v)
|
||||
end if
|
||||
return v
|
||||
end |λ|
|
||||
end script
|
||||
end iterate
|
||||
|
||||
|
||||
-- map :: (a -> b) -> [a] -> [b]
|
||||
on map(f, xs)
|
||||
-- The list obtained by applying f
|
||||
-- to each element of xs.
|
||||
tell mReturn(f)
|
||||
set lng to length of xs
|
||||
set lst to {}
|
||||
repeat with i from 1 to lng
|
||||
set end of lst to |λ|(item i of xs, i, xs)
|
||||
end repeat
|
||||
return lst
|
||||
end tell
|
||||
end map
|
||||
|
||||
|
||||
-- mReturn :: First-class m => (a -> b) -> m (a -> b)
|
||||
on mReturn(f)
|
||||
-- 2nd class handler function lifted into 1st class script wrapper.
|
||||
if script is class of f then
|
||||
f
|
||||
else
|
||||
script
|
||||
property |λ| : f
|
||||
end script
|
||||
end if
|
||||
end mReturn
|
||||
|
||||
|
||||
-- gen :: [a] -> Gen a
|
||||
on gen(xs)
|
||||
script go
|
||||
property lng : length of xs
|
||||
property i : 0
|
||||
on |λ|()
|
||||
if i ≥ lng then
|
||||
missing value
|
||||
else
|
||||
set i to 1 + i
|
||||
item i of xs
|
||||
end if
|
||||
end |λ|
|
||||
end script
|
||||
end gen
|
||||
|
||||
|
||||
-- showList :: [a] -> String
|
||||
on showList(xs)
|
||||
"[" & intercalate(", ", my map(my str, xs)) & "]"
|
||||
end showList
|
||||
|
||||
|
||||
-- showTuple :: (,) -> String
|
||||
on showTuple(xs)
|
||||
"(" & intercalate(", ", my map(my str, xs)) & ")"
|
||||
end showTuple
|
||||
|
||||
|
||||
-- snd :: (a, b) -> b
|
||||
on snd(tpl)
|
||||
if class of tpl is record then
|
||||
|2| of tpl
|
||||
else
|
||||
item 2 of tpl
|
||||
end if
|
||||
end snd
|
||||
|
||||
|
||||
-- str :: a -> String
|
||||
on str(x)
|
||||
x as string
|
||||
end str
|
||||
|
||||
|
||||
-- take :: Int -> [a] -> [a]
|
||||
-- take :: Int -> String -> String
|
||||
on take(n, xs)
|
||||
set c to class of xs
|
||||
if list is c then
|
||||
if 0 < n then
|
||||
items 1 thru min(n, length of xs) of xs
|
||||
else
|
||||
{}
|
||||
end if
|
||||
else if string is c then
|
||||
if 0 < n then
|
||||
text 1 thru min(n, length of xs) of xs
|
||||
else
|
||||
""
|
||||
end if
|
||||
else if script is c then
|
||||
set ys to {}
|
||||
repeat with i from 1 to n
|
||||
set v to |λ|() of xs
|
||||
if missing value is v then
|
||||
return ys
|
||||
else
|
||||
set end of ys to v
|
||||
end if
|
||||
end repeat
|
||||
return ys
|
||||
else
|
||||
missing value
|
||||
end if
|
||||
end take
|
||||
|
||||
|
||||
-- unlines :: [String] -> String
|
||||
on unlines(xs)
|
||||
-- A single string formed by the intercalation
|
||||
-- of a list of strings with the newline character.
|
||||
set {dlm, my text item delimiters} to ¬
|
||||
{my text item delimiters, linefeed}
|
||||
set s to xs as text
|
||||
set my text item delimiters to dlm
|
||||
s
|
||||
end unlines
|
||||
27
Task/Fusc-sequence/Arturo/fusc-sequence.arturo
Normal file
27
Task/Fusc-sequence/Arturo/fusc-sequence.arturo
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
fusc: function [n][
|
||||
if? or? n=0 n=1 -> n
|
||||
else [
|
||||
if? 0=n%2 -> fusc n/2
|
||||
else -> (fusc (n-1)/2) + fusc (n+1)/2
|
||||
]
|
||||
]
|
||||
|
||||
print "The first 61 Fusc numbers:"
|
||||
print map 0..61 => fusc
|
||||
|
||||
print "\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
|
||||
print " n fusc(n)"
|
||||
print "--------- ---------"
|
||||
maxLength: 0
|
||||
|
||||
loop 0..40000 'i [
|
||||
f: fusc i
|
||||
l: size to :string f
|
||||
if l > maxLength [
|
||||
maxLength: l
|
||||
print [
|
||||
pad to :string i 9
|
||||
pad to :string f 9
|
||||
]
|
||||
]
|
||||
]
|
||||
14
Task/Fusc-sequence/AutoHotkey/fusc-sequence.ahk
Normal file
14
Task/Fusc-sequence/AutoHotkey/fusc-sequence.ahk
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
fusc:=[], fusc[0]:=0, fusc[1]:=1, n:=1, l:=0, result:=""
|
||||
|
||||
while (StrLen(fusc[n]) < 5)
|
||||
fusc[++n] := Mod(n, 2) ? fusc[floor((n-1)/2)] + fusc[Floor((n+1)/2)] : fusc[floor(n/2)]
|
||||
|
||||
while (A_Index <= 61)
|
||||
result .= (result = "" ? "" : ",") fusc[A_Index-1]
|
||||
|
||||
result .= "`n`nfusc number whose length is greater than any previous fusc number length:`nindex`tnumber`n"
|
||||
for i, v in fusc
|
||||
if (l < StrLen(v))
|
||||
l := StrLen(v), result .= i "`t" v "`n"
|
||||
|
||||
MsgBox % result
|
||||
32
Task/Fusc-sequence/BASIC256/fusc-sequence.basic
Normal file
32
Task/Fusc-sequence/BASIC256/fusc-sequence.basic
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
global f, max
|
||||
max = 36000
|
||||
dim f(max)
|
||||
|
||||
call fusc()
|
||||
|
||||
for i = 0 to 60
|
||||
print f[i]; " ";
|
||||
next i
|
||||
|
||||
print : print
|
||||
print " Index Value"
|
||||
d = 0
|
||||
for i = 0 to max-1
|
||||
if f[i] >= d then
|
||||
print rjust(string(i),10," "), rjust(string(f[i]),10," ")
|
||||
if d = 0 then d = 1
|
||||
d *= 10
|
||||
end if
|
||||
next i
|
||||
end
|
||||
|
||||
subroutine fusc()
|
||||
f[0] = 0 : f[1] = 1
|
||||
for n = 2 to max-1
|
||||
if (n mod 2) then
|
||||
f[n] = f[(n-1)/2] + f[(n+1)/2]
|
||||
else
|
||||
f[n] = f[n/2]
|
||||
end if
|
||||
next n
|
||||
end subroutine
|
||||
9
Task/Fusc-sequence/BQN/fusc-sequence-1.bqn
Normal file
9
Task/Fusc-sequence/BQN/fusc-sequence-1.bqn
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
Fusc ← {
|
||||
{
|
||||
𝕩∾+´(⍷(⌈∾⌊)2÷˜≠𝕩)⊑¨<𝕩
|
||||
}⍟(𝕩-2)↕2
|
||||
}
|
||||
|
||||
•Show Fusc 61
|
||||
|
||||
•Show >⟨"Index"‿"Number"⟩∾{((1+↕4)⊐˜(⌊1+10⋆⁼1⌈|)¨𝕩){𝕨∾𝕨⊑𝕩}¨<𝕩} Fusc 99999
|
||||
8
Task/Fusc-sequence/BQN/fusc-sequence-2.bqn
Normal file
8
Task/Fusc-sequence/BQN/fusc-sequence-2.bqn
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
⟨ 0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4 ⟩
|
||||
┌─
|
||||
╵ "Index" "Number"
|
||||
0 0
|
||||
37 11
|
||||
1173 108
|
||||
35499 1076
|
||||
┘
|
||||
57
Task/Fusc-sequence/C++/fusc-sequence.cpp
Normal file
57
Task/Fusc-sequence/C++/fusc-sequence.cpp
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
const int n = 61;
|
||||
std::vector<int> l{ 0, 1 };
|
||||
|
||||
int fusc(int n) {
|
||||
if (n < l.size()) return l[n];
|
||||
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
|
||||
l.push_back(f);
|
||||
return f;
|
||||
}
|
||||
|
||||
int main() {
|
||||
bool lst = true;
|
||||
int w = -1;
|
||||
int c = 0;
|
||||
int t;
|
||||
std::string res;
|
||||
std::cout << "First " << n << " numbers in the fusc sequence:\n";
|
||||
for (int i = 0; i < INT32_MAX; i++) {
|
||||
int f = fusc(i);
|
||||
if (lst) {
|
||||
if (i < 61) {
|
||||
std::cout << f << ' ';
|
||||
} else {
|
||||
lst = false;
|
||||
std::cout << "\nPoints in the sequence where an item has more digits than any previous items:\n";
|
||||
std::cout << std::setw(11) << "Index\\" << " " << std::left << std::setw(9) << "/Value\n";
|
||||
std::cout << res << '\n';
|
||||
res = "";
|
||||
}
|
||||
}
|
||||
std::stringstream ss;
|
||||
ss << f;
|
||||
t = ss.str().length();
|
||||
ss.str("");
|
||||
ss.clear();
|
||||
if (t > w) {
|
||||
w = t;
|
||||
res += (res == "" ? "" : "\n");
|
||||
ss << std::setw(11) << i << " " << std::left << std::setw(9) << f;
|
||||
res += ss.str();
|
||||
if (!lst) {
|
||||
std::cout << res << '\n';
|
||||
res = "";
|
||||
}
|
||||
if (++c > 5) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
42
Task/Fusc-sequence/C-sharp/fusc-sequence.cs
Normal file
42
Task/Fusc-sequence/C-sharp/fusc-sequence.cs
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
static class program
|
||||
{
|
||||
static int n = 61;
|
||||
static List<int> l = new List<int>() { 0, 1 };
|
||||
|
||||
static int fusc(int n)
|
||||
{
|
||||
if (n < l.Count) return l[n];
|
||||
int f = (n & 1) == 0 ? l[n >> 1] : l[(n - 1) >> 1] + l[(n + 1) >> 1];
|
||||
l.Add(f); return f;
|
||||
}
|
||||
|
||||
static void Main(string[] args)
|
||||
{
|
||||
bool lst = true; int w = -1, c = 0, t;
|
||||
string fs = "{0,11:n0} {1,-9:n0}", res = "";
|
||||
Console.WriteLine("First {0} numbers in the fusc sequence:", n);
|
||||
for (int i = 0; i < int.MaxValue; i++)
|
||||
{
|
||||
int f = fusc(i); if (lst)
|
||||
{
|
||||
if (i < 61) Console.Write("{0} ", f);
|
||||
else
|
||||
{
|
||||
lst = false;
|
||||
Console.WriteLine();
|
||||
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:");
|
||||
Console.WriteLine(fs, "Index\\", "/Value"); Console.WriteLine(res); res = "";
|
||||
}
|
||||
}
|
||||
if ((t = f.ToString().Length) > w)
|
||||
{
|
||||
w = t; res += (res == "" ? "" : "\n") + string.Format(fs, i, f);
|
||||
if (!lst) { Console.WriteLine(res); res = ""; } if (++c > 5) break;
|
||||
}
|
||||
}
|
||||
l.Clear();
|
||||
}
|
||||
}
|
||||
50
Task/Fusc-sequence/C/fusc-sequence.c
Normal file
50
Task/Fusc-sequence/C/fusc-sequence.c
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
#include<limits.h>
|
||||
#include<stdio.h>
|
||||
|
||||
int fusc(int n){
|
||||
if(n==0||n==1)
|
||||
return n;
|
||||
else if(n%2==0)
|
||||
return fusc(n/2);
|
||||
else
|
||||
return fusc((n-1)/2) + fusc((n+1)/2);
|
||||
}
|
||||
|
||||
int numLen(int n){
|
||||
int sum = 1;
|
||||
|
||||
while(n>9){
|
||||
n = n/10;
|
||||
sum++;
|
||||
}
|
||||
|
||||
return sum;
|
||||
}
|
||||
|
||||
void printLargeFuscs(int limit){
|
||||
int i,f,len,maxLen = 1;
|
||||
|
||||
printf("\n\nPrinting all largest Fusc numbers upto %d \nIndex-------Value",limit);
|
||||
|
||||
for(i=0;i<=limit;i++){
|
||||
f = fusc(i);
|
||||
len = numLen(f);
|
||||
|
||||
if(len>maxLen){
|
||||
maxLen = len;
|
||||
printf("\n%5d%12d",i,f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
int i;
|
||||
|
||||
printf("Index-------Value");
|
||||
for(i=0;i<61;i++)
|
||||
printf("\n%5d%12d",i,fusc(i));
|
||||
printLargeFuscs(INT_MAX);
|
||||
return 0;
|
||||
}
|
||||
49
Task/Fusc-sequence/CLU/fusc-sequence.clu
Normal file
49
Task/Fusc-sequence/CLU/fusc-sequence.clu
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
fusc = iter () yields (int)
|
||||
q: array[int] := array[int]$[1]
|
||||
yield(0)
|
||||
yield(1)
|
||||
|
||||
while true do
|
||||
x: int := array[int]$reml(q)
|
||||
array[int]$addh(q,x)
|
||||
yield(x)
|
||||
|
||||
x := x + array[int]$bottom(q)
|
||||
array[int]$addh(q,x)
|
||||
yield(x)
|
||||
end
|
||||
end fusc
|
||||
|
||||
longest_fusc = iter () yields (int,int)
|
||||
sofar: int := 0
|
||||
count: int := 0
|
||||
|
||||
for f: int in fusc() do
|
||||
if f >= sofar then
|
||||
yield (count,f)
|
||||
sofar := 10*sofar
|
||||
if sofar=0 then sofar:=10 end
|
||||
end
|
||||
count := count + 1
|
||||
end
|
||||
end longest_fusc
|
||||
|
||||
start_up = proc ()
|
||||
po: stream := stream$primary_output()
|
||||
|
||||
stream$putl(po, "First 61:")
|
||||
n: int := 0
|
||||
for f: int in fusc() do
|
||||
stream$puts(po, int$unparse(f) || " ")
|
||||
n := n + 1
|
||||
if n = 61 then break end
|
||||
end
|
||||
|
||||
stream$putl(po, "\nLength records:")
|
||||
n := 0
|
||||
for i, f: int in longest_fusc() do
|
||||
stream$putl(po, "fusc(" || int$unparse(i) || ") = " || int$unparse(f))
|
||||
n := n + 1
|
||||
if n = 5 then break end
|
||||
end
|
||||
end start_up
|
||||
25
Task/Fusc-sequence/D/fusc-sequence-1.d
Normal file
25
Task/Fusc-sequence/D/fusc-sequence-1.d
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import std.functional, std.stdio, std.format, std.conv;
|
||||
|
||||
ulong fusc(ulong n) =>
|
||||
memoize!fuscImp(n);
|
||||
|
||||
ulong fuscImp(ulong n) =>
|
||||
( n < 2 ) ? n :
|
||||
( n % 2 == 0 ) ? memoize!fuscImp( n/2 ) :
|
||||
memoize!fuscImp( (n-1)/2 ) + memoize!fuscImp( (n+1)/2 );
|
||||
|
||||
void main() {
|
||||
const N_FIRST=61;
|
||||
const MAX_N_DIGITS=5;
|
||||
|
||||
format!"First %d fusc numbers: "(N_FIRST).write;
|
||||
foreach( n; 0..N_FIRST ) n.fusc.format!"%d ".write;
|
||||
writeln;
|
||||
|
||||
format!"\nFusc numbers with more digits than any previous (1 to %d digits):"(MAX_N_DIGITS).writeln;
|
||||
for(auto n=0, ndigits=0; ndigits<MAX_N_DIGITS; n++)
|
||||
if( n.fusc.to!string.length > ndigits ){
|
||||
format!"fusc(%d)=%d"( n, n.fusc ).writeln;
|
||||
ndigits = n.fusc.to!string.length.to!int;
|
||||
}
|
||||
}
|
||||
28
Task/Fusc-sequence/D/fusc-sequence-2.d
Normal file
28
Task/Fusc-sequence/D/fusc-sequence-2.d
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import std.stdio, std.format, std.conv;
|
||||
|
||||
int[] fusc_cache = [0, 1];
|
||||
int fusc(int n) {
|
||||
// Ensure cache contains all missing numbers until n
|
||||
for(auto i=fusc_cache.length;i<=n;i++)
|
||||
fusc_cache ~= i%2 == 0
|
||||
? fusc_cache[i/2]
|
||||
: fusc_cache[(i-1)/2] + fusc_cache[(i + 1)/2];
|
||||
// Solve using cache
|
||||
return fusc_cache[n];
|
||||
}
|
||||
|
||||
void main() {
|
||||
const N_FIRST=61;
|
||||
const MAX_N_DIGITS=6;
|
||||
|
||||
format!"First %d fusc numbers: "(N_FIRST).write;
|
||||
foreach( n; 0..N_FIRST ) n.fusc.format!"%d ".write;
|
||||
writeln;
|
||||
|
||||
format!"\nFusc numbers with more digits than any previous (1 to %d digits):"(MAX_N_DIGITS).writeln;
|
||||
for(auto n=0, ndigits=0; ndigits<MAX_N_DIGITS; n++)
|
||||
if( n.fusc.to!string.length > ndigits ){
|
||||
format!"fusc(%d)=%d"( n, n.fusc ).writeln;
|
||||
ndigits = n.fusc.to!string.length.to!int;
|
||||
}
|
||||
}
|
||||
46
Task/Fusc-sequence/Dyalect/fusc-sequence.dyalect
Normal file
46
Task/Fusc-sequence/Dyalect/fusc-sequence.dyalect
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
let n = 61
|
||||
let l = [0, 1]
|
||||
|
||||
func fusc(n) {
|
||||
return l[n] when n < l.Length()
|
||||
let f = (n &&& 1) == 0 ? l[n >>> 1] : l[(n - 1) >>> 1] + l[(n + 1) >>> 1]
|
||||
l.Add(f)
|
||||
return f
|
||||
}
|
||||
|
||||
var lst = true
|
||||
var w = -1
|
||||
var c = 0
|
||||
var t = nil
|
||||
var res = ""
|
||||
|
||||
print("First \(n) numbers in the fusc sequence:")
|
||||
for i in 0..Integer.Max {
|
||||
let f = fusc(i)
|
||||
if lst {
|
||||
if i < 61 {
|
||||
print("\(f) ", terminator: "")
|
||||
} else {
|
||||
lst = false
|
||||
print("")
|
||||
print("Points in the sequence where an item has more digits than any previous items:")
|
||||
print("Index/Value:")
|
||||
print(res)
|
||||
res = ""
|
||||
}
|
||||
}
|
||||
t = f.ToString().Length()
|
||||
if t > w {
|
||||
w = t
|
||||
res += (res == "" ? "" : "\n") + "\(i)/\(f)"
|
||||
if !lst {
|
||||
print(res)
|
||||
res = ""
|
||||
}
|
||||
c += 1
|
||||
if c > 5 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
l.Clear()
|
||||
3
Task/Fusc-sequence/F-Sharp/fusc-sequence-1.fs
Normal file
3
Task/Fusc-sequence/F-Sharp/fusc-sequence-1.fs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
// Generate the fusc sequence. Nigel Galloway: March 20th., 2019
|
||||
let fG n=seq{for (n,g) in Seq.append n [1] |> Seq.pairwise do yield n; yield n+g}
|
||||
let fusc=seq{yield 0; yield! Seq.unfold(fun n->Some(n,fG n))(seq[1])|>Seq.concat}|> Seq.mapi(fun n g->(n,g))
|
||||
1
Task/Fusc-sequence/F-Sharp/fusc-sequence-2.fs
Normal file
1
Task/Fusc-sequence/F-Sharp/fusc-sequence-2.fs
Normal file
|
|
@ -0,0 +1 @@
|
|||
fusc |> Seq.take 61 |> Seq.iter(fun(_,g)->printf "%d " g); printfn ""
|
||||
2
Task/Fusc-sequence/F-Sharp/fusc-sequence-3.fs
Normal file
2
Task/Fusc-sequence/F-Sharp/fusc-sequence-3.fs
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
let fN=let mutable n=0 in (fun (_,g)->if g>=n then n<-pown 10 (string g).Length; true else false)
|
||||
fusc |> Seq.filter fN |> Seq.take 7 |> Seq.iter(fun(n,g)->printfn "fusc %d -> %d" n g)
|
||||
39
Task/Fusc-sequence/Factor/fusc-sequence.factor
Normal file
39
Task/Fusc-sequence/Factor/fusc-sequence.factor
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
USING: arrays assocs formatting io kernel make math math.parser
|
||||
math.ranges namespaces prettyprint sequences
|
||||
tools.memory.private ;
|
||||
IN: rosetta-code.fusc
|
||||
|
||||
<PRIVATE
|
||||
|
||||
: (fusc) ( n -- seq )
|
||||
[ 2 ] dip [a,b) [
|
||||
0 , 1 , [
|
||||
[ building get ] dip dup even?
|
||||
[ 2/ swap nth ]
|
||||
[ [ 1 - 2/ ] [ 1 + 2/ ] 2bi [ swap nth ] 2bi@ + ]
|
||||
if ,
|
||||
] each
|
||||
] { } make ;
|
||||
|
||||
: increases ( seq -- assoc )
|
||||
[ 0 ] dip [
|
||||
[
|
||||
2array 2dup first number>string length <
|
||||
[ [ 1 + ] [ , ] bi* ] [ drop ] if
|
||||
] each-index
|
||||
] { } make nip ;
|
||||
|
||||
PRIVATE>
|
||||
|
||||
: fusc ( n -- seq )
|
||||
dup 3 < [ { 0 1 } swap head ] [ (fusc) ] if ;
|
||||
|
||||
: fusc-demo ( -- )
|
||||
"First 61 fusc numbers:" print 61 fusc [ pprint bl ] each
|
||||
nl nl
|
||||
"Fusc numbers with more digits than all previous ones:"
|
||||
print "Value Index\n====== =======" print
|
||||
1,000,000 fusc increases
|
||||
[ [ commas ] bi@ "%-6s %-7s\n" printf ] assoc-each ;
|
||||
|
||||
MAIN: fusc-demo
|
||||
42
Task/Fusc-sequence/Forth/fusc-sequence.fth
Normal file
42
Task/Fusc-sequence/Forth/fusc-sequence.fth
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
\ Gforth 0.7.9_20211014
|
||||
|
||||
: fusc ( n -- n) \ input n -- output fusc(n)
|
||||
dup dup 0= swap 1 = or \ n = 0 or 1
|
||||
if exit \ return n
|
||||
else dup 2 mod 0= \ test even
|
||||
if 2/ recurse \ even fusc(n)= fusc(n/2)
|
||||
else dup 1- 2/ recurse \ odd fusc(n) = fusc((n-1)/2) +
|
||||
swap 1+ 2/ recurse + \ fusc((n+1)/2)
|
||||
then
|
||||
then
|
||||
;
|
||||
|
||||
: cntDigits ( n -- n ) \ returns the numbers of digits
|
||||
0 begin 1+ swap
|
||||
10 /
|
||||
swap over
|
||||
0= until
|
||||
swap drop
|
||||
;
|
||||
|
||||
: fuscLen ( n -- ) \ count until end index
|
||||
cr 1 swap 0
|
||||
do
|
||||
i fusc cntDigits
|
||||
over > if 1+
|
||||
." fusc( " i . ." ) : "
|
||||
i fusc . cr
|
||||
then
|
||||
loop
|
||||
;
|
||||
|
||||
: firstFusc ( n -- ) \ show fusc(i) until limit
|
||||
dup ." First " . ." fusc(n) : " cr
|
||||
0 do I fusc . loop cr
|
||||
;
|
||||
|
||||
61 firstFusc
|
||||
|
||||
20 1000 1000 * * fuscLen
|
||||
|
||||
bye
|
||||
48
Task/Fusc-sequence/FreeBASIC/fusc-sequence.basic
Normal file
48
Task/Fusc-sequence/FreeBASIC/fusc-sequence.basic
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
' version 01-03-2019
|
||||
' compile with: fbc -s console
|
||||
|
||||
#Define max 20000000
|
||||
|
||||
Dim Shared As UInteger f(max)
|
||||
|
||||
Sub fusc
|
||||
|
||||
f(0) = 0
|
||||
f(1) = 1
|
||||
|
||||
For n As UInteger = 2 To max
|
||||
If n And 1 Then
|
||||
f(n) = f((n -1) \ 2) + f((n +1) \ 2)
|
||||
Else
|
||||
f(n) = f(n \ 2)
|
||||
End If
|
||||
Next
|
||||
|
||||
End Sub
|
||||
|
||||
' ------=< MAIN >=------
|
||||
|
||||
Dim As UInteger i, d
|
||||
Dim As String fs
|
||||
|
||||
fusc
|
||||
|
||||
For i = 0 To 60
|
||||
Print f(i); " ";
|
||||
Next
|
||||
|
||||
Print : Print
|
||||
Print " Index Value"
|
||||
For i = 0 To max
|
||||
If f(i) >= d Then
|
||||
Print Using "###########," ; i; f(i)
|
||||
If d = 0 Then d = 1
|
||||
d *= 10
|
||||
End If
|
||||
Next
|
||||
|
||||
' empty keyboard buffer
|
||||
While Inkey <> "" : Wend
|
||||
Print : Print "hit any key to end program"
|
||||
Sleep
|
||||
End
|
||||
70
Task/Fusc-sequence/Go/fusc-sequence.go
Normal file
70
Task/Fusc-sequence/Go/fusc-sequence.go
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func fusc(n int) []int {
|
||||
if n <= 0 {
|
||||
return []int{}
|
||||
}
|
||||
if n == 1 {
|
||||
return []int{0}
|
||||
}
|
||||
res := make([]int, n)
|
||||
res[0] = 0
|
||||
res[1] = 1
|
||||
for i := 2; i < n; i++ {
|
||||
if i%2 == 0 {
|
||||
res[i] = res[i/2]
|
||||
} else {
|
||||
res[i] = res[(i-1)/2] + res[(i+1)/2]
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func fuscMaxLen(n int) [][2]int {
|
||||
maxLen := -1
|
||||
maxFusc := -1
|
||||
f := fusc(n)
|
||||
var res [][2]int
|
||||
for i := 0; i < n; i++ {
|
||||
if f[i] <= maxFusc {
|
||||
continue // avoid expensive strconv operation where possible
|
||||
}
|
||||
maxFusc = f[i]
|
||||
le := len(strconv.Itoa(f[i]))
|
||||
if le > maxLen {
|
||||
res = append(res, [2]int{i, f[i]})
|
||||
maxLen = le
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func commatize(n int) string {
|
||||
s := fmt.Sprintf("%d", n)
|
||||
if n < 0 {
|
||||
s = s[1:]
|
||||
}
|
||||
le := len(s)
|
||||
for i := le - 3; i >= 1; i -= 3 {
|
||||
s = s[0:i] + "," + s[i:]
|
||||
}
|
||||
if n >= 0 {
|
||||
return s
|
||||
}
|
||||
return "-" + s
|
||||
}
|
||||
|
||||
func main() {
|
||||
fmt.Println("The first 61 fusc numbers are:")
|
||||
fmt.Println(fusc(61))
|
||||
fmt.Println("\nThe fusc numbers whose length > any previous fusc number length are:")
|
||||
res := fuscMaxLen(20000000) // examine first twenty million numbers say
|
||||
for i := 0; i < len(res); i++ {
|
||||
fmt.Printf("%7s (index %10s)\n", commatize(res[i][1]), commatize(res[i][0]))
|
||||
}
|
||||
}
|
||||
39
Task/Fusc-sequence/Groovy/fusc-sequence.groovy
Normal file
39
Task/Fusc-sequence/Groovy/fusc-sequence.groovy
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
class FuscSequence {
|
||||
static void main(String[] args) {
|
||||
println("Show the first 61 fusc numbers (starting at zero) in a horizontal format")
|
||||
for (int n = 0; n < 61; n++) {
|
||||
printf("%,d ", fusc[n])
|
||||
}
|
||||
|
||||
println()
|
||||
println()
|
||||
println("Show the fusc number (and its index) whose length is greater than any previous fusc number length.")
|
||||
int start = 0
|
||||
for (int i = 0; i <= 5; i++) {
|
||||
int val = i != 0 ? (int) Math.pow(10, i) : -1
|
||||
for (int j = start; j < FUSC_MAX; j++) {
|
||||
if (fusc[j] > val) {
|
||||
printf("fusc[%,d] = %,d%n", j, fusc[j])
|
||||
start = j
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final int FUSC_MAX = 30000000
|
||||
private static int[] fusc = new int[FUSC_MAX]
|
||||
|
||||
static {
|
||||
fusc[0] = 0
|
||||
fusc[1] = 1
|
||||
for (int n = 2; n < FUSC_MAX; n++) {
|
||||
int n2 = (int) (n / 2)
|
||||
int n2m = (int) ((n - 1) / 2)
|
||||
int n2p = (int) ((n + 1) / 2)
|
||||
fusc[n] = n % 2 == 0
|
||||
? fusc[n2]
|
||||
: fusc[n2m] + fusc[n2p]
|
||||
}
|
||||
}
|
||||
}
|
||||
37
Task/Fusc-sequence/Haskell/fusc-sequence-1.hs
Normal file
37
Task/Fusc-sequence/Haskell/fusc-sequence-1.hs
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
---------------------- FUSC SEQUENCE ---------------------
|
||||
|
||||
fusc :: Int -> Int
|
||||
fusc i
|
||||
| 1 > i = 0
|
||||
| otherwise = fst $ go (pred i)
|
||||
where
|
||||
go n
|
||||
| 0 == n = (1, 0)
|
||||
| even n = (x + y, y)
|
||||
| otherwise = (x, x + y)
|
||||
where
|
||||
(x, y) = go (div n 2)
|
||||
|
||||
--------------------------- TEST -------------------------
|
||||
main :: IO ()
|
||||
main = do
|
||||
putStrLn "First 61 terms:"
|
||||
print $ fusc <$> [0 .. 60]
|
||||
putStrLn "\n(Index, Value):"
|
||||
mapM_ print $ take 5 widths
|
||||
|
||||
widths :: [(Int, Int)]
|
||||
widths =
|
||||
fmap
|
||||
(\(_, i, x) -> (i, x))
|
||||
(iterate nxtWidth (2, 0, 0))
|
||||
|
||||
nxtWidth :: (Int, Int, Int) -> (Int, Int, Int)
|
||||
nxtWidth (w, i, v) = (succ w, j, x)
|
||||
where
|
||||
fi = (,) <*> fusc
|
||||
(j, x) =
|
||||
until
|
||||
((w <=) . length . show . snd)
|
||||
(fi . succ . fst)
|
||||
(fi i)
|
||||
21
Task/Fusc-sequence/Haskell/fusc-sequence-2.hs
Normal file
21
Task/Fusc-sequence/Haskell/fusc-sequence-2.hs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
zipWithLazy :: (a -> b -> c) -> [a] -> [b] -> [c]
|
||||
zipWithLazy f ~(x : xs) ~(y : ys) =
|
||||
f x y : zipWithLazy f xs ys
|
||||
|
||||
fuscs :: [Integer]
|
||||
fuscs = 0 : s
|
||||
where
|
||||
s = 1 : concat (zipWithLazy f s (tail s))
|
||||
f x y = [x, x + y]
|
||||
|
||||
widths :: [(Int, Integer)]
|
||||
widths = map head $ scanl f (zip [0 ..] fuscs) [2 ..]
|
||||
where
|
||||
f fis w = dropWhile ((< w) . length . show . snd) fis
|
||||
|
||||
main :: IO ()
|
||||
main = do
|
||||
putStrLn "First 61 terms:"
|
||||
print $ take 61 fuscs
|
||||
putStrLn "\n(Index, Value):"
|
||||
mapM_ print $ take 5 widths
|
||||
18
Task/Fusc-sequence/J/fusc-sequence.j
Normal file
18
Task/Fusc-sequence/J/fusc-sequence.j
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
fusc_term =: ({~ -:@#)`([: +/ ({~ ([: -: _1 1 + #)))@.(2 | #)
|
||||
fusc =: (, fusc_term)@:]^:[ 0 1"_
|
||||
|
||||
NB. show the first 61 fusc numbers (starting at zero) in a horizontal format.
|
||||
61 {. fusc 70
|
||||
0 1 1 2 1 3 2 3 1 4 3 5 2 5 3 4 1 5 4 7 3 8 5 7 2 7 5 8 3 7 4 5 1 6 5 9 4 11 7 10 3 11 8 13 5 12 7 9 2 9 7 12 5 13 8 11 3 10 7 11 4
|
||||
|
||||
9!:17]2 2 NB. specify bottom right position in box
|
||||
|
||||
FUSC =: fusc 99999
|
||||
DIGITS =: ; ([: # 10&#.inv)&.> FUSC
|
||||
|
||||
(;: 'index value') ,. <"0(,: {&A) DIGITS i. 1 2 3 4
|
||||
┌─────┬─┬──┬────┬─────┐
|
||||
│index│0│37│1173│35499│
|
||||
├─────┼─┼──┼────┼─────┤
|
||||
│value│0│11│ 108│ 1076│
|
||||
└─────┴─┴──┴────┴─────┘
|
||||
33
Task/Fusc-sequence/Java/fusc-sequence.java
Normal file
33
Task/Fusc-sequence/Java/fusc-sequence.java
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
public class FuscSequence {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("Show the first 61 fusc numbers (starting at zero) in a horizontal format");
|
||||
for ( int n = 0 ; n < 61 ; n++ ) {
|
||||
System.out.printf("%,d ", fusc[n]);
|
||||
}
|
||||
|
||||
System.out.printf("%n%nShow the fusc number (and its index) whose length is greater than any previous fusc number length.%n");
|
||||
int start = 0;
|
||||
for (int i = 0 ; i <= 5 ; i++ ) {
|
||||
int val = i != 0 ? (int) Math.pow(10, i) : -1;
|
||||
for ( int j = start ; j < FUSC_MAX ; j++ ) {
|
||||
if ( fusc[j] > val ) {
|
||||
System.out.printf("fusc[%,d] = %,d%n", j, fusc[j] );
|
||||
start = j;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static final int FUSC_MAX = 30000000;
|
||||
private static int[] fusc = new int[FUSC_MAX];
|
||||
|
||||
static {
|
||||
fusc[0] = 0;
|
||||
fusc[1] = 1;
|
||||
for ( int n = 2 ; n < FUSC_MAX ; n++ ) {
|
||||
fusc[n] = (n % 2 == 0 ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
106
Task/Fusc-sequence/JavaScript/fusc-sequence.js
Normal file
106
Task/Fusc-sequence/JavaScript/fusc-sequence.js
Normal file
|
|
@ -0,0 +1,106 @@
|
|||
(() => {
|
||||
"use strict";
|
||||
|
||||
// ---------------------- FUSC -----------------------
|
||||
|
||||
// fusc :: Int -> Int
|
||||
const fusc = i => {
|
||||
const go = n =>
|
||||
0 === n ? [
|
||||
1, 0
|
||||
] : (() => {
|
||||
const [x, y] = go(Math.floor(n / 2));
|
||||
|
||||
return 0 === n % 2 ? (
|
||||
[x + y, y]
|
||||
) : [x, x + y];
|
||||
})();
|
||||
|
||||
return 1 > i ? (
|
||||
0
|
||||
) : go(i - 1)[0];
|
||||
};
|
||||
|
||||
|
||||
// ---------------------- TEST -----------------------
|
||||
const main = () => {
|
||||
const terms = enumFromTo(0)(60).map(fusc);
|
||||
|
||||
return [
|
||||
"First 61 terms:",
|
||||
`[${terms.join(",")}]`,
|
||||
"",
|
||||
"(Index, Value):",
|
||||
firstWidths(5).reduce(
|
||||
(a, x) => [x.slice(1), ...a],
|
||||
[]
|
||||
)
|
||||
.map(([i, x]) => `(${i}, ${x})`)
|
||||
.join("\n")
|
||||
]
|
||||
.join("\n");
|
||||
};
|
||||
|
||||
|
||||
// firstWidths :: Int -> [(Int, Int)]
|
||||
const firstWidths = n => {
|
||||
const nxtWidth = xs => {
|
||||
const
|
||||
fi = fanArrow(fusc)(x => x),
|
||||
[w, i] = xs[0],
|
||||
[x, j] = Array.from(
|
||||
until(
|
||||
v => w <= `${v[0]}`.length
|
||||
)(
|
||||
v => fi(1 + v[1])
|
||||
)(fi(i))
|
||||
);
|
||||
|
||||
return [
|
||||
[1 + w, j, x],
|
||||
...xs
|
||||
];
|
||||
};
|
||||
|
||||
return until(x => n < x[0][0])(
|
||||
nxtWidth
|
||||
)([
|
||||
[2, 0, 0]
|
||||
]);
|
||||
};
|
||||
|
||||
|
||||
// ---------------- GENERIC FUNCTIONS ----------------
|
||||
|
||||
// enumFromTo :: Int -> Int -> [Int]
|
||||
const enumFromTo = m =>
|
||||
n => Array.from({
|
||||
length: 1 + n - m
|
||||
}, (_, i) => m + i);
|
||||
|
||||
|
||||
// fanArrow (&&&) ::
|
||||
// (a -> b) -> (a -> c) -> (a -> (b, c))
|
||||
const fanArrow = f =>
|
||||
// A combined function, given f and g,
|
||||
// from x to a tuple of (f(x), g(x))
|
||||
// ((,) . f <*> g)
|
||||
g => x => [f(x), g(x)];
|
||||
|
||||
|
||||
// until :: (a -> Bool) -> (a -> a) -> a -> a
|
||||
const until = p =>
|
||||
// The value resulting from successive applications
|
||||
// of f to f(x), starting with a seed value x,
|
||||
// and terminating when the result returns true
|
||||
// for the predicate p.
|
||||
f => {
|
||||
const go = x =>
|
||||
p(x) ? x : go(f(x));
|
||||
|
||||
return go;
|
||||
};
|
||||
|
||||
// MAIN ---
|
||||
return main();
|
||||
})();
|
||||
9
Task/Fusc-sequence/Jq/fusc-sequence-1.jq
Normal file
9
Task/Fusc-sequence/Jq/fusc-sequence-1.jq
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
# input should be a non-negative integer
|
||||
def commatize:
|
||||
# "," is 44
|
||||
def digits: tostring | explode | reverse;
|
||||
[foreach digits[] as $d (-1; .+1;
|
||||
(select(. > 0 and . % 3 == 0)|44), $d)]
|
||||
| reverse | implode ;
|
||||
|
||||
def lpad($len): tostring | ($len - length) as $l | (" " * $l)[:$l] + .;
|
||||
34
Task/Fusc-sequence/Jq/fusc-sequence-2.jq
Normal file
34
Task/Fusc-sequence/Jq/fusc-sequence-2.jq
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
# Save space by truncating the beginning of the array
|
||||
def fusc:
|
||||
0, 1,
|
||||
foreach range(2; infinite) as $n ([0, 1];
|
||||
($n % 2 == 0) as $even
|
||||
| if $even then . + [.[1]] else.[1:] + [.[1] + .[2]] end;
|
||||
.[-1] );
|
||||
|
||||
# Report first longest
|
||||
def fusc( $mx ):
|
||||
def l: commatize|lpad(10);
|
||||
|
||||
foreach limit( $mx; fusc ) as $f ({ maxLen: 0, n: 0 };
|
||||
.emit = false
|
||||
| ("\($f)"|length) as $len
|
||||
| if $len > .maxLen
|
||||
then .maxLen = $len
|
||||
| .emit = "\(.n|l) \($f|commatize)"
|
||||
else .
|
||||
end
|
||||
| .n += 1
|
||||
;
|
||||
select(.emit).emit
|
||||
);
|
||||
|
||||
# First $first numbers in the fusc sequence
|
||||
61 as $first
|
||||
| 2e6 as $mx
|
||||
| "The first \($first) numbers in the fusc sequence are:",
|
||||
([limit($first; fusc)]| map(tostring) | join(" ")) ,
|
||||
|
||||
"\nFirst terms longer than any previous ones for indices < \($mx + 0 |commatize):",
|
||||
" Index Value",
|
||||
fusc($mx)
|
||||
27
Task/Fusc-sequence/Julia/fusc-sequence.julia
Normal file
27
Task/Fusc-sequence/Julia/fusc-sequence.julia
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
using Memoize, Formatting
|
||||
|
||||
@memoize function sternbrocot(n)
|
||||
if n < 2
|
||||
return n
|
||||
elseif iseven(n)
|
||||
return sternbrocot(div(n, 2))
|
||||
else
|
||||
m = div(n - 1, 2)
|
||||
return sternbrocot(m) + sternbrocot(m + 1)
|
||||
end
|
||||
end
|
||||
|
||||
function fusclengths(N=100000000)
|
||||
println("sequence number : fusc value")
|
||||
maxlen = 0
|
||||
for i in 0:N
|
||||
x = sternbrocot(i)
|
||||
if (len = length(string(x))) > maxlen
|
||||
println(lpad(format(i, commas=true), 15), " : ", format(x, commas=true))
|
||||
maxlen = len
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
println("The first 61 fusc numbers are: ", [sternbrocot(x) for x in 0:60])
|
||||
fusclengths()
|
||||
43
Task/Fusc-sequence/Kotlin/fusc-sequence.kotlin
Normal file
43
Task/Fusc-sequence/Kotlin/fusc-sequence.kotlin
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
// Version 1.3.21
|
||||
|
||||
fun fusc(n: Int): IntArray {
|
||||
if (n <= 0) return intArrayOf()
|
||||
if (n == 1) return intArrayOf(0)
|
||||
val res = IntArray(n)
|
||||
res[1] = 1
|
||||
for (i in 2 until n) {
|
||||
if (i % 2 == 0) {
|
||||
res[i] = res[i / 2]
|
||||
} else {
|
||||
res[i] = res[(i - 1) / 2] + res[(i + 1) / 2]
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
fun fuscMaxLen(n: Int): List<Pair<Int, Int>> {
|
||||
var maxLen = -1
|
||||
var maxFusc = -1
|
||||
val f = fusc(n)
|
||||
val res = mutableListOf<Pair<Int, Int>>()
|
||||
for (i in 0 until n) {
|
||||
if (f[i] <= maxFusc) continue // avoid string conversion
|
||||
maxFusc = f[i]
|
||||
val len = f[i].toString().length
|
||||
if (len > maxLen) {
|
||||
res.add(Pair(i, f[i]))
|
||||
maxLen = len
|
||||
}
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
fun main() {
|
||||
println("The first 61 fusc numbers are:")
|
||||
println(fusc(61).asList())
|
||||
println("\nThe fusc numbers whose length > any previous fusc number length are:")
|
||||
val res = fuscMaxLen(20_000_000) // examine first 20 million numbers say
|
||||
for (r in res) {
|
||||
System.out.printf("%,7d (index %,10d)\n", r.second, r.first)
|
||||
}
|
||||
}
|
||||
43
Task/Fusc-sequence/Lua/fusc-sequence.lua
Normal file
43
Task/Fusc-sequence/Lua/fusc-sequence.lua
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
function fusc(n)
|
||||
n = math.floor(n)
|
||||
if n == 0 or n == 1 then
|
||||
return n
|
||||
elseif n % 2 == 0 then
|
||||
return fusc(n / 2)
|
||||
else
|
||||
return fusc((n - 1) / 2) + fusc((n + 1) / 2)
|
||||
end
|
||||
end
|
||||
|
||||
function numLen(n)
|
||||
local sum = 1
|
||||
while n > 9 do
|
||||
n = math.floor(n / 10)
|
||||
sum = sum + 1
|
||||
end
|
||||
return sum
|
||||
end
|
||||
|
||||
function printLargeFuscs(limit)
|
||||
print("Printing all largest Fusc numbers up to " .. limit)
|
||||
print("Index-------Value")
|
||||
local maxLen = 1
|
||||
for i=0,limit do
|
||||
local f = fusc(i)
|
||||
local le = numLen(f)
|
||||
if le > maxLen then
|
||||
maxLen = le
|
||||
print(string.format("%5d%12d", i, f))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
function main()
|
||||
print("Index-------Value")
|
||||
for i=0,60 do
|
||||
print(string.format("%5d%12d", i, fusc(i)))
|
||||
end
|
||||
printLargeFuscs(math.pow(2, 31) - 1)
|
||||
end
|
||||
|
||||
main()
|
||||
13
Task/Fusc-sequence/M2000-Interpreter/fusc-sequence-1.m2000
Normal file
13
Task/Fusc-sequence/M2000-Interpreter/fusc-sequence-1.m2000
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
module Fusc_sequence (max as long) {
|
||||
long n, max_len=-1, m
|
||||
string fmt="#,##0", fs="{0:-10} : {1}"
|
||||
dim f(0 to max) as long
|
||||
f(0)=0, 1
|
||||
for n=2 To max{If binary.and(n,1) Then f(n)=f((n-1)/2)+f((n+1)/2) else f(n)=f(n/2)}
|
||||
print "First 61 terms:"
|
||||
print "["+f()#slice(0,60)#str$(", ")+"]"
|
||||
print "Points in the sequence where an item has more digits than any previous items:"
|
||||
print format$(fs, "index", "value")
|
||||
for n=0 to max{if f(n)>=max_len then m++:max_len=10&**m:print format$(fs,str$(n,fmt),str$(f(n),fmt)):refresh}
|
||||
}
|
||||
Fusc_sequence 700000
|
||||
40
Task/Fusc-sequence/M2000-Interpreter/fusc-sequence-2.m2000
Normal file
40
Task/Fusc-sequence/M2000-Interpreter/fusc-sequence-2.m2000
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
module Fusc_sequence (level) {
|
||||
class z {
|
||||
boolean noStop=true
|
||||
module generate(&k()) {
|
||||
object q=stack:=1
|
||||
call k(0)
|
||||
call k(1)
|
||||
stack q {
|
||||
x=number:data x:call k(x)
|
||||
x+=stackitem():data x:call k(x)
|
||||
if .noStop then loop
|
||||
}
|
||||
q=stack
|
||||
.noStop<=true
|
||||
}
|
||||
}
|
||||
z=z()
|
||||
long max=61, n, k=-1, m
|
||||
string fmt="#,##0", fs="{0:-10} : {1}", prev
|
||||
function f1(new x) {
|
||||
n++
|
||||
if n=1 then print "First 61 terms:":print "[";
|
||||
if n<max then
|
||||
print x+", ";
|
||||
else.if n=max then
|
||||
print x+"]"
|
||||
z.noStop=false
|
||||
end if
|
||||
}
|
||||
profiler
|
||||
z.generate lazy$(&f1())
|
||||
print "Points in the sequence where an item has more digits than any previous items:"
|
||||
print format$(fs, "index", "value")
|
||||
n=0: max=level
|
||||
function f2(new x) {if x>=k then m++:k=10&**m:print format$(fs,str$(n,fmt),str$(x,fmt)):if m=max then z.noStop=false
|
||||
n++}
|
||||
z.generate lazy$(&f2())
|
||||
print timecount
|
||||
}
|
||||
Fusc_sequence 5
|
||||
16
Task/Fusc-sequence/Mathematica/fusc-sequence.math
Normal file
16
Task/Fusc-sequence/Mathematica/fusc-sequence.math
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
ClearAll[Fusc]
|
||||
Fusc[0] := 0
|
||||
Fusc[1] := 1
|
||||
Fusc[n_] := Fusc[n] = If[EvenQ[n], Fusc[n/2], Fusc[(n - 1)/2] + Fusc[(n + 1)/2]]
|
||||
Fusc /@ Range[0, 60]
|
||||
res = {{0, 1}};
|
||||
i = 0;
|
||||
PrintTemporary[Dynamic[{res, i}]];
|
||||
While[Length[res] < 6,
|
||||
f = Fusc[i];
|
||||
If[IntegerLength[res[[-1, -1]]] < IntegerLength[f],
|
||||
AppendTo[res, {i, f}]
|
||||
];
|
||||
i++;
|
||||
];
|
||||
res
|
||||
23
Task/Fusc-sequence/Nim/fusc-sequence-1.nim
Normal file
23
Task/Fusc-sequence/Nim/fusc-sequence-1.nim
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
import strformat
|
||||
|
||||
func fusc(n: int): int =
|
||||
if n == 0 or n == 1:
|
||||
n
|
||||
elif n mod 2 == 0:
|
||||
fusc(n div 2)
|
||||
else:
|
||||
fusc((n - 1) div 2) + fusc((n + 1) div 2)
|
||||
|
||||
echo "The first 61 Fusc numbers:"
|
||||
for i in 0..61:
|
||||
write(stdout, fmt"{fusc(i)} ")
|
||||
echo "\n\nThe Fusc numbers whose lengths are greater than those of previous Fusc numbers:"
|
||||
echo fmt" n fusc(n)"
|
||||
echo "--------- ---------"
|
||||
var maxLength = 0
|
||||
for i in 0..700_000:
|
||||
var f = fusc(i)
|
||||
var length = len($f)
|
||||
if length > maxLength:
|
||||
maxLength = length
|
||||
echo fmt"{i:9} {f:9}"
|
||||
51
Task/Fusc-sequence/Nim/fusc-sequence-2.nim
Normal file
51
Task/Fusc-sequence/Nim/fusc-sequence-2.nim
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import deques, strformat
|
||||
|
||||
|
||||
iterator fusc(): int =
|
||||
var q = [1].toDeque()
|
||||
yield 0
|
||||
yield 1
|
||||
|
||||
while true:
|
||||
var val = q.popFirst()
|
||||
q.addLast(val)
|
||||
yield val
|
||||
|
||||
val += q[0]
|
||||
q.addLast(val)
|
||||
yield val
|
||||
|
||||
|
||||
iterator longestFusc(): tuple[idx, val: int] =
|
||||
var sofar = 0
|
||||
var i = -1
|
||||
for f in fusc():
|
||||
inc i
|
||||
if f >= sofar:
|
||||
yield (i, f)
|
||||
sofar = if sofar == 0: 10 else: 10 * sofar
|
||||
|
||||
|
||||
#———————————————————————————————————————————————————————————————————————————————————————————————————
|
||||
|
||||
const
|
||||
MaxFusc = 61
|
||||
LongestCount = 7
|
||||
|
||||
echo &"First {MaxFusc}:"
|
||||
var i = -1
|
||||
for f in fusc():
|
||||
inc i
|
||||
stdout.write f
|
||||
if i == MaxFusc:
|
||||
echo ""
|
||||
break
|
||||
stdout.write ' '
|
||||
|
||||
echo "\nLength records:"
|
||||
var count = 0
|
||||
for (i, f) in longestFusc():
|
||||
inc count
|
||||
echo &"fusc({i}) = {f}"
|
||||
if count == LongestCount:
|
||||
break
|
||||
22
Task/Fusc-sequence/OCaml/fusc-sequence.ocaml
Normal file
22
Task/Fusc-sequence/OCaml/fusc-sequence.ocaml
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
let seq_fusc =
|
||||
let rec next x xs () =
|
||||
match xs () with
|
||||
| Seq.Nil -> assert false
|
||||
| Cons (x', xs') -> Seq.Cons (x' + x, Seq.cons x' (next x' xs'))
|
||||
in
|
||||
let rec tail () = Seq.Cons (1, next 1 tail) in
|
||||
Seq.cons 0 (Seq.cons 1 tail)
|
||||
|
||||
let seq_first_of_lengths =
|
||||
let rec next i l sq () =
|
||||
match sq () with
|
||||
| Seq.Nil -> Seq.Nil
|
||||
| Cons (x, xs) when x >= l -> Cons ((i, x), next (succ i) (10 * l) xs)
|
||||
| Cons (_, xs) -> next (succ i) l xs ()
|
||||
in next 0 10
|
||||
|
||||
let () =
|
||||
seq_fusc |> Seq.take 61 |> Seq.iter (Printf.printf " %u") |> print_newline
|
||||
and () =
|
||||
seq_fusc |> seq_first_of_lengths |> Seq.take 7
|
||||
|> Seq.iter (fun (i, x) -> Printf.printf "%9u @ %u%!\n" x i)
|
||||
127
Task/Fusc-sequence/Pascal/fusc-sequence.pas
Normal file
127
Task/Fusc-sequence/Pascal/fusc-sequence.pas
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
program fusc;
|
||||
uses
|
||||
sysutils;
|
||||
const
|
||||
{$IFDEF FPC}
|
||||
MaxIdx = 1253 * 1000 * 1000; //19573420; // must be even
|
||||
{$ELSE}
|
||||
// Dynamics arrays in Delphi cann't be to large
|
||||
MaxIdx = 19573420;
|
||||
{$ENDIF}
|
||||
|
||||
type
|
||||
tFuscElem = LongWord;
|
||||
tFusc = array of tFuscElem;
|
||||
var
|
||||
FuscField : tFusc;
|
||||
|
||||
function commatize(n:NativeUint):string;
|
||||
var
|
||||
l,i : NativeUint;
|
||||
begin
|
||||
str(n,result);
|
||||
l := length(result);
|
||||
//no commatize
|
||||
if l < 4 then
|
||||
exit;
|
||||
//new length
|
||||
i := l+ (l-1) DIV 3;
|
||||
setlength(result,i);
|
||||
//copy chars to the right place
|
||||
While i <> l do
|
||||
Begin
|
||||
result[i]:= result[l];result[i-1]:= result[l-1];
|
||||
result[i-2]:= result[l-2];result[i-3]:= ',';
|
||||
dec(i,4);dec(l,3);
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure OutFusc(StartIdx,EndIdx :NativeInt;const FF:tFusc);
|
||||
Begin
|
||||
IF StartIdx < Low(FF) then StartIdx :=Low(FF);
|
||||
IF EndIdx > High(FF) then EndIdx := High(FF);
|
||||
For StartIdx := StartIdx to EndIdx do
|
||||
write(FF[StartIdx],' ');
|
||||
writeln;
|
||||
end;
|
||||
|
||||
procedure FuscCalc(var FF:tFusc);
|
||||
var
|
||||
pFFn,pFFi : ^tFuscElem;
|
||||
i,n,sum : NativeUint;
|
||||
Begin
|
||||
FF[0]:= 0;
|
||||
FF[1]:= 1;
|
||||
n := 2;
|
||||
i := 1;
|
||||
pFFn := @FF[n];
|
||||
pFFi := @FF[i];
|
||||
sum := pFFi^;
|
||||
while n <= MaxIdx-2 do
|
||||
begin
|
||||
//even
|
||||
pFFn^ := sum;//FF[n] := FF[i];
|
||||
//odd
|
||||
inc(pFFi);//FF[i+1]
|
||||
inc(pFFn);//FF[n+1]
|
||||
sum := sum+pFFi^;
|
||||
pFFn^:= sum; //FF[n+1] := FF[i]+FF[i+1];
|
||||
sum := pFFi^;
|
||||
inc(pFFn);
|
||||
inc(n,2);
|
||||
//inc(i);
|
||||
end;
|
||||
end;
|
||||
|
||||
procedure OutHeader(base:NativeInt);
|
||||
begin
|
||||
writeln('Fusc numbers with more digits in base ',base,' than all previous ones:');
|
||||
writeln('Value':10,'Index':10,' IndexNum/IndexNumBefore');
|
||||
writeln('======':10,' =======':14);
|
||||
end;
|
||||
|
||||
procedure CheckFuscDigits(const FF:tFusc;Base:NativeUint);
|
||||
var
|
||||
pFF : ^tFuscElem;
|
||||
Dig,
|
||||
i,lastIdx: NativeInt;
|
||||
Begin
|
||||
OutHeader(base);
|
||||
Dig := -1;
|
||||
i := 0;
|
||||
lastIdx := 0;
|
||||
pFF := @FF[0];// aka FF[i]
|
||||
repeat
|
||||
//search in tight loop speeds up
|
||||
repeat
|
||||
inc(pFF);
|
||||
inc(i);
|
||||
until pFF^ >Dig;
|
||||
|
||||
if i>= MaxIdx then
|
||||
BREAK;
|
||||
//output
|
||||
write(commatize(pFF^):10,commatize(i):14);//,DIG:10);
|
||||
IF lastIdx> 0 then
|
||||
write(i/lastIdx:12:7);
|
||||
writeln;
|
||||
lastIdx := i;
|
||||
IF Dig >0 then
|
||||
Dig := Dig*Base+Base-1
|
||||
else
|
||||
Dig := Base-1;
|
||||
until false;
|
||||
writeln;
|
||||
end;
|
||||
|
||||
BEGIN
|
||||
setlength(FuscField,MaxIdx);
|
||||
FuscCalc(FuscField);
|
||||
writeln('First 61 fusc numbers:');
|
||||
OutFusc(0,60,FuscField);
|
||||
|
||||
CheckFuscDigits(FuscField,10);
|
||||
CheckFuscDigits(FuscField,11); //11 ~phi^5 1.6180..^5 = 11,09
|
||||
setlength(FuscField,0);
|
||||
{$IFDEF WIN}readln;{$ENDIF}
|
||||
END.
|
||||
25
Task/Fusc-sequence/Perl/fusc-sequence.pl
Normal file
25
Task/Fusc-sequence/Perl/fusc-sequence.pl
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
use strict;
|
||||
use warnings;
|
||||
use feature 'say';
|
||||
|
||||
sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
|
||||
|
||||
sub stern_diatomic {
|
||||
my ($p,$q,$i) = (0,1,shift);
|
||||
while ($i) {
|
||||
if ($i & 1) { $p += $q; } else { $q += $p; }
|
||||
$i >>= 1;
|
||||
}
|
||||
$p;
|
||||
}
|
||||
|
||||
say "First 61 terms of the Fusc sequence:\n" . join ' ', map { stern_diatomic($_) } 0..60;
|
||||
say "\nIndex and value for first term longer than any previous:";
|
||||
|
||||
my $i = 0;
|
||||
my $l = -1;
|
||||
while ($l < 5) {
|
||||
my $v = stern_diatomic($i);
|
||||
printf("%15s : %s\n", comma($i), comma($v)) and $l = length $v if length $v > $l;
|
||||
$i++;
|
||||
}
|
||||
21
Task/Fusc-sequence/Phix/fusc-sequence.phix
Normal file
21
Task/Fusc-sequence/Phix/fusc-sequence.phix
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
(phixonline)[nb very slow]-->
|
||||
<span style="color: #008080;">constant</span> <span style="color: #000000;">limit</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">20_000_000</span>
|
||||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">fuscs</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">limit</span><span style="color: #0000FF;">);</span> <span style="color: #000080;font-style:italic;">-- NB 1-based indexing; fusc(0)===fuscs[1]</span>
|
||||
<span style="color: #000000;">fuscs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1</span> <span style="color: #000080;font-style:italic;">-- ie fusc(1):=1</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #000000;">limit</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #000000;">fuscs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">remainder</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)?</span><span style="color: #000000;">fuscs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">fuscs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]:</span><span style="color: #000000;">fuscs</span><span style="color: #0000FF;">[(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">])</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<span style="color: #000080;font-style:italic;">--printf(1,"First 61 terms of the Fusc sequence:\n%v\n",{fuscs[1..61]})</span>
|
||||
<span style="color: #004080;">string</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">61</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">&=</span><span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%,d "</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fuscs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">])</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"First 61 terms of the Fusc sequence:\n%s\n\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">s</span><span style="color: #0000FF;">})</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Elements with more digits than any previous items:\n"</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">" Index : Value\n"</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #004080;">integer</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">fuscs</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #008080;">if</span> <span style="color: #000000;">fuscs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]>=</span><span style="color: #000000;">d</span> <span style="color: #008080;">then</span>
|
||||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%,15d : %,d\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">fuscs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">n</span><span style="color: #0000FF;">]})</span>
|
||||
<span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #008080;">iff</span><span style="color: #0000FF;">(</span><span style="color: #000000;">d</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span><span style="color: #0000FF;">?</span><span style="color: #000000;">10</span><span style="color: #0000FF;">:</span><span style="color: #000000;">d</span><span style="color: #0000FF;">*</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
<!--
|
||||
29
Task/Fusc-sequence/Picat/fusc-sequence.picat
Normal file
29
Task/Fusc-sequence/Picat/fusc-sequence.picat
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
main =>
|
||||
println("First 61 fusc numbers:"),
|
||||
println([fusc(I) : I in 0..60]),
|
||||
nl,
|
||||
println("Points in the sequence whose length is greater than any previous fusc number length:\n"),
|
||||
println(" Index fusc Len"),
|
||||
largest_fusc_string(20_000_000).
|
||||
|
||||
table
|
||||
fusc(0) = 0.
|
||||
fusc(1) = 1.
|
||||
fusc(N) = fusc(N//2), even(N) => true.
|
||||
fusc(N) = fusc((N-1)//2) + fusc((N+1)//2) => true.
|
||||
|
||||
largest_fusc_string(Limit) =>
|
||||
largest_fusc_string(0,Limit,0).
|
||||
|
||||
largest_fusc_string(Limit,Limit,_).
|
||||
largest_fusc_string(N,Limit,LargestLen) :-
|
||||
N <= Limit,
|
||||
F = fusc(N),
|
||||
Len = F.to_string.len,
|
||||
(Len > LargestLen ->
|
||||
printf("%8d %8d %4d\n",N,F,Len),
|
||||
LargestLen1 = Len
|
||||
;
|
||||
LargestLen1 = LargestLen
|
||||
),
|
||||
largest_fusc_string(N+1,Limit,LargestLen1).
|
||||
27
Task/Fusc-sequence/Processing/fusc-sequence.processing
Normal file
27
Task/Fusc-sequence/Processing/fusc-sequence.processing
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
void setup() {
|
||||
println("First 61 terms:");
|
||||
for (int i = 0; i < 60; i++) {
|
||||
print(fusc(i) + " ");
|
||||
}
|
||||
println(fusc(60));
|
||||
println();
|
||||
println("Sequence elements where number of digits of the value increase:");
|
||||
int max_len = 0;
|
||||
for (int i = 0; i < 700000; i++) {
|
||||
int temp = fusc(i);
|
||||
if (str(temp).length() > max_len) {
|
||||
max_len = str(temp).length();
|
||||
println("(" + i + ", " + temp + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int fusc(int n) {
|
||||
if (n <= 1) {
|
||||
return n;
|
||||
} else if (n % 2 == 0) {
|
||||
return fusc(n / 2);
|
||||
} else {
|
||||
return fusc((n - 1) / 2) + fusc((n + 1) / 2);
|
||||
}
|
||||
}
|
||||
55
Task/Fusc-sequence/Prolog/fusc-sequence.pro
Normal file
55
Task/Fusc-sequence/Prolog/fusc-sequence.pro
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
:- dynamic fusc_cache/2.
|
||||
|
||||
fusc(0, 0):-!.
|
||||
fusc(1, 1):-!.
|
||||
fusc(N, F):-
|
||||
fusc_cache(N, F),
|
||||
!.
|
||||
fusc(N, F):-
|
||||
0 is N mod 2,
|
||||
!,
|
||||
M is N//2,
|
||||
fusc(M, F),
|
||||
assertz(fusc_cache(N, F)).
|
||||
fusc(N, F):-
|
||||
N1 is (N - 1)//2,
|
||||
N2 is (N + 1)//2,
|
||||
fusc(N1, F1),
|
||||
fusc(N2, F2),
|
||||
F is F1 + F2,
|
||||
assertz(fusc_cache(N, F)).
|
||||
|
||||
print_fusc_sequence(N):-
|
||||
writef('First %w fusc numbers:\n', [N]),
|
||||
print_fusc_sequence(N, 0),
|
||||
nl.
|
||||
|
||||
print_fusc_sequence(N, M):-
|
||||
M >= N,
|
||||
!.
|
||||
print_fusc_sequence(N, M):-
|
||||
fusc(M, F),
|
||||
writef('%w ', [F]),
|
||||
M1 is M + 1,
|
||||
print_fusc_sequence(N, M1).
|
||||
|
||||
print_max_fusc(N):-
|
||||
writef('Fusc numbers up to %w that are longer than any previous one:\n', [N]),
|
||||
print_max_fusc(N, 0, 0).
|
||||
|
||||
print_max_fusc(N, M, _):-
|
||||
M >= N,
|
||||
!.
|
||||
print_max_fusc(N, M, Max):-
|
||||
fusc(M, F),
|
||||
(F >= Max ->
|
||||
writef('n = %w, fusc(n) = %w\n', [M, F]), Max1 = max(10, Max * 10)
|
||||
;
|
||||
Max1 = Max
|
||||
),
|
||||
M1 is M + 1,
|
||||
print_max_fusc(N, M1, Max1).
|
||||
|
||||
main:-
|
||||
print_fusc_sequence(61),
|
||||
print_max_fusc(1000000).
|
||||
33
Task/Fusc-sequence/Python/fusc-sequence-1.py
Normal file
33
Task/Fusc-sequence/Python/fusc-sequence-1.py
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
from collections import deque
|
||||
from itertools import islice, count
|
||||
|
||||
|
||||
def fusc():
|
||||
q = deque([1])
|
||||
yield 0
|
||||
yield 1
|
||||
|
||||
while True:
|
||||
x = q.popleft()
|
||||
q.append(x)
|
||||
yield x
|
||||
|
||||
x += q[0]
|
||||
q.append(x)
|
||||
yield x
|
||||
|
||||
|
||||
def longest_fusc():
|
||||
sofar = 0
|
||||
for i, f in zip(count(), fusc()):
|
||||
if f >= sofar:
|
||||
yield(i, f)
|
||||
sofar = 10 * sofar or 10
|
||||
|
||||
|
||||
print('First 61:')
|
||||
print(list(islice(fusc(), 61)))
|
||||
|
||||
print('\nLength records:')
|
||||
for i, f in islice(longest_fusc(), 6):
|
||||
print(f'fusc({i}) = {f}')
|
||||
126
Task/Fusc-sequence/Python/fusc-sequence-2.py
Normal file
126
Task/Fusc-sequence/Python/fusc-sequence-2.py
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
'''Fusc sequence'''
|
||||
|
||||
from itertools import chain, count, islice
|
||||
from operator import itemgetter
|
||||
|
||||
|
||||
# As an infinite stream of terms,
|
||||
|
||||
# infiniteFusc :: [Int]
|
||||
def infiniteFusc():
|
||||
'''Fusc sequence.
|
||||
OEIS A2487
|
||||
'''
|
||||
def go(step):
|
||||
isEven, n, xxs = step
|
||||
x, xs = xxs[0], xxs[1:]
|
||||
if isEven:
|
||||
nxt = n + x
|
||||
return not isEven, nxt, xxs + [nxt]
|
||||
else:
|
||||
return not isEven, x, xs + [x]
|
||||
|
||||
return chain(
|
||||
[0, 1],
|
||||
map(
|
||||
itemgetter(1),
|
||||
iterate(go)(
|
||||
(True, 1, [1])
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# Or as a function over an integer:
|
||||
|
||||
# fusc :: Int -> Int
|
||||
def fusc(i):
|
||||
'''Fusc sequence'''
|
||||
def go(n):
|
||||
if 0 == n:
|
||||
return (1, 0)
|
||||
else:
|
||||
x, y = go(n // 2)
|
||||
return (x + y, y) if 0 == n % 2 else (
|
||||
x, x + y
|
||||
)
|
||||
return 0 if 1 > i else (
|
||||
go(i - 1)[0]
|
||||
)
|
||||
|
||||
|
||||
# firstFuscOfEachMagnitude ::
|
||||
def firstFuscOfEachMagnitude():
|
||||
'''Non-finite stream of each term
|
||||
in OEIS A2487 that requires an
|
||||
unprecedented quantity of decimal digits.
|
||||
'''
|
||||
a2487 = enumerate(map(fusc, count()))
|
||||
|
||||
def go(e):
|
||||
limit = 10 ** e
|
||||
return next(
|
||||
(i, x) for i, x in a2487
|
||||
if limit <= x
|
||||
)
|
||||
return (
|
||||
chain([(0, 0)], map(go, count(1)))
|
||||
)
|
||||
|
||||
|
||||
# --------------------------TEST---------------------------
|
||||
# main :: IO ()
|
||||
def main():
|
||||
'''Tests'''
|
||||
|
||||
print('First 61 terms:')
|
||||
print(showList(
|
||||
take(61)(
|
||||
map(fusc, count())
|
||||
)
|
||||
))
|
||||
|
||||
print('\nFirst term of each decimal magnitude:')
|
||||
print('(Index, Term):')
|
||||
ixs = firstFuscOfEachMagnitude()
|
||||
for _ in range(0, 5):
|
||||
print(next(ixs))
|
||||
|
||||
|
||||
# -------------------------GENERIC-------------------------
|
||||
|
||||
# iterate :: (a -> a) -> a -> Gen [a]
|
||||
def iterate(f):
|
||||
'''An infinite list of repeated
|
||||
applications of f to x.
|
||||
'''
|
||||
def go(x):
|
||||
v = x
|
||||
while True:
|
||||
yield v
|
||||
v = f(v)
|
||||
return lambda x: go(x)
|
||||
|
||||
|
||||
# showList :: [a] -> String
|
||||
def showList(xs):
|
||||
'''Compact stringification of a list.'''
|
||||
return '[' + ','.join(repr(x) for x in xs) + ']'
|
||||
|
||||
|
||||
# take :: Int -> [a] -> [a]
|
||||
# take :: Int -> String -> String
|
||||
def take(n):
|
||||
'''The prefix of xs of length n,
|
||||
or xs itself if n > length xs.
|
||||
'''
|
||||
return lambda xs: (
|
||||
xs[0:n]
|
||||
if isinstance(xs, (list, tuple))
|
||||
else list(islice(xs, n))
|
||||
)
|
||||
|
||||
|
||||
# MAIN ---
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
38
Task/Fusc-sequence/Quackery/fusc-sequence.quackery
Normal file
38
Task/Fusc-sequence/Quackery/fusc-sequence.quackery
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
[ 1 & ] is odd ( n --> b )
|
||||
|
||||
[ 0 swap
|
||||
[ dip 1+
|
||||
10 / dup
|
||||
0 = until ]
|
||||
drop ] is digits ( n --> n )
|
||||
|
||||
[ dup dup size
|
||||
dup odd iff
|
||||
[ dup 1 - 2 /
|
||||
dip
|
||||
[ 1 + 2 / peek
|
||||
over ]
|
||||
peek + ]
|
||||
else
|
||||
[ 2 / peek ]
|
||||
join ] is nextfusc ( [ --> [ )
|
||||
|
||||
say "First 61 terms." cr
|
||||
' [ 0 1 ]
|
||||
59 times nextfusc
|
||||
witheach [ echo sp ]
|
||||
cr cr
|
||||
say "Terms where the digit count increases." cr
|
||||
say "fusc(0) = 0" cr
|
||||
1 ' [ 0 1 ]
|
||||
[ nextfusc
|
||||
dup -1 peek digits
|
||||
rot 2dup > iff
|
||||
[ drop swap
|
||||
say "fusc("
|
||||
dup -1 peek echo
|
||||
say ") = "
|
||||
dup size 1 - echo cr ]
|
||||
else [ nip swap ]
|
||||
dup size 1000000 = until ]
|
||||
2drop
|
||||
15
Task/Fusc-sequence/R/fusc-sequence-1.r
Normal file
15
Task/Fusc-sequence/R/fusc-sequence-1.r
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
firstNFuscNumbers <- function(n)
|
||||
{
|
||||
stopifnot(n > 0)
|
||||
if(n == 1) return(0) else fusc <- c(0, 1)
|
||||
if(n > 2)
|
||||
{
|
||||
for(i in seq(from = 3, to = n, by = 1))
|
||||
{
|
||||
fusc[i] <- if(i %% 2) fusc[(i + 1) / 2] else fusc[i / 2] + fusc[(i + 2) / 2]
|
||||
}
|
||||
}
|
||||
fusc
|
||||
}
|
||||
first61 <- firstNFuscNumbers(61)
|
||||
cat("The first 61 Fusc numbers are:", "\n", first61, "\n")
|
||||
4
Task/Fusc-sequence/R/fusc-sequence-2.r
Normal file
4
Task/Fusc-sequence/R/fusc-sequence-2.r
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
index <- which.max(nchar(first61) == 2)
|
||||
number <- first61[index]
|
||||
cat("The first fusc number that is longer than all previous fusc numbers is", number,
|
||||
"and it occurs at index", index, "\n")
|
||||
7
Task/Fusc-sequence/R/fusc-sequence-3.r
Normal file
7
Task/Fusc-sequence/R/fusc-sequence-3.r
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
twentyMillion <- firstNFuscNumbers(2 * 10^7)
|
||||
twentyMillionCountable <- format(twentyMillion, scientific = FALSE, trim = TRUE)
|
||||
indices <- sapply(2:6, function(x) which.max(nchar(twentyMillionCountable) == x))
|
||||
numbers <- twentyMillion[indices]
|
||||
cat("Some fusc numbers that are longer than all previous fusc numbers are:\n",
|
||||
paste0(format(twentyMillion[indices], scientific = FALSE, trim = TRUE, big.mark = ","),
|
||||
" (at index ", format(indices, trim = TRUE, big.mark = ","), ")\n"))
|
||||
26
Task/Fusc-sequence/REXX/fusc-sequence-1.rexx
Normal file
26
Task/Fusc-sequence/REXX/fusc-sequence-1.rexx
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
/*REXX program calculates and displays the fusc (or Stern's Diatomic) sequence. */
|
||||
parse arg st # xw . /*obtain optional arguments from the CL*/
|
||||
if st=='' | st=="," then st= 0 /*Not specified? Then use the default.*/
|
||||
if #=='' | #=="," then #= 61 /* " " " " " " */
|
||||
if xw=='' | xw=="," then xw= 0 /* " " " " " " */
|
||||
list= xw<1 /*boolean value: LIST to show numbers*/
|
||||
@.=; @.0= 0; @.1= 1 /*assign array default; assign low vals*/
|
||||
mL= 0 /*the maximum length (digits) so far. */
|
||||
$= /* " list of fusc numbers " " */
|
||||
do j=0 for # /*process a bunch of integers from zero*/
|
||||
if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end
|
||||
else do; _= j % 2; @.j= @._; end
|
||||
if list then if j>=st then $= $ commas(@.j) /*add it to a list*/
|
||||
else nop /*NOP≡placeholder.*/
|
||||
else do; if length(@.j)<=mL then iterate /*still too small.*/
|
||||
mL= length(@.j) /*found increase. */
|
||||
if mL==1 then say '═══index═══ ═══fusc number═══'
|
||||
say right( commas(j), 9) right( commas(@.j), 14)
|
||||
if mL==xw then leave /*Found max length? Then stop looking.*/
|
||||
end /* [↑] display fusc #s of maximum len.*/
|
||||
end /*j*/
|
||||
/*$ has a superfluous leading blank. */
|
||||
if $\=='' then say strip($) /*display a horizontal list of fusc #s.*/
|
||||
exit 0 /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
|
||||
37
Task/Fusc-sequence/REXX/fusc-sequence-2.rexx
Normal file
37
Task/Fusc-sequence/REXX/fusc-sequence-2.rexx
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
/*REXX program calculates and displays the fusc (or Stern's Diatomic) sequence. */
|
||||
parse arg st # xw . /*obtain optional arguments from the CL*/
|
||||
if st=='' | st=="," then st= 0 /*Not specified? Then use the default.*/
|
||||
if #=='' | #=="," then #= 256 /* " " " " " " */
|
||||
if xw=='' | xw=="," then xw= 0 /* " " " " " " */
|
||||
list= xw<1 /*boolean value: LIST to show numbers*/
|
||||
@.=; @.0= 0; @.1= 1 /*assign array default; assign low vals*/
|
||||
mL= 0 /*the maximum length (digits) so far. */
|
||||
$= /* " list of fusc numbers " " */
|
||||
do j=0 for # /*process a bunch of integers from zero*/
|
||||
if j>1 then if j//2 then do; _= (j-1) % 2; p= (j+1) % 2; @.j= @._ + @.p; end
|
||||
else do; _= j % 2; @.j= @._; end
|
||||
if list then if j>=st then $= $ commas(@.j) /*add it to a list*/
|
||||
else nop /*NOP≡placeholder.*/
|
||||
else do; if length(@.j)<=mL then iterate /*still too small.*/
|
||||
mL= length(@.j) /*found increase. */
|
||||
if mL==1 then say '═══index═══ ═══fusc number═══'
|
||||
say right( commas(j), 9) right( commas(@.j), 14)
|
||||
if mL==xw then leave /*Found max length? Then stop looking.*/
|
||||
end /* [↑] display fusc #s of maximum len.*/
|
||||
end /*j*/
|
||||
/*$ has a superfluous leading blank. */
|
||||
if $=='' then exit 0 /*display a horizontal list of fusc #s.*/
|
||||
row= -1 /*output will be starting ar row zero.*/
|
||||
$$= 0 /*initialize with the zeroth entry (=0)*/
|
||||
do k=2 for #; y= word($, k) /*start processing with the 2nd number.*/
|
||||
if y==1 then do; row= row + 1 /*Is it unity? Then bump row number.*/
|
||||
say 'row('row")=" $$ /*display the row that was just created*/
|
||||
$$= 1 /*initialize a new row with 1 (unity).*/
|
||||
end
|
||||
else $$= $$ y /*Not unity? Just append it to a row.*/
|
||||
end /*k*/
|
||||
|
||||
if $$\=='' then say "row("row+1')=' $$ /*display any residual data in the row.*/
|
||||
exit 0 /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
commas: parse arg ?; do _=length(?)-3 to 1 by -3; ?=insert(',', ?, _); end; return ?
|
||||
44
Task/Fusc-sequence/Racket/fusc-sequence.rkt
Normal file
44
Task/Fusc-sequence/Racket/fusc-sequence.rkt
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
#lang racket
|
||||
|
||||
(require racket/generator)
|
||||
|
||||
(define (memoize f)
|
||||
(define table (make-hash))
|
||||
(λ args (hash-ref! table args (thunk (apply f args)))))
|
||||
|
||||
(define fusc
|
||||
(memoize
|
||||
(λ (n)
|
||||
(cond
|
||||
[(<= n 1) n]
|
||||
[(even? n) (fusc (/ n 2))]
|
||||
[else (+ (fusc (/ (sub1 n) 2)) (fusc (/ (add1 n) 2)))]))))
|
||||
|
||||
(define (comma x)
|
||||
(string-join
|
||||
(reverse
|
||||
(for/list ([digit (in-list (reverse (string->list (~a x))))] [i (in-naturals)])
|
||||
(cond
|
||||
[(and (= 0 (modulo i 3)) (> i 0)) (string digit #\,)]
|
||||
[else (string digit)])))
|
||||
""))
|
||||
|
||||
;; Task 1
|
||||
(displayln (string-join (for/list ([i (in-range 61)]) (comma (fusc i))) " "))
|
||||
(newline)
|
||||
|
||||
;; Task 2
|
||||
(define gen
|
||||
(in-generator
|
||||
(let loop ([prev 0] [i 0])
|
||||
(define result (fusc i))
|
||||
(define len (string-length (~a result)))
|
||||
(cond
|
||||
[(> len prev)
|
||||
(yield (list i result))
|
||||
(loop len (add1 i))]
|
||||
[else (loop prev (add1 i))]))))
|
||||
|
||||
(for ([i (in-range 5)] [x gen])
|
||||
(match-define (list index result) x)
|
||||
(printf "~a: ~a\n" (comma index) (comma result)))
|
||||
13
Task/Fusc-sequence/Raku/fusc-sequence-1.raku
Normal file
13
Task/Fusc-sequence/Raku/fusc-sequence-1.raku
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
my @Fusc = 0, 1, 1, { |(@Fusc[$_ - 1] + @Fusc[$_], @Fusc[$_]) given ++$+1 } ... *;
|
||||
|
||||
sub comma { $^i.flip.comb(3).join(',').flip }
|
||||
|
||||
put "First 61 terms of the Fusc sequence:\n{@Fusc[^61]}" ~
|
||||
"\n\nIndex and value for first term longer than any previous:";
|
||||
|
||||
for flat 'Index', 'Value', 0, 0, (1..4).map({
|
||||
my $l = 10**$_;
|
||||
@Fusc.first(* > $l, :kv).map: &comma
|
||||
}) -> $i, $v {
|
||||
printf "%15s : %s\n", $i, $v
|
||||
}
|
||||
5
Task/Fusc-sequence/Raku/fusc-sequence-2.raku
Normal file
5
Task/Fusc-sequence/Raku/fusc-sequence-2.raku
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
multi fusc( 0 ) { 0 }
|
||||
multi fusc( 1 ) { 1 }
|
||||
multi fusc( $n where $n %% 2 ) { fusc $n div 2 }
|
||||
multi fusc( $n ) { [+] map *.&fusc, ( $n - 1 ) div 2, ( $n + 1 ) div 2 }
|
||||
put map *.&fusc, 0..60;
|
||||
38
Task/Fusc-sequence/Ring/fusc-sequence.ring
Normal file
38
Task/Fusc-sequence/Ring/fusc-sequence.ring
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
# Project: Fusc sequence
|
||||
|
||||
max = 60
|
||||
fusc = list(36000)
|
||||
fusc[1] = 1
|
||||
see "working..." + nl
|
||||
see "wait for done..." + nl
|
||||
see "The first 61 fusc numbers are:" + nl
|
||||
fuscseq(max)
|
||||
see "0"
|
||||
for m = 1 to max
|
||||
see " " + fusc[m]
|
||||
next
|
||||
|
||||
see nl
|
||||
see "The fusc numbers whose length > any previous fusc number length are:" + nl
|
||||
see "Index Value" + nl
|
||||
see " 0 0" + nl
|
||||
d = 10
|
||||
for i = 1 to 36000
|
||||
if fusc[i] >= d
|
||||
see " " + i + " " + fusc[i] + nl
|
||||
if d = 0
|
||||
d = 1
|
||||
ok
|
||||
d = d*10
|
||||
ok
|
||||
next
|
||||
see "done..." + nl
|
||||
|
||||
func fuscseq(max)
|
||||
for n = 2 to 36000
|
||||
if n%2 = 1
|
||||
fusc[n] = fusc[(n-1)/2] + fusc[(n+1)/2]
|
||||
but n%2 = 0
|
||||
fusc[n] = fusc[n/2]
|
||||
ok
|
||||
next
|
||||
25
Task/Fusc-sequence/Ruby/fusc-sequence.rb
Normal file
25
Task/Fusc-sequence/Ruby/fusc-sequence.rb
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
fusc = Enumerator.new do |y|
|
||||
y << 0
|
||||
y << 1
|
||||
arr = [0,1]
|
||||
2.step do |n|
|
||||
res = n.even? ? arr[n/2] : arr[(n-1)/2] + arr[(n+1)/2]
|
||||
y << res
|
||||
arr << res
|
||||
end
|
||||
end
|
||||
|
||||
fusc_max_digits = Enumerator.new do |y|
|
||||
cur_max, cur_exp = 0, 0
|
||||
0.step do |i|
|
||||
f = fusc.next
|
||||
if f >= cur_max
|
||||
cur_exp += 1
|
||||
cur_max = 10**cur_exp
|
||||
y << [i, f]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
puts fusc.take(61).join(" ")
|
||||
fusc_max_digits.take(6).each{|pair| puts "%15s : %s" % pair }
|
||||
36
Task/Fusc-sequence/Rust/fusc-sequence.rust
Normal file
36
Task/Fusc-sequence/Rust/fusc-sequence.rust
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
fn fusc_sequence() -> impl std::iter::Iterator<Item = u32> {
|
||||
let mut sequence = vec![0, 1];
|
||||
let mut n = 0;
|
||||
std::iter::from_fn(move || {
|
||||
if n > 1 {
|
||||
sequence.push(match n % 2 {
|
||||
0 => sequence[n / 2],
|
||||
_ => sequence[(n - 1) / 2] + sequence[(n + 1) / 2],
|
||||
});
|
||||
}
|
||||
let result = sequence[n];
|
||||
n += 1;
|
||||
Some(result)
|
||||
})
|
||||
}
|
||||
|
||||
fn main() {
|
||||
println!("First 61 fusc numbers:");
|
||||
for n in fusc_sequence().take(61) {
|
||||
print!("{} ", n)
|
||||
}
|
||||
println!();
|
||||
|
||||
let limit = 1000000000;
|
||||
println!(
|
||||
"Fusc numbers up to {} that are longer than any previous one:",
|
||||
limit
|
||||
);
|
||||
let mut max = 0;
|
||||
for (index, n) in fusc_sequence().take(limit).enumerate() {
|
||||
if n >= max {
|
||||
max = std::cmp::max(10, max * 10);
|
||||
println!("index = {}, fusc number = {}", index, n);
|
||||
}
|
||||
}
|
||||
}
|
||||
20
Task/Fusc-sequence/Sidef/fusc-sequence.sidef
Normal file
20
Task/Fusc-sequence/Sidef/fusc-sequence.sidef
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
func fusc(n) is cached {
|
||||
|
||||
return 0 if n.is_zero
|
||||
return 1 if n.is_one
|
||||
|
||||
n.is_even ? fusc(n/2) : (fusc((n-1)/2) + fusc(((n-1)/2)+1))
|
||||
}
|
||||
|
||||
say ("First 61 terms of the Stern-Brocot sequence: ", 61.of(fusc).join(' '))
|
||||
|
||||
say "\nIndex and value for first term longer than any previous:"
|
||||
printf("%15s : %s\n", "Index", "Value");
|
||||
|
||||
var (index=0, len=0)
|
||||
|
||||
5.times {
|
||||
index = (index..Inf -> first_by { fusc(_).len > len })
|
||||
len = fusc(index).len
|
||||
printf("%15s : %s\n", index.commify, fusc(index).commify)
|
||||
}
|
||||
41
Task/Fusc-sequence/Swift/fusc-sequence.swift
Normal file
41
Task/Fusc-sequence/Swift/fusc-sequence.swift
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
struct FuscSeq: Sequence, IteratorProtocol {
|
||||
private var arr = [0, 1]
|
||||
private var i = 0
|
||||
|
||||
mutating func next() -> Int? {
|
||||
defer {
|
||||
i += 1
|
||||
}
|
||||
|
||||
guard i > 1 else {
|
||||
return arr[i]
|
||||
}
|
||||
|
||||
switch i & 1 {
|
||||
case 0:
|
||||
arr.append(arr[i / 2])
|
||||
case 1:
|
||||
arr.append(arr[(i - 1) / 2] + arr[(i + 1) / 2])
|
||||
case _:
|
||||
fatalError()
|
||||
}
|
||||
|
||||
return arr.last!
|
||||
}
|
||||
}
|
||||
|
||||
let first = FuscSeq().prefix(61)
|
||||
|
||||
print("First 61: \(Array(first))")
|
||||
|
||||
var max = -1
|
||||
|
||||
for (i, n) in FuscSeq().prefix(20_000_000).enumerated() {
|
||||
let f = String(n).count
|
||||
|
||||
if f > max {
|
||||
max = f
|
||||
|
||||
print("New max: \(i): \(n)")
|
||||
}
|
||||
}
|
||||
46
Task/Fusc-sequence/Tcl/fusc-sequence.tcl
Normal file
46
Task/Fusc-sequence/Tcl/fusc-sequence.tcl
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
proc fusc n {
|
||||
if {$n < 2} {
|
||||
return $n
|
||||
}
|
||||
|
||||
if {[info exists ::g_fusc($n)]} { return $::g_fusc($n) }
|
||||
|
||||
if {$n % 2} { ;# n is odd
|
||||
set r [expr {[fusc [expr {($n-1)/2}]] + [fusc [expr {($n+1)/2}]]}]
|
||||
} else { ;# n is even
|
||||
set r [fusc [expr {$n/2}]]
|
||||
}
|
||||
|
||||
if {$n < 999999} { set ::g_fusc($n) $r }
|
||||
|
||||
return $r
|
||||
}
|
||||
|
||||
proc ,,, {str {sep ,} {grouplen 3}} {
|
||||
set strlen [string length $str]
|
||||
set padlen [expr {($grouplen - ($strlen % $grouplen)) % $grouplen}]
|
||||
set r [regsub -all ... [string repeat " " $padlen]$str &$sep]
|
||||
return [string range $r $padlen end-[string length $sep]]
|
||||
}
|
||||
|
||||
proc tabline {a b c} {
|
||||
puts "[format %2s $a] [format %10s $b] [format %8s $c]"
|
||||
}
|
||||
|
||||
proc doit {{nmax 20000000}} {
|
||||
for {set i 0} {$i < 61} {incr i} {
|
||||
puts -nonewline " [fusc $i]"
|
||||
}
|
||||
puts ""
|
||||
tabline L n fusc(n)
|
||||
set maxL 0
|
||||
for {set n 0} {$n < $nmax} {incr n} {
|
||||
set f [fusc $n]
|
||||
set L [string length $f]
|
||||
if {$L > $maxL} {
|
||||
set maxL $L
|
||||
tabline $L [,,, $n] [,,, $f]
|
||||
}
|
||||
}
|
||||
}
|
||||
doit
|
||||
24
Task/Fusc-sequence/V-(Vlang)/fusc-sequence.v
Normal file
24
Task/Fusc-sequence/V-(Vlang)/fusc-sequence.v
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
fn main() {
|
||||
mut max_len, mut temp := 0, 0
|
||||
println("First 61 terms:")
|
||||
for i := 0; i < 60; i++ {
|
||||
print("${fusc(i)} ")
|
||||
}
|
||||
println(fusc(60))
|
||||
println("\nNumbers whose length is greater than any previous fusc number length:")
|
||||
println("Index:\tValue:")
|
||||
// less than 700,000 used
|
||||
for i := 0; i < 700000; i++ {
|
||||
temp = fusc(i)
|
||||
if temp.str().len > max_len {
|
||||
max_len = temp.str().len
|
||||
println("${i}\t${temp}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fusc(n int) int {
|
||||
if n <= 1 {return n}
|
||||
else if n % 2 == 0 {return fusc(n / 2)}
|
||||
else {return fusc((n - 1) / 2) + fusc((n + 1) / 2)}
|
||||
}
|
||||
26
Task/Fusc-sequence/Vala/fusc-sequence.vala
Normal file
26
Task/Fusc-sequence/Vala/fusc-sequence.vala
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
int fusc(int n) {
|
||||
if (n == 0 || n == 1)
|
||||
return n;
|
||||
else if (n % 2 == 0)
|
||||
return fusc(n / 2);
|
||||
else
|
||||
return fusc((n - 1) / 2) + fusc((n + 1) / 2);
|
||||
}
|
||||
|
||||
void main() {
|
||||
print("The first 61 fusc numbers:\n");
|
||||
for (int i = 0; i < 61; i++)
|
||||
print(@"$(fusc(i)) ");
|
||||
print("\n\nThe fusc numbers whose lengths are greater than those of previous fusc numbers:\n");
|
||||
print(" n fusc(n)\n");
|
||||
print("-------------------\n");
|
||||
var max_length = 0;
|
||||
for (int i = 0; i < 700000; i++) {
|
||||
var f = fusc(i);
|
||||
var length = f.to_string().length;
|
||||
if (length > max_length) {
|
||||
max_length = length;
|
||||
print("%9d %9d\n", i, f);
|
||||
}
|
||||
}
|
||||
}
|
||||
36
Task/Fusc-sequence/Visual-Basic-.NET/fusc-sequence.vb
Normal file
36
Task/Fusc-sequence/Visual-Basic-.NET/fusc-sequence.vb
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
Module Module1
|
||||
|
||||
Dim n As Integer = 61, l As List(Of Integer) = {0, 1}.ToList
|
||||
|
||||
Function fusc(n As Integer) As Integer
|
||||
If n < l.Count Then Return l(n)
|
||||
fusc = If((n And 1) = 0, l(n >> 1), l((n - 1) >> 1) + l((n + 1) >> 1))
|
||||
l.Add(fusc)
|
||||
End Function
|
||||
|
||||
Sub Main(args As String())
|
||||
Dim lst As Boolean = True, w As Integer = -1, c As Integer = 0,
|
||||
fs As String = "{0,11:n0} {1,-9:n0}", res As String = ""
|
||||
Console.WriteLine("First {0} numbers in the fusc sequence:", n)
|
||||
For i As Integer = 0 To Integer.MaxValue
|
||||
Dim f As Integer = fusc(i)
|
||||
If lst Then
|
||||
If i < 61 Then
|
||||
Console.Write("{0} ", f)
|
||||
Else
|
||||
lst = False
|
||||
Console.WriteLine()
|
||||
Console.WriteLine("Points in the sequence where an item has more digits than any previous items:")
|
||||
Console.WriteLine(fs, "Index\", "/Value") : Console.WriteLine(res) : res = ""
|
||||
End If
|
||||
End If
|
||||
Dim t As Integer = f.ToString.Length
|
||||
If t > w Then
|
||||
w = t
|
||||
res &= If(res = "", "", vbLf) & String.Format(fs, i, f)
|
||||
If Not lst Then Console.WriteLine(res) : res = ""
|
||||
c += 1 : If c > 5 Then Exit For
|
||||
End If
|
||||
Next : l.Clear()
|
||||
End Sub
|
||||
End Module
|
||||
27
Task/Fusc-sequence/Wren/fusc-sequence.wren
Normal file
27
Task/Fusc-sequence/Wren/fusc-sequence.wren
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import "/fmt" for Fmt
|
||||
|
||||
System.print("The first 61 numbers in the fusc sequence are:")
|
||||
var fusc = [0, 1]
|
||||
var fusc2 = [[0, 0]]
|
||||
var maxLen = 1
|
||||
var n = 2
|
||||
while (n < 20e6) { // limit to indices under 20 million say
|
||||
var f = (n % 2 == 0) ? fusc[n/2] : fusc[(n-1)/2] + fusc[(n+1)/2]
|
||||
fusc.add(f)
|
||||
var len = "%(f)".count
|
||||
if (len > maxLen) {
|
||||
maxLen = len
|
||||
if (n <= 60) {
|
||||
fusc2.add([n, f])
|
||||
} else {
|
||||
System.print("%(Fmt.dc(10, n)) %(Fmt.dc(0, f))")
|
||||
}
|
||||
}
|
||||
if (n == 60 ) {
|
||||
for (f in fusc) System.write("%(f) ")
|
||||
System.print("\n\nFirst terms longer than any previous ones for indices < 20,000,000:")
|
||||
System.print(" Index Value")
|
||||
for (iv in fusc2) System.print("%(Fmt.d(10, iv[0])) %(iv[1])")
|
||||
}
|
||||
n = n + 1
|
||||
}
|
||||
29
Task/Fusc-sequence/XPL0/fusc-sequence.xpl0
Normal file
29
Task/Fusc-sequence/XPL0/fusc-sequence.xpl0
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
func IntLen(N); \Return number of digits in N
|
||||
int N, L;
|
||||
[L:= 0;
|
||||
repeat N:= N/10;
|
||||
L:= L+1;
|
||||
until N = 0;
|
||||
return L;
|
||||
];
|
||||
|
||||
def Size = 1000000;
|
||||
int Fusc(Size), N, Len, Max;
|
||||
[Fusc(0):= 0; Fusc(1):= 1;
|
||||
for N:= 2 to Size-1 do
|
||||
Fusc(N):= if N&1 then Fusc((N-1)/2) + Fusc((N+1)/2) else Fusc(N/2);
|
||||
for N:= 0 to 60 do
|
||||
[IntOut(0, Fusc(N)); ChOut(0, ^ )];
|
||||
Text(0, "
|
||||
n fusc(n)
|
||||
");
|
||||
Max:= 0;
|
||||
for N:= 0 to Size-1 do
|
||||
[Len:= IntLen(Fusc(N));
|
||||
if Len > Max then
|
||||
[Max:= Len;
|
||||
IntOut(0, N); ChOut(0, 9\tab\);
|
||||
IntOut(0, Fusc(N)); CrLf(0);
|
||||
];
|
||||
];
|
||||
]
|
||||
30
Task/Fusc-sequence/Yabasic/fusc-sequence.basic
Normal file
30
Task/Fusc-sequence/Yabasic/fusc-sequence.basic
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
maximo = 20000000
|
||||
dim f(maximo)
|
||||
|
||||
fusc()
|
||||
|
||||
for i = 0 to 60
|
||||
print f(i), " ";
|
||||
next i
|
||||
|
||||
print "\n\n Index Value"
|
||||
d = 0
|
||||
for i = 0 to maximo-1
|
||||
if f(i) >= d then
|
||||
print i using "###,###,###", f(i) using "###,###,###"
|
||||
if d = 0 d = 1
|
||||
d = d * 10
|
||||
end if
|
||||
next i
|
||||
end
|
||||
|
||||
sub fusc()
|
||||
f(0) = 0 : f(1) = 1
|
||||
for n = 2 to maximo-1
|
||||
if mod(n, 2) then
|
||||
f(n) = f((n-1) / 2) + f((n+1) / 2)
|
||||
else
|
||||
f(n) = f(n / 2)
|
||||
end if
|
||||
next n
|
||||
end sub
|
||||
15
Task/Fusc-sequence/Zkl/fusc-sequence.zkl
Normal file
15
Task/Fusc-sequence/Zkl/fusc-sequence.zkl
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
fuscs:=List.createLong(1_000_000, 0); fuscs[1]=1; // we'll just use a big count
|
||||
foreach n in ([2..fuscs.len()-1]){ // and generate
|
||||
fuscs[n]=( if(n.isEven()) fuscs[n/2] else fuscs[(n-1)/2] + fuscs[(n+1)/2] )
|
||||
}
|
||||
|
||||
println("First 61 terms of the Stern-Brocot sequence:");
|
||||
fuscs[0,61].concat(" ").println();
|
||||
|
||||
println("\nIndex and value for first term longer than any previous:");
|
||||
println(" Index : Value");
|
||||
prevMax:=-1;
|
||||
foreach n in (fuscs.len()){
|
||||
f,fd := fuscs[n], f.numDigits;
|
||||
if(fd>prevMax){ println("%15,d : %,d".fmt(n,f)); prevMax=fd }
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue