Zeckendorf number representation: Difference between revisions

m
m (→‎{{header|Wren}}: Minor tidy)
 
(27 intermediate revisions by 14 users not shown)
Line 28:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V n = 20
F z(=n)
I n == 0
Line 45:
 
L(i) 0..n
print(‘#3: #8’.format(i, z(i).map(d -> String(d)).join(‘’)))</langsyntaxhighlight>
 
{{out}}
Line 74:
=={{header|360 Assembly}}==
{{trans|BBC BASIC}}
<langsyntaxhighlight lang="360asm">* Zeckendorf number representation 04/04/2017
ZECKEN CSECT
USING ZECKEN,R13 base register
Line 140:
XDEC DS CL12 temp
YREGS
END ZECKEN</langsyntaxhighlight>
{{out}}
<pre>
Line 167:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Encode(INT x CHAR ARRAY s)
INT ARRAY fib(22)=
[1 2 3 5 8 13 21 34 55 89 144 233 377 610
Line 206:
PrintF("%I -> %S%E",i,s)
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Zeckendorf_number_representation.png Screenshot from Atari 8-bit computer]
Line 235:
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Strings.Unbounded;
 
procedure Print_Zeck is
Line 260:
Ada.Text_IO.Put(To_String(Current) & " ");
end loop;
end Print_Zeck;</langsyntaxhighlight>
 
{{out}}<pre>1 10 100 101 1000 1001 1010 10000 10001 10010 10100 10101 100000 100001 100010 100100 100101 101000 101001 101010</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68"># print some Zeckendorf number representations #
 
# We handle 32-bit numbers, the maximum fibonacci number that can fit in a #
Line 324:
print( ( whole( i, -3 ), " ", to zeckendorf( i ), newline ) )
OD
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 353:
{{Trans|Haskell}} ('''mapAccumuL''' example)
 
<langsyntaxhighlight AppleScriptlang="applescript">--------------------- ZECKENDORF NUMBERS -------------------
 
-- zeckendorf :: Int -> String
Line 512:
end tell
return v
end |until|</langsyntaxhighlight>
{{Out}}
<pre>0
Line 538:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">Z: function [x][
if x=0 -> return "0"
fib: new [2 1]
Line 559:
 
loop 0..20 'i ->
print [pad to :string i 3 pad Z i 8]</langsyntaxhighlight>
 
{{out}}
Line 587:
=={{header|AutoHotkey}}==
{{works with|AutoHotkey_L}}
<langsyntaxhighlight AutoHotkeylang="autohotkey">Fib := NStepSequence(1, 2, 2, 20)
Loop, 21 {
i := A_Index - 1
Line 610:
}
return, a
}</langsyntaxhighlight>[http://rosettacode.org/wiki/Fibonacci_n-step_number_sequences#AutoHotkey NStepSequence()]
'''Output:'''
<pre>0: 0
Line 635:
 
=={{header|AutoIt}}==
<langsyntaxhighlight lang="autoit">
For $i = 0 To 20
ConsoleWrite($i &": "& Zeckendorf($i)&@CRLF)
Line 678:
Return $Array
EndFunc ;==>Fibonacci
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 704:
</pre>
 
=={{header|BBC BASIC}}==
==={{header|BBC BASIC}}===
<lang bbcbasic> FOR n% = 0 TO 20
<syntaxhighlight lang="bbcbasic"> FOR n% = 0 TO 20
PRINT n% RIGHT$(" " + FNzeckendorf(n%), 8)
NEXT
Line 731 ⟶ 732:
ENDIF
UNTIL i% = 1
= o$</langsyntaxhighlight>
'''Output:'''
<pre>
Line 759 ⟶ 760:
No Zeckendorf numbers contain consecutive 1's
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' version 17-10-2016
' compile with: fbc -s console
 
#Define max 92 ' max for Fibonacci number
 
Dim Shared As ULongInt fib(max)
 
fib(0) = 1
fib(1) = 1
 
For x As Integer = 2 To max
fib(x) = fib(x-1) + fib(x-2)
Next
 
Function num2zeck(n As Integer) As String
 
If n < 0 Then
Print "Error: no negative numbers allowed"
Beep : Sleep 5000,1 : End
End If
 
If n < 2 Then Return Str(n)
 
Dim As String zeckendorf
For x As Integer = max To 1 Step -1
If fib(x) <= n Then
zeckendorf = zeckendorf + "1"
n = n - fib(x)
Else
zeckendorf = zeckendorf + "0"
End If
Next
 
return LTrim(zeckendorf, "0") ' get rid of leading zeroes
End Function
 
' ------=< MAIN >=------
 
Dim As Integer x, e
Dim As String zeckendorf
Print "number zeckendorf"
 
For x = 0 To 200000
zeckendorf = num2zeck(x)
If x <= 20 Then Print x, zeckendorf
' check for two consecutive Fibonacci numbers
If InStr(zeckendorf, "11") <> 0 Then
Print " Error: two consecutive Fibonacci numbers "; x, zeckendorf
e = e +1
End If
Next
 
Print
If e = 0 Then
Print " No Zeckendorf numbers with two consecutive Fibonacci numbers found"
Else
Print e; " error(s) found"
End If
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>number zeckendorf
0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010
 
No Zeckendorf numbers with two consecutive Fibonacci numbers found</pre>
 
==={{header|Liberty BASIC}}===
''CBTJD'': 2020/03/09
{{works with|Just BASIC}}
<syntaxhighlight lang="vb">samples = 20
call zecklist samples
 
print "Decimal","Zeckendorf"
for n = 0 to samples
print n, zecklist$(n)
next n
 
Sub zecklist inDEC
dim zecklist$(inDEC)
do
bin$ = dec2bin$(count)
if instr(bin$,"11") = 0 then
zecklist$(found) = bin$
found = found + 1
end if
count = count+1
loop until found = inDEC + 1
End sub
 
function dec2bin$(inDEC)
do
bin$ = str$(inDEC mod 2) + bin$
inDEC = int(inDEC/2)
loop until inDEC = 0
dec2bin$ = bin$
end function</syntaxhighlight>
{{out}}
<pre>
Decimal Zeckendorf
0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010
</pre>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">Procedure.s zeck(n.i)
Dim f.i(1) : Define i.i=1, o$
f(0)=1 : f(1)=1
While f(i)<n
i+1 : ReDim f(ArraySize(f())+1) : f(i)=f(i-1)+f(i-2)
Wend
For i=i To 1 Step -1
If n>=f(i) : o$+"1" : n-f(i) : Else : o$+"0" : EndIf
Next
If Len(o$)>1 : o$=LTrim(o$,"0") : EndIf
ProcedureReturn o$
EndProcedure
 
Define n.i, t$
OpenConsole("Zeckendorf number representation")
PrintN(~"\tNr.\tZeckendorf")
For n=0 To 20
t$=zeck(n)
If FindString(t$,"11")
PrintN("Error: n= "+Str(n)+~"\tZeckendorf= "+t$)
Break
Else
PrintN(~"\t"+RSet(Str(n),3," ")+~"\t"+RSet(t$,7," "))
EndIf
Next
Input()</syntaxhighlight>
{{out}}
<pre> Nr. Zeckendorf
0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010</pre>
 
==={{header|QuickBASIC}}===
{{trans|ALGOL 68}}
<syntaxhighlight lang="qbasic">
' Zeckendorf number representation
DECLARE FUNCTION ToZeckendorf$ (N%)
' The maximum Fibonacci number that can fit in a
' 32 bit number is Fib&(45)
CONST MAXFIBINDEX% = 45, TRUE% = -1, FALSE% = 0
DIM SHARED Fib&(1 TO MAXFIBINDEX%)
Fib&(1) = 1: Fib&(2) = 2
FOR I% = 3 TO MAXFIBINDEX%
Fib&(I%) = Fib&(I% - 1) + Fib&(I% - 2)
NEXT I%
FOR I% = 0 TO 20
SixChars$ = SPACE$(6)
RSET SixChars$ = ToZeckendorf$(I%)
PRINT USING "### "; I%; : PRINT SixChars$
NEXT I%
END
 
FUNCTION ToZeckendorf$ (N%)
' returns the Zeckendorf representation of N% or "?" if one cannot be found
IF N% = 0 THEN
ToZeckendorf$ = "0"
ELSE
Result$ = ""
FPos% = MAXFIBINDEX%
Rest% = ABS(N%)
' Find the first non-zero Zeckendorf digit
WHILE FPos% > 1 AND Rest% < Fib&(FPos%)
FPos% = FPos% - 1
WEND
' If we found a digit, build the representation
IF FPos% >= 1 THEN ' have a digit
SkipDigit% = FALSE%
WHILE FPos% >= 1
IF Rest% <= 0 THEN
Result$ = Result$ + "0"
ELSEIF SkipDigit% THEN ' we used the previous digit
SkipDigit% = FALSE%
Result$ = Result$ + "0"
ELSEIF Rest% < Fib&(FPos%) THEN ' cannot use the digit at FPos%
SkipDigit% = FALSE%
Result$ = Result$ + "0"
ELSE ' can use this digit
SkipDigit% = TRUE%
Result$ = Result$ + "1"
Rest% = Rest% - Fib&(FPos%)
END IF
FPos% = FPos% - 1
WEND
END IF
IF Rest% = 0 THEN
ToZeckendorf$ = Result$
ELSE
ToZeckendorf$ = "?"
END IF
END IF
END FUNCTION
</syntaxhighlight>
{{out}}
<pre>
0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010
</pre>
 
==={{header|Sinclair ZX81 BASIC}}===
Works on the 1k RAM model, albeit without much room for manoeuvre. (You'd like the Zeckendorf numbers further over towards the right-hand side of the screen? Sorry, can't spare the video RAM.) If you have 2k or more, you can replace the constant 6 with some higher value wherever it occurs in the program and enable yourself to represent bigger numbers in Zeckendorf form.
<syntaxhighlight lang="basic"> 10 DIM F(6)
20 LET F(1)=1
30 LET F(2)=2
40 FOR I=3 TO 6
50 LET F(I)=F(I-2)+F(I-1)
60 NEXT I
70 FOR I=0 TO 20
80 LET Z$=""
90 LET S$=" "
100 LET Z=I
110 FOR J=6 TO 1 STEP -1
120 IF J=1 THEN LET S$="0"
130 IF Z<F(J) THEN GOTO 180
140 LET Z$=Z$+"1"
150 LET Z=Z-F(J)
160 LET S$="0"
170 GOTO 190
180 LET Z$=Z$+S$
190 NEXT J
200 PRINT I;" ";
210 IF I<10 THEN PRINT " ";
220 PRINT Z$
230 NEXT I</syntaxhighlight>
{{out}}
<pre>0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010</pre>
 
==={{header|uBasic/4tH}}===
<syntaxhighlight lang="text">For x = 0 to 20 ' Print Zeckendorf numbers 0 - 20
Print x,
Push x : Gosub _Zeckendorf ' get Zeckendorf number repres.
Print ' terminate line
Next
 
End
 
_Fibonacci
Push Tos() ' duplicate TOS()
@(0) = 0 ' This function returns the
@(1) = 1 ' Fibonacci number which is smaller
' or equal to TOS()
Do While @(1) < Tos() + 1
Push (@(1))
@(1) = @(0) + @(1) ' get next Fibonacci number
@(0) = Pop()
Loop ' loop if not exceeded TOS()
 
Gosub _Drop ' clear TOS()
Push @(0) ' return Fibonacci number
Return
 
_Zeckendorf
GoSub _Fibonacci ' This function breaks TOS() up
Print Tos(); ' into its Zeckendorf components
Push -(Pop() - Pop()) ' first digit is always there
' the remainder to resolve
Do While Tos() ' now go for the next digits
GoSub _Fibonacci
Print " + ";Tos(); ' print the next digit
Push -(Pop() - Pop())
Loop
 
Gosub _Drop ' clear TOS()
Return ' and return
 
_Drop
If Pop()%1 = 0 Then Return ' This function clears TOS()</syntaxhighlight>
Output:
<pre>0 0
1 1
2 2
3 3
4 3 + 1
5 5
6 5 + 1
7 5 + 2
8 8
9 8 + 1
10 8 + 2
11 8 + 3
12 8 + 3 + 1
13 13
14 13 + 1
15 13 + 2
16 13 + 3
17 13 + 3 + 1
18 13 + 5
19 13 + 5 + 1
20 13 + 5 + 2
 
0 OK, 0:901</pre>
 
==={{header|VBA}}===
{{trans|Phix}}<syntaxhighlight lang="vb">Private Function zeckendorf(ByVal n As Integer) As Integer
Dim r As Integer: r = 0
Dim c As Integer
Dim fib As New Collection
fib.Add 1
fib.Add 1
Do While fib(fib.Count) < n
fib.Add fib(fib.Count - 1) + fib(fib.Count)
Loop
For i = fib.Count To 2 Step -1
c = n >= fib(i)
r = r + r - c
n = n + c * fib(i)
Next i
zeckendorf = r
End Function
Public Sub main()
Dim i As Integer
For i = 0 To 20
Debug.Print Format(i, "@@"); ":"; Format(WorksheetFunction.Dec2Bin(zeckendorf(i)), "@@@@@@@")
Next i
End Sub</syntaxhighlight>{{out}}
<pre> 0: 0
1: 1
2: 10
3: 100
4: 101
5: 1000
6: 1001
7: 1010
8: 10000
9: 10001
10: 10010
11: 10100
12: 10101
13: 100000
14: 100001
15: 100010
16: 100100
17: 100101
18: 101000
19: 101001
20: 101010</pre>
 
==={{header|VBScript}}===
<syntaxhighlight lang="vb">
Function Zeckendorf(n)
num = n
Set fibonacci = CreateObject("System.Collections.Arraylist")
fibonacci.Add 1 : fibonacci.Add 2
i = 1
Do While fibonacci(i) < num
fibonacci.Add fibonacci(i) + fibonacci(i-1)
i = i + 1
Loop
tmp = ""
For j = fibonacci.Count-1 To 0 Step -1
If fibonacci(j) <= num And (tmp = "" Or Left(tmp,1) <> "1") Then
tmp = tmp & "1"
num = num - fibonacci(j)
Else
tmp = tmp & "0"
End If
Next
Zeckendorf = CLng(tmp)
End Function
 
'testing the function
For k = 0 To 20
WScript.StdOut.WriteLine k & ": " & Zeckendorf(k)
Next
</syntaxhighlight>
{{Out}}
<pre>
0: 0
1: 1
2: 10
3: 100
4: 101
5: 1000
6: 1001
7: 1010
8: 10000
9: 10001
10: 10010
11: 10100
12: 10101
13: 100000
14: 100001
15: 100010
16: 100100
17: 100101
18: 101000
19: 101001
20: 101010
</pre>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="yabasic">sub Zeckendorf(n)
local i, n$, c
do
n$ = bin$(i)
if not instr(n$,"11") then
print c,":\t",n$
if c = n break
c = c + 1
end if
i = i + 1
loop
end sub
 
Zeckendorf(20)
</syntaxhighlight>
 
=={{header|bc}}==
<syntaxhighlight lang="bc">obase = 2
f[0] = 1
f[t = 1] = 2
 
define z(n) {
auto p, r
 
for (p = t; p >= 0; --p) {
r += r
if (n >= f[p]) {
r += 1
n -= f[p]
}
}
return(r)
}
 
for (x = 0; x != 21; ++x) {
if (x > f[t]) {
t += 1
f[t] = f[t - 2] + f[t - 1]
}
z(x)
}</syntaxhighlight>
{{out}}
<pre>0
1
10
100
101
1000
1001
1010
10000
10001
10010
10100
10101
100000
100001
100010
100100
100101
101000
101001
101010</pre>
 
=={{header|Befunge}}==
The first number on the stack, <tt>45*</tt>, specifies the range of values to display. However, the algorithm depends on a hardcoded list of Fibonacci values (currently just 10) so the theoretical maximum is 143. It's also constrained by the range of a Befunge data cell, which on many implementations will be as low as 127.
 
<langsyntaxhighlight lang="befunge">45*83p0>:::.0`"0"v
v53210p 39+!:,,9+<
>858+37 *66g"7Y":v
Line 769 ⟶ 1,334:
^8:+1,+5_5<>-:0\`|
v:-\g39_^#:<*:p39<
>0\`:!"0"+#^ ,#$_^</langsyntaxhighlight>
 
{{out}}
Line 795 ⟶ 1,360:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
 
typedef unsigned long long u64;
Line 852 ⟶ 1,417:
 
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 879 ⟶ 1,444:
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">
using System;
using System.Collections.Generic;
Line 945 ⟶ 1,510:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 974 ⟶ 1,539:
{{works with|C++11}}
see [[Fibonacci sequence#Using Zeckendorf Numbers|Here]] for a further example using this class.
<langsyntaxhighlight lang="cpp">
// For a class N which implements Zeckendorf numbers:
// I define an increment operation ++()
Line 1,010 ⟶ 1,575:
return os;
}
</syntaxhighlight>
</lang>
I may now write:
<langsyntaxhighlight lang="cpp">
int main(void) {
//for (N G; G <= 101010N; ++G) std::cout << G << std::endl; // from zero to 101010M
Line 1,018 ⟶ 1,583:
return 0;
}
</syntaxhighlight>
</lang>
Which produces:
{{out}}
Line 1,042 ⟶ 1,607:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(def fibs (lazy-cat [1 1] (map + fibs (rest fibs))))
 
(defn z [n]
Line 1,054 ⟶ 1,619:
(->> ps (reduce fz [[] n]) first (apply str)))))
 
(doseq [n (range 0 21)] (println n (z n)))</langsyntaxhighlight>
 
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">% Get list of distinct Fibonacci numbers up to N
fibonacci = proc (n: int) returns (array[int])
list: array[int] := array[int]$[]
Line 1,097 ⟶ 1,662:
stream$putl(po, zeckendorf(i))
end
end start_up</langsyntaxhighlight>
{{out}}
<pre> 0: 0
Line 1,123 ⟶ 1,688:
=={{header|Common Lisp}}==
Common Lisp's arbitrary precision integers should handle any positive input:
<langsyntaxhighlight lang="lisp">(defun zeckendorf (n)
"returns zeckendorf integer of n (see OEIS A003714)"
(let ((fib '(2 1)))
Line 1,137 ⟶ 1,702:
;;; task requirement
(loop for i from 0 to 20 do
(format t "~2D: ~2R~%" i (zeckendorf i)))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="lisp">
;; Print Zeckendorf numbers upto 20.
;; I have implemented this as a state machine.
Line 1,150 ⟶ 1,715:
(if (= z 1) (format t "~S" 0)))))
(if (= z 0) (format t "~S~%" 0) (format t "~%"))))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,177 ⟶ 1,742:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub zeckendorf(n: uint32, buf: [uint8]): (r: [uint8]) is
Line 1,221 ⟶ 1,786:
print_nl();
i := i + 1;
end loop;</langsyntaxhighlight>
{{out}}
<pre>0: 0
Line 1,247 ⟶ 1,812:
=={{header|Crystal}}==
{{trans|Ruby of Python}}
<langsyntaxhighlight lang="ruby">def zeckendorf(n)
return 0 if n.zero?
fib = [1, 2]
Line 1,262 ⟶ 1,827:
end
(0..20).each { |i| puts "%3d: %8d" % [i, zeckendorf(i)] }</langsyntaxhighlight>
 
Using an explicit Iterator.
<langsyntaxhighlight lang="ruby">class ZeckendorfIterator
include Iterator(String)
 
Line 1,287 ⟶ 1,852:
end
 
zeckendorf(21).each_with_index{ |x,i| puts "%3d: %8s"% [i, x] }</langsyntaxhighlight>
 
Using oneliners.
<langsyntaxhighlight lang="ruby">def zeckendorf(n)
0.step.map(&.to_s(2)).reject(&.includes?("11")).first(n)
end
Line 1,300 ⟶ 1,865:
end
 
zeckendorf(21).each_with_index{ |x,i| puts "%3d: %8s"% [i, x] }</langsyntaxhighlight>
 
{{out}}
Line 1,329 ⟶ 1,894:
=={{header|D}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.algorithm, std.functional;
 
void main() {
Line 1,338 ⟶ 1,903:
.take(21)
.binaryReverseArgs!writefln("%(%b\n%)");
}</langsyntaxhighlight>
{{out}}
<pre>0
Line 1,363 ⟶ 1,928:
 
{{trans|Go}}
<langsyntaxhighlight lang="d">import std.stdio, std.typecons;
 
int zeckendorf(in int n) pure nothrow {
Line 1,384 ⟶ 1,949:
foreach (i; 0 .. 21)
writefln("%2d: %6b", i, zeckendorf(i));
}</langsyntaxhighlight>
{{out}}
<pre> 0: 0
Line 1,410 ⟶ 1,975:
{{trans|Tcl}}
(Same output.)
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
string zeckendorf(size_t n) {
Line 1,430 ⟶ 1,995:
foreach (immutable i; 0 .. 21)
writefln("%2d: %6s", i, i.zeckendorf);
}</langsyntaxhighlight>
 
=={{header|Dart}}==
{{trans|Java}}
<syntaxhighlight lang="Dart">
class Zeckendorf {
static String getZeckendorf(int n) {
if (n == 0) {
return "0";
}
List<int> fibNumbers = [1];
int nextFib = 2;
while (nextFib <= n) {
fibNumbers.add(nextFib);
nextFib += fibNumbers[fibNumbers.length - 2];
}
StringBuffer sb = StringBuffer();
for (int i = fibNumbers.length - 1; i >= 0; i--) {
int fibNumber = fibNumbers[i];
sb.write((fibNumber <= n) ? "1" : "0");
if (fibNumber <= n) {
n -= fibNumber;
}
}
return sb.toString();
}
 
static void main() {
for (int i = 0; i <= 20; i++) {
print("Z($i)=${getZeckendorf(i)}");
}
}
}
 
void main() {
Zeckendorf.main();
}
</syntaxhighlight>
{{out}}
<pre>
Z(0)=0
Z(1)=1
Z(2)=10
Z(3)=100
Z(4)=101
Z(5)=1000
Z(6)=1001
Z(7)=1010
Z(8)=10000
Z(9)=10001
Z(10)=10010
Z(11)=10100
Z(12)=10101
Z(13)=100000
Z(14)=100001
Z(15)=100010
Z(16)=100100
Z(17)=100101
Z(18)=101000
Z(19)=101001
Z(20)=101010
 
</pre>
 
=={{header|Delphi}}==
{{works with|Delphi|6.0}}
{{libheader|SysUtils,StdCtrls}}
 
 
<syntaxhighlight lang="Delphi">
 
const FibNums: array [0..21] of integer =
(1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, 610, 987, 1597, 2584,
4181, 6765, 10946, 17711, 28657);
 
 
function GetZeckNumber(N: integer): string;
{Returns Zeckendorf number for N as string}
var I: integer;
begin
Result:='';
{Subtract Fibonacci numbers from N}
for I:=High(FibNums) downto 0 do
if (N-FibNums[I])>=0 then
begin
Result:=Result+'1';
N:=N-FibNums[I];
end
else if Length(Result)>0 then Result:=Result+'0';
if Result='' then Result:='0';
end;
 
 
procedure ShowZeckendorfNumbers(Memo: TMemo);
var I: integer;
var S: string;
begin
S:='';
for I:=0 to 20 do
begin
Memo.Lines.Add(IntToStr(I)+': '+GetZeckNumber(I));
end;
end;
 
 
</syntaxhighlight>
{{out}}
<pre>
0: 0
1: 1
2: 10
3: 100
4: 101
5: 1000
6: 1001
7: 1010
8: 10000
9: 10001
10: 10010
11: 10100
12: 10101
13: 100000
14: 100001
15: 100010
16: 100100
17: 100101
18: 101000
19: 101001
20: 101010
 
Elapsed Time: 26.683 ms.
 
</pre>
 
 
=={{header|EasyLang}}==
{{trans|FreeBASIC}}
<syntaxhighlight>
proc mkfibs n . fib[] .
fib[] = [ ]
last = 1
current = 1
while current <= n
fib[] &= current
nxt = last + current
last = current
current = nxt
.
.
func$ zeckendorf n .
mkfibs n fib[]
for pos = len fib[] downto 1
if n >= fib[pos]
zeck$ &= "1"
n -= fib[pos]
else
zeck$ &= "0"
.
.
if zeck$ = ""
return "0"
.
return zeck$
.
for n = 0 to 20
print " " & n & " " & zeckendorf n
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
We analytically find the first fibonacci(i) >= n, using the formula i = log((n* Φ) + 0.5) / log(Φ) .
<langsyntaxhighlight lang="scheme">
;; special fib's starting with 1 2 3 5 ...
(define (fibonacci n)
Line 1,462 ⟶ 2,195:
(if ( > s n) 0
(begin (-= n s) 1 )))))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,476 ⟶ 2,209:
=={{header|Elena}}==
{{trans|C#}}
ELENA 46.x :
<langsyntaxhighlight lang="elena">import system'routines;
import system'collections;
import system'text;
Line 1,505 ⟶ 2,238:
while (currentFibonaciNum <= num)
{
fibonacciNumbers.append:(currentFibonaciNum);
fibPosition := fibPosition + 1;
Line 1,514 ⟶ 2,247:
int temp := num;
fibonacciNumbers.sequenceReverse().forEach::(item)
{
if (item <= temp)
Line 1,533 ⟶ 2,266:
public program()
{
for(int i := 1,; i <= 20,; i += 1)
{
console.printFormatted("{0} : {1}",i,i.zeckendorf()).writeLine()
Line 1,539 ⟶ 2,272:
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>1 : 1
Line 1,565 ⟶ 2,298:
{{trans|Ruby}}
Stream generator:
<langsyntaxhighlight lang="elixir">defmodule Zeckendorf do
def number do
Stream.unfold(0, fn n -> zn_loop(n) end)
Line 1,577 ⟶ 2,310:
 
Zeckendorf.number |> Enum.take(21) |> Enum.with_index
|> Enum.each(fn {zn, i} -> IO.puts "#{i}: #{zn}" end)</langsyntaxhighlight>
 
{{out}}
Line 1,605 ⟶ 2,338:
 
Fibonacci numbers:
<langsyntaxhighlight lang="elixir">defmodule Zeckendorf do
def number(n) do
fib_loop(n, [2,1])
Line 1,618 ⟶ 2,351:
end
 
for i <- 0..20, do: IO.puts "#{i}: #{Zeckendorf.number(i)}"</langsyntaxhighlight>
same output
 
 
=={{header|Erlang}}==
{{trans|Elixir}}
<syntaxhighlight lang="Erlang">
% Function to generate a list of the first N Zeckendorf numbers
number(N) ->
number_helper(N, 0, 0, []).
 
number_helper(0, _, _, Acc) ->
lists:reverse(Acc);
number_helper(N, Curr, Index, Acc) ->
case zn_loop(Curr) of
{Bin, Next} ->
number_helper(N - 1, Next, Index + 1, [{Bin, Index} | Acc])
end.
 
% Helper function to find the next Zeckendorf number
zn_loop(N) ->
Bin = my_integer_to_binary(N),
case re:run(Bin, "11", [{capture, none}]) of
match ->
zn_loop(N + 1);
nomatch ->
{Bin, N + 1}
end.
 
% Convert an integer to its binary representation as a string
my_integer_to_binary(N) ->
lists:flatten(io_lib:format("~.2B", [N])).
 
% Test function to output the first 21 Zeckendorf numbers
main([]) ->
ZnNumbers = number(21),
lists:foreach(
fun({Zn, I}) ->
io:format("~p: ~s~n", [I, Zn])
end, ZnNumbers).
</syntaxhighlight>
{{out}}
<pre>
0: 0
1: 1
2: 10
3: 100
4: 101
5: 1000
6: 1001
7: 1010
8: 10000
9: 10001
10: 10010
11: 10100
12: 10101
13: 100000
14: 100001
15: 100010
16: 100100
17: 100101
18: 101000
19: 101001
20: 101010
 
</pre>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let fib = Seq.unfold (fun (x, y) -> Some(x, (y, x + y))) (1,2)
 
let zeckendorf n =
Line 1,635 ⟶ 2,432:
|> List.rev
 
for i in 0 .. 20 do printfn "%2d: %8s" i (String.concat "" (zeckendorf i))</langsyntaxhighlight>
{{out}}
<pre style="height:5em"> 0: 0
Line 1,660 ⟶ 2,457:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel locals make math sequences ;
 
:: fib<= ( n -- seq )
Line 1,670 ⟶ 2,467:
[ dup s + n <= [ s + s! 49 ] [ drop 48 ] if ] "" map-as ;
21 <iota> [ dup zeck "%2d: %6s\n" printf ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 1,697 ⟶ 2,494:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">: fib<= ( n -- n )
>r 0 1 BEGIN dup r@ <= WHILE tuck + REPEAT drop rdrop ;
 
Line 1,711 ⟶ 2,508:
21 0 DO
cr i 2 .r tab i z.
LOOP ;</langsyntaxhighlight>
{{out}}
<pre>
Line 1,749 ⟶ 2,546:
By declaring the horde of simple names to have the PRIVATE attribute, they will not litter the name space of routines invoking the module, but alas, they will still occupy their own storage space. Another possibility would be to use the EQUIVALENCE statement to have them placed within array <code>F1B</code>, but alas, as noted in [[15_Puzzle_Game#Fortran]], the compiler will not countenance PARAMETER statements for names engaged in such misbehviour. A pity.
 
Still another possibility would be to take advantage of the formula for calculating the values of the Fibonacci series directly (with careful attention to the offsets needed for the Fib1nacci sequence), but this formula is rather intimidating: <langsyntaxhighlight Fortranlang="fortran">F(N) = ((1 + SQRT(5))**N - (1 - SQRT(5))**N)/(SQRT(5)*2**N)</langsyntaxhighlight> It can easily be coded as a Fortran function (and would have to be double precision because 32-bit floating-point arithmetic is not accurate enough for integer constants approaching 32 bits), but alas, the compiler does not allow itself to take the risk of invoking a user-written function in a PARAMETER statement, even if the compiler had itself compiled it. For, [https://en.wikipedia.org/wiki/Entscheidungsproblem who knows] what it might do?
 
 
Line 1,758 ⟶ 2,555:
The source uses F90 for its MODULE facility, in particular having array <code>F1B</code> available without having to mess about with additional parameters or COMMON statements. This also enables the specification of arrays with a lower bound other than one, which makes it easy to define the digit arrays to have a current length, stored in element zero. This sort of "string" facility is often restricted only to strings of characters, but the notion "string of <type>" is often useful. If in routines declared within a MODULE the size of an array parameter is declared via <code>:</code> there are secret additional parameters defining its size, accessible via special functions such as <code>UBOUND</code> so there is no need for an explicit parameter doing so as would be the case prior to F90. With F90 it is also possible to define a compound data type for the digit sequence, but a simple array seems more flexible.
 
The pleasing name, "MODULE ZECKENDORF ARITHMETIC" causes some odd behaviour, even though Fortran source normally involves spaces having no significance outside text literals.<langsyntaxhighlight Fortranlang="fortran"> MODULE ZECKENDORF ARITHMETIC !Using the Fibonacci series, rather than powers of some base.
INTEGER ZLAST !The standard 32-bit two's complement integers
PARAMETER (ZLAST = 45) !only get so far, just as there's a limit to the highest power.
Line 1,843 ⟶ 2,640:
END DO !On to the next.
 
END</langsyntaxhighlight>
 
Output: shown aligned right for a more regular table. Producing leading spaces or digits required a conversion from a numerical digit to a character digit, so that all the output could use the <code>A</code> format code.
Line 1,873 ⟶ 2,670:
20 101010
</pre>
 
=={{header|FreeBASIC}}==
<lang freebasic>' version 17-10-2016
' compile with: fbc -s console
 
#Define max 92 ' max for Fibonacci number
 
Dim Shared As ULongInt fib(max)
 
fib(0) = 1
fib(1) = 1
 
For x As Integer = 2 To max
fib(x) = fib(x-1) + fib(x-2)
Next
 
Function num2zeck(n As Integer) As String
 
If n < 0 Then
Print "Error: no negative numbers allowed"
Beep : Sleep 5000,1 : End
End If
 
If n < 2 Then Return Str(n)
 
Dim As String zeckendorf
For x As Integer = max To 1 Step -1
If fib(x) <= n Then
zeckendorf = zeckendorf + "1"
n = n - fib(x)
Else
zeckendorf = zeckendorf + "0"
End If
Next
 
return LTrim(zeckendorf, "0") ' get rid of leading zeroes
End Function
 
' ------=< MAIN >=------
 
Dim As Integer x, e
Dim As String zeckendorf
Print "number zeckendorf"
 
For x = 0 To 200000
zeckendorf = num2zeck(x)
If x <= 20 Then Print x, zeckendorf
' check for two consecutive Fibonacci numbers
If InStr(zeckendorf, "11") <> 0 Then
Print " Error: two consecutive Fibonacci numbers "; x, zeckendorf
e = e +1
End If
Next
 
Print
If e = 0 Then
Print " No Zeckendorf numbers with two consecutive Fibonacci numbers found"
Else
Print e; " error(s) found"
End If
 
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</lang>
{{out}}
<pre>number zeckendorf
0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010
 
No Zeckendorf numbers with two consecutive Fibonacci numbers found</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 2,000 ⟶ 2,702:
}
return
}</langsyntaxhighlight>
{{out}}
<pre> 0 0
Line 2,026 ⟶ 2,728:
=={{header|Haskell}}==
Using "no consecutive 1s" rule:
<langsyntaxhighlight lang="haskell">import Data.Bits
import Numeric
 
Line 2,034 ⟶ 2,736:
b x = showIntAtBase 2 ("01"!!) x ""
 
main = mapM_ putStrLn $ take 21 zeckendorf</langsyntaxhighlight>
which is the same as
<langsyntaxhighlight lang="haskell">zeckendorf = "0":"1":[s++[d] | s <- tail zeckendorf, d <- "01",
last s /= '1' || d /= '1']
 
main = mapM putStrLn $ take 21 zeckendorf</langsyntaxhighlight>
or a different way to generate the sequence:
<langsyntaxhighlight lang="haskell">import Numeric
 
fib = 1 : 1 : zipWith (+) fib (tail fib)
Line 2,051 ⟶ 2,753:
b x = showIntAtBase 2 ("01"!!) x ""
 
main = mapM_ putStrLn $ take 21 zeckendorf</langsyntaxhighlight>
 
Creating a string for an individual number:
<langsyntaxhighlight lang="haskell">import Data.List (mapAccumL)
 
fib :: [Int]
Line 2,068 ⟶ 2,770:
 
main :: IO ()
main = (putStrLn . unlines) $ zeckendorf <$> [0 .. 20]</langsyntaxhighlight>
{{out}}
<pre>
Line 2,096 ⟶ 2,798:
=={{header|J}}==
Please enjoy our [http://www.jsoftware.com/jwiki/Essays/Fibonacci%20Sums Zeckendorf essay].
<syntaxhighlight lang="j">
<lang J>
fib=: 3 : 0 " 0
mp=. +/ .*
Line 2,126 ⟶ 2,828:
│100001│100010│100100│100101│101000│101001│101010│
└──────┴──────┴──────┴──────┴──────┴──────┴──────┘
</syntaxhighlight>
</lang>
 
Explanation:
Line 2,142 ⟶ 2,844:
'''Code:'''
 
<langsyntaxhighlight lang="java">import java.util.*;
 
class Zeckendorf
Line 2,174 ⟶ 2,876:
System.out.println("Z(" + i + ")=" + getZeckendorf(i));
}
}</langsyntaxhighlight>
 
'''Output:'''
Line 2,203 ⟶ 2,905:
 
'''Code:'''
<langsyntaxhighlight lang="java">import java.util.ArrayList;
import java.util.List;
 
Line 2,243 ⟶ 2,945:
}
}
}</langsyntaxhighlight>
 
'''Output:'''
Line 2,272 ⟶ 2,974:
===ES6===
{{Trans|Haskell}} ('''mapAccumuL''' example)
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,406 ⟶ 3,108:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>0
Line 2,432 ⟶ 3,134:
=={{header|jq}}==
{{works with|jq|1.5}}
<langsyntaxhighlight lang="jq">def zeckendorf:
def fibs($n):
# input: [f(i-2), f(i-1)]
Line 2,456 ⟶ 3,158:
| [., ($f|length)-1]
| loop($f)
| join("") ;</langsyntaxhighlight>
 
'''Example:'''
<langsyntaxhighlight lang="jq">range(0;21) | "\(.): \(zeckendorf)"</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang="sh">$ jq -n -r -f zeckendorf.jq
0: 0
1: 1
Line 2,482 ⟶ 3,184:
18: 101000
19: 101001
20: 101010</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang="julia">function zeck(n)
n <= 0 && return 0
fib = [2,1]; while fib[1] < n unshift!(fib,sum(fib[1:2])) end
dig = Int[]; for f in fib f <= n ? (push!(dig,1); n = n-f;) : push!(dig,0) end
return dig[1] == 0 ? dig[2:end] : dig
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,521 ⟶ 3,223:
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
:listos
Line 2,547 ⟶ 3,249:
20 Zeckendorf
 
nl "End " input</langsyntaxhighlight>
{{out}}
<pre>0: 0
Line 2,574 ⟶ 3,276:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
const val LIMIT = 46 // to stay within range of signed 32 bit integer
Line 2,612 ⟶ 3,314:
println(" n z")
for (i in 0..20) println("${"%2d".format(i)} : ${zeckendorf(i)}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,639 ⟶ 3,341:
20 : 101010
</pre>
 
=={{header|Liberty BASIC}}==
''CBTJD'': 2020/03/09
<lang vb>samples = 20
call zecklist samples
 
print "Decimal","Zeckendorf"
for n = 0 to samples
print n, zecklist$(n)
next n
 
Sub zecklist inDEC
dim zecklist$(inDEC)
do
bin$ = dec2bin$(count)
if instr(bin$,"11") = 0 then
zecklist$(found) = bin$
found = found + 1
end if
count = count+1
loop until found = inDEC + 1
End sub
 
function dec2bin$(inDEC)
do
bin$ = str$(inDEC mod 2) + bin$
inDEC = int(inDEC/2)
loop until inDEC = 0
dec2bin$ = bin$
end function</lang>
 
=={{header|Lingo}}==
{{trans|Lua}}
<langsyntaxhighlight Lingolang="lingo">-- Return the distinct Fibonacci numbers not greater than 'n'
on fibsUpTo (n)
fibList = []
Line 2,700 ⟶ 3,372:
if zeck = "" then return "0"
return zeck
end</langsyntaxhighlight>
 
<langsyntaxhighlight Lingolang="lingo">repeat with n = 0 to 20
put n & ": " & zeckendorf(n)
end repeat</langsyntaxhighlight>
 
{{out}}
Line 2,735 ⟶ 3,407:
 
Most online LMC simulators seem to have very limited space for output. Peter Higginson's allows only sixteen lines of four characters each. Previous output scrolls off and is lost. The output from this program had to be captured by repeatedly pausing the program and using copy-and-paste.
<syntaxhighlight lang="little man computer">
<lang Little Man Computer>
// Little Man Computer, for Rosetta Code.
// Writes Zeckendorf representations of numbers 0..20.
Line 2,815 ⟶ 3,487:
ascii_1 DAT 49
// end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,844 ⟶ 3,516:
 
=={{header|Logo}}==
<langsyntaxhighlight lang="logo">; return the (N+1)th Fibonacci number (1,2,3,5,8,13,...)
to fib m
local "n
Line 2,894 ⟶ 3,566:
]
print []
bye</langsyntaxhighlight>
{{Out}}
<pre>0 1 10 100 101 1000 1001 1010 10000 10001 10010 10100 10101 100000 100001 100010 100100 100101 101000 101001 101010</pre>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- Return the distinct Fibonacci numbers not greater than 'n'
function fibsUpTo (n)
local fibList, last, current, nxt = {}, 1, 1
Line 2,931 ⟶ 3,603:
for n = 0, 20 do
print(" " .. n, "| " .. zeckendorf(n))
end</langsyntaxhighlight>
{{out}}
<pre> n | Zeckendorf(n)
Line 2,958 ⟶ 3,630:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">
<lang Mathematica>zeckendorf[0] = 0;
ZeckendorfRepresentation[0] = 0;
zeckendorf[n_Integer] :=
 
10^(# - 1) + zeckendorf[n - Fibonacci[# + 1]] &@
ZeckendorfRepresentation[n_Integer?Positive]:=
LengthWhile[
NumberDecompose[n, Reverse@Fibonacci@Range[2,1000]] // FromDigits
Fibonacci /@
 
Range[2, Ceiling@Log[GoldenRatio, n Sqrt@5]], # <= n &];
zeckendorfZeckendorfRepresentation /@ Range[0, 20]</langsyntaxhighlight>
{{Out}}
<pre>{0, 1, 10, 100, 101, 1000, 1001, 1010, 10000, 10001, 10010, 10100,
10101, 100000, 100001, 100010, 100100, 100101, 101000, 101001, 101010}</pre>
 
=={{header|MATLAB}}==
{{trans|Julia}}
<syntaxhighlight lang="MATLAB">
clear all; close all; clc;
 
% Print the sequence for numbers from 0 to 20
for x = 0:20
zeckString = arrayfun(@num2str, zeck(x), 'UniformOutput', false);
zeckString = strjoin(zeckString, '');
fprintf("%d : %s\n", x, zeckString);
end
 
function dig = zeck(n)
if n <= 0
dig = 0;
return;
end
fib = [1, 2];
while fib(end) < n
fib(end + 1) = sum(fib(end-1:end));
end
fib = fliplr(fib); % Reverse the order of Fibonacci numbers
dig = [];
for i = 1:length(fib)
if fib(i) <= n
dig(end + 1) = 1;
n = n - fib(i);
else
dig(end + 1) = 0;
end
end
if dig(1) == 0
dig = dig(2:end);
end
end
</syntaxhighlight>
{{out}}
<pre>
0 : 0
1 : 1
2 : 10
3 : 100
4 : 101
5 : 1000
6 : 1001
7 : 1010
8 : 10000
9 : 10001
10 : 10010
11 : 10100
12 : 10101
13 : 100000
14 : 100001
15 : 100010
16 : 100100
17 : 100101
18 : 101000
19 : 101001
20 : 101010
 
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
fibonacci = function(val)
if val < 1 then return []
fib = []
a = 1; b = 2
while a <= val
fib.insert(0, a)
next = a + b
a = b
b = next
end while
return fib
end function
 
zeckendorf = function(val)
seq = fibonacci(val)
s = ""
for i in seq
onOff = val >= i and (s == "" or s[-1] == "0")
s += str(onOff)
val -= (i*onOff)
end for
return s
end function
 
for i in range(1, 20)
print [i, zeckendorf(i)]
end for
</syntaxhighlight>
{{out}}
<pre>[1, "1"]
[2, "10"]
[3, "100"]
[4, "101"]
[5, "1000"]
[6, "1001"]
[7, "1010"]
[8, "10000"]
[9, "10001"]
[10, "10010"]
[11, "10100"]
[12, "10101"]
[13, "100000"]
[14, "100001"]
[15, "100010"]
[16, "100100"]
[17, "100101"]
[18, "101000"]
[19, "101001"]
[20, "101010"]
</pre>
 
=={{header|Nim}}==
{{trans|Python}}
<langsyntaxhighlight lang="nim">import strformat, strutils
proc z(n: Natural): string =
Line 2,988 ⟶ 3,778:
for i in 0 .. 20:
echo &"{i:>3} {z(i):>8}"</langsyntaxhighlight>
 
{{out}}
Line 3,012 ⟶ 3,802:
19 101001
20 101010</pre>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">let zeck n =
let rec enc x s = function
| h :: t when h <= x -> enc (x - h) (s ^ "1") t
| _ :: t -> enc x (s ^ "0") t
| _ -> s
and fib b a l =
if b > n
then enc (n - a) "1" l
else fib (b + a) b (a :: l)
in
if n = 0 then "0" else fib 2 1 []
 
let () =
for i = 0 to 20 do Printf.printf "%3u:%8s\n" i (zeck i) done</syntaxhighlight>
{{out}}
<pre>
0: 0
1: 1
2: 10
3: 100
4: 101
5: 1000
6: 1001
7: 1010
8: 10000
9: 10001
10: 10010
11: 10100
12: 10101
13: 100000
14: 100001
15: 100010
16: 100100
17: 100101
18: 101000
19: 101001
20: 101010
</pre>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">Z(n)=if(!n,print1(0));my(k=2);while(fibonacci(k)<=n,k++); forstep(i=k-1,2,-1,print1(if(fibonacci(i)<=n,n-=fibonacci(i);1,0)));print
for(n=0,20,Z(n))</langsyntaxhighlight>
<pre>0
1
Line 3,041 ⟶ 3,871:
A console application in Free Pascal, created with the Lazarus IDE.
Though written independently of the Tcl solution, it uses essentially the same algorithm.
<langsyntaxhighlight lang="pascal">
program ZeckendorfRep_RC;
 
Line 3,093 ⟶ 3,923:
WriteLn( SysUtils.Format( '%2d: %s', [C, ZeckRep(C)]));
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,120 ⟶ 3,950:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my @fib;
 
sub fib {
Line 3,143 ⟶ 3,973:
 
printf "%4d: %8s\n", $_, zeckendorf($_) for 0..20;
</syntaxhighlight>
</lang>
{{out}}
<pre> 0: 0
Line 3,169 ⟶ 3,999:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">zeckendorf</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">r</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span>
Line 3,187 ⟶ 4,017:
<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;">"%2d: %7b\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">i</span><span style="color: #0000FF;">,</span><span style="color: #000000;">zeckendorf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 3,214 ⟶ 4,044:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">def Zeckendorf /# n -- #/
0 var i 0 var c 1 1 2 tolist var pattern
true
Line 3,234 ⟶ 4,064:
enddef
 
20 Zeckendorf</langsyntaxhighlight>
 
=={{header|PHP}}==
<syntaxhighlight lang="php">
<lang PHP>
<?php
$m = 20;
Line 3,260 ⟶ 4,090:
}
?>
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,284 ⟶ 4,114:
1: 1
</pre>
 
=={{header|Picat}}==
===Constraint model===
<syntaxhighlight lang="picat">go =>
foreach(Num in 0..20)
zeckendorf_cp(Num,X,F),
Nums = [F[I] : I in 1..X.length, X[I] = 1],
printf("%2d %6s %w\n",Num, rep(X),Nums),
end,
nl.
 
zeckendorf_cp(Num, X,F) =>
F = get_fibs(Num).reverse(),
N = F.length,
X = new_list(N),
X :: 0..1,
 
% From the task description:
% """
% For a true Zeckendorf number there is the added restriction that
% no two consecutive Fibonacci numbers can be used which leads to
% the former unique solution.
% """
foreach(I in 2..N)
X[I-1] #= 1 #=> X[I] #= 0
end,
 
scalar_product(F,X,Num),
solve([ff,split],X).
 
%
% Fibonacci numbers
%
table
fib(0) = 0.
fib(1) = 1.
fib(N) = fib(N-1) + fib(N-2).
 
%
% Remove leading 0's and stringify it
%
rep(X) = Str =>
First = 1,
if X.length > 1, X[First] = 0 then
while (X[First] == 0)
First := First + 1
end
end,
Str = [X[I].to_string() : I in First..X.length].join('').
 
%
% Return a list of fibs <= N
%
get_fibs(N) = Fibs =>
I = 2,
Fib = fib(I),
Fibs1 = [Fib],
while (Fib < N)
I := I + 1,
Fib := fib(I),
Fibs1 := Fibs1 ++ [Fib]
end,
Fibs = Fibs1.</syntaxhighlight>
 
{{out}}
<pre> 0 0 []
1 1 [1]
2 10 [2]
3 100 [3]
4 101 [3,1]
5 1000 [5]
6 1001 [5,1]
7 1010 [5,2]
8 10000 [8]
9 10001 [8,1]
10 10010 [8,2]
11 10100 [8,3]
12 10101 [8,3,1]
13 100000 [13]
14 100001 [13,1]
15 100010 [13,2]
16 100100 [13,3]
17 100101 [13,3,1]
18 101000 [13,5]
19 101001 [13,5,1]
20 101010 [13,5,2]</pre>
 
===An iterative approach===
<syntaxhighlight lang="picat">go2 =>
foreach(Num in 0..20)
zeckendorf2(Num,X,F),
Nums = [F[I] : I in 1..X.length, X[I]= 1],
printf("%2d %6s %w\n",Num, rep(X),Nums)
end,
nl.
 
zeckendorf2(0, [0],[0]).
zeckendorf2(Num, X,F) :-
Fibs = get_fibs(Num),
I = Fibs.length,
N = Num,
X1 = [],
while (I > 0)
Fib := Fibs[I],
X1 := X1 ++ [cond(Fib > N,0,1)],
if Fib <= N then
N := N - Fib
end,
I := I - 1
end,
X = X1,
F = Fibs.reverse().</syntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de fib (N)
(let Fibs (1 1)
(while (>= N (+ (car Fibs) (cadr Fibs)))
Line 3,316 ⟶ 4,259:
(glue " + " (zecken2 N)) ) )
 
(bye)</langsyntaxhighlight>
{{out}}
<pre>
Line 3,344 ⟶ 4,287:
This code needs an etex engine.
 
<langsyntaxhighlight lang="tex">\def\genfibolist#1{% #creates the fibo list which sum>=#1
\let\fibolist\empty\def\targetsum{#1}\def\fibosum{0}%
\genfibolistaux1,1\relax
Line 3,380 ⟶ 4,323:
}
\listzeckendorf{20}% any integer accepted
\bye</langsyntaxhighlight>
 
pdf output looks like:
Line 3,408 ⟶ 4,351:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-ZeckendorfNumber ( $N )
{
Line 3,435 ⟶ 4,378:
return $ZeckendorfNumber
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
# Get Zeckendorf numbers through 20, convert to binary for display
0..20 | ForEach { [convert]::ToString( ( Get-ZeckendorfNumber $_ ), 2 ) }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,464 ⟶ 4,407:
101010
</pre>
 
=={{header|PureBasic}}==
<lang PureBasic>Procedure.s zeck(n.i)
Dim f.i(1) : Define i.i=1, o$
f(0)=1 : f(1)=1
While f(i)<n
i+1 : ReDim f(ArraySize(f())+1) : f(i)=f(i-1)+f(i-2)
Wend
For i=i To 1 Step -1
If n>=f(i) : o$+"1" : n-f(i) : Else : o$+"0" : EndIf
Next
If Len(o$)>1 : o$=LTrim(o$,"0") : EndIf
ProcedureReturn o$
EndProcedure
 
Define n.i, t$
OpenConsole("Zeckendorf number representation")
PrintN(~"\tNr.\tZeckendorf")
For n=0 To 20
t$=zeck(n)
If FindString(t$,"11")
PrintN("Error: n= "+Str(n)+~"\tZeckendorf= "+t$)
Break
Else
PrintN(~"\t"+RSet(Str(n),3," ")+~"\t"+RSet(t$,7," "))
EndIf
Next
Input()</lang>
{{out}}
<pre> Nr. Zeckendorf
0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def fib():
memo = [1, 2]
while True:
Line 3,550 ⟶ 4,442:
print('Fibonacci digit multipliers: %r' % sequence_down_from_n(n, fib))
for i in range(n + 1):
print('%3i: %8s' % (i, ''.join(str(d) for d in zeckendorf(i))))</langsyntaxhighlight>
 
{{out}}
Line 3,577 ⟶ 4,469:
 
===Shorter version===
<langsyntaxhighlight lang="python">n = 20
def z(n):
if n == 0 : return [0]
Line 3,591 ⟶ 4,483:
 
for i in range(n + 1):
print('%3i: %8s' % (i, ''.join(str(d) for d in z(i))))</langsyntaxhighlight>
{{out}}
Line 3,618 ⟶ 4,510:
=={{header|Quackery}}==
 
Converting non-negative integers to and from Zeckendorf representation.
<lang Quackery>[ ' [ 2 1 ]
[ dup 0 peek
over 1 peek +
rot 2dup < while
unrot
swap join again ]
2drop ] is obif ( n --> [ )
 
<syntaxhighlight lang="quackery"> [ 2 base put
[ 20 obif ] constant is fibnums ( --> [ )
echo
base release ] is binecho ( n --> )
 
[ 0 swap ' [ 2 1 ]
[ 2dup 0 peek < iff
fibnums witheach
[ rot 1 << unrot[ behead drop ]
2dup < not iffdone
dup 0 [ -peek
dip [over 1 | ] ]peek
else+ dropswap ]join again ]
witheach
drop ] is zeckendorficate ( n --> n )
[ rot 1 << unrot
2dup < iff drop
else
[ -
dip
[ 1 | ] ] ]
drop ] is n->z ( n --> z )
 
[ 20 basetemp put
1 1 rot
echo
[ dup while
base release ] is binecho ( n --> )
dup 1 & if
[ over
temp tally ]
1 >>
dip [ tuck + ]
again ]
2drop drop
temp take ] is z->n ( z --> n )
 
21 times
[ i^ dup echo
dup 10 < ifsay sp" -> "
echo sp n->z dup binecho
say " -> "
zeckendorficate binecho
z->n echo cr ]</langsyntaxhighlight>
 
{{Out}}
 
<pre>1 -> 1 -> 1
2 -> 10 -> 2
3 -> 100 -> 3
4 -> 101 -> 4
5 -> 1000 -> 5
6 -> 1001 -> 6
7 -> 1010 -> 7
8 -> 10000 -> 8
9 -> 10001 -> 9
10 -> 10010 -> 10
11 -> 10100 -> 11
12 -> 10101 -> 12
13 -> 100000 -> 13
14 -> 100001 -> 14
15 -> 100010 -> 15
16 -> 100100 -> 16
17 -> 100101 -> 17
18 -> 101000 -> 18
19 -> 101001 -> 19
20 -> 101010 -> 20</pre>
 
===Bit Twiddling===
 
The task notes:
::The Zeckendorf form can be iterated by some bit twiddling rather than calculating each value separately but leave that to another separate task.
 
That other separate task is [[Zeckendorf arithmetic]], specifically the ''optional'' increment function which, at the time of writing, has not been addressed in any of the languages present on the page. So here it is.
 
<lang Quackery> [ dup 1 >> ~ tuck - & ] is zinc ( n --> n )
 
0 21 times
[ i^ dup
10 < if sp
echo sp
dup binecho cr
zinc ]
drop</lang>
 
{{out}}
 
<pre> 0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010</pre>
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">zeckendorf <- function(number) {
 
# Get an upper limit on Fibonacci numbers needed to cover number
Line 3,756 ⟶ 4,618:
}
 
print(unlist(lapply(0:20, zeckendorf)))</langsyntaxhighlight>
 
This is definitely not the shortest way to implement the Zeckendorf numbers but focus was on the functional aspect of R, so no loops and (almost) no assignments.
Line 3,766 ⟶ 4,628:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket (require math)
 
Line 3,784 ⟶ 4,646:
(for/list ([n 21])
(list n (zechendorf n)))
</syntaxhighlight>
</lang>
Output:
<langsyntaxhighlight lang="racket">
'((0 ())
(1 (1))
Line 3,808 ⟶ 4,670:
(19 (1 0 1 0 0 1))
(20 (1 0 1 0 1 0)))
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2015.12}}
<syntaxhighlight lang="raku" perl6line>printf "%2d: %8s\n", $_, zeckendorf($_) for 0 .. 20;
 
multi zeckendorf(0) { '0' }
Line 3,822 ⟶ 4,684:
+$digit;
}, reverse FIBS ...^ * > $n;
}</langsyntaxhighlight>
{{out}}
<pre> 0: 0
Line 3,848 ⟶ 4,710:
=={{header|REXX}}==
===specific to 20===
<langsyntaxhighlight lang="rexx">
/* REXX ***************************************************************
* 11.10.2012 Walter Pachl
Line 3,870 ⟶ 4,732:
If r='' Then r='0' /* take care of 0 */
Say right(n,2)': 'right(r,6) /* show result */
End</langsyntaxhighlight>
Output:
<pre>
Line 3,898 ⟶ 4,760:
This generalized REXX version will work for any Zeckendorf number (up to 100,000 decimal digits).
<br><br>A list of Fibonacci numbers (in ascending order) is generated large enough to handle the &nbsp; '''N<sup>th</sup>''' &nbsp; Zeckendorf number.
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the first N Zeckendorf numbers. */
numeric digits 100000 /*just in case user gets real ka─razy. */
parse arg N . /*let the user specify the upper limit.*/
Line 3,915 ⟶ 4,777:
end /*k*/
say ' Zeckendorf' right(j, w) "=" right(z+0, 30) /*display a number.*/
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 3,946 ⟶ 4,808:
 
There isn't any need to generate a Fibonacci series with this method. &nbsp; This method is extremely fast.
<langsyntaxhighlight REXXlang="rexx">/*REXX program calculates and displays the first N Zeckendorf numbers. */
numeric digits 100000 /*just in case user gets real ka─razy. */
parse arg N . /*let the user specify the upper limit.*/
Line 3,955 ⟶ 4,817:
say ' Zeckendorf' right(z, w) "=" right(_+0, 30) /*display a number.*/
z= z + 1 /*bump the Zeckendorf number counter.*/
end /*j*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the previous (generalized) version.}} <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Zeckendorf number representation
 
Line 3,987 ⟶ 4,849:
end
return o
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,012 ⟶ 4,874:
20 101010
</pre>
 
=={{header|RPL}}==
The two-step algorithm - first generating a series a Fibonacci numbers, then encrypting - is an opportunity to showcase the structured programming that RPL allows, with two separate structures having each their own local variables to avoid too complex stack handlings.
{{works with|Halcyon Calc|4.2.7}}
≪ → m
≪ { 1 } 1 1
DO
ROT OVER SWAP +
ROT ROT SWAP OVER +
UNTIL DUP m > END
DROP2 m SWAP
→ fibs
≪ "" SWAP
1 fibs SIZE 1 - FOR j
fibs j GET
IF DUP2 ≥ THEN - SWAP "1" ELSE DROP SWAP "0" END
+ SWAP
NEXT
DROP
'→ZKDF' STO
≪ { } 1 20 FOR j j →ZKDF + NEXT ≫ EVAL
{{out}}
<pre>
{ "1" "10" "100" "101" "1000" "1001" "1010" "10000" "10001" "10010" "10100" "10101" "100000" "100001" "100010" "100100" "100101" "101000" "101001" "101010" }
</pre>
 
 
=={{header|Ruby}}==
Featuring a method doubling as an enumerator.
<langsyntaxhighlight lang="ruby">def zeckendorf
return to_enum(__method__) unless block_given?
x = 0
Line 4,025 ⟶ 4,917:
end
 
zeckendorf.take(21).each_with_index{|x,i| puts "%3d: %8s"% [i, x]}</langsyntaxhighlight>
 
{{trans|Python}}
<langsyntaxhighlight lang="ruby">def zeckendorf(n)
return 0 if n.zero?
fib = [1,2]
Line 4,045 ⟶ 4,937:
for i in 0..20
puts '%3d: %8d' % [i, zeckendorf(i)]
end</langsyntaxhighlight>
As oneliner.
{{trans|Crystal}}
<langsyntaxhighlight lang="ruby">def zeckendorf(n)
0.step.lazy.map { |x| x.to_s(2) }.reject { |z| z.include?("11") }.first(n)
end
 
zeckendorf(21).each_with_index{ |x,i| puts "%3d: %8s"% [i, x] }
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,078 ⟶ 4,970:
19: 101001
20: 101010</pre>
 
=={{header|Rust}}==
{{trans|C#}}
<syntaxhighlight lang="Rust">
use std::collections::VecDeque;
 
fn fibonacci(n: u32) -> u32 {
match n {
0 => 0,
1 => 1,
_ => fibonacci(n - 1) + fibonacci(n - 2),
}
}
 
fn zeckendorf(num: u32) -> String {
let mut fibonacci_numbers = VecDeque::new();
let mut fib_position = 2;
let mut current_fibonacci_num = fibonacci(fib_position);
 
while current_fibonacci_num <= num {
fibonacci_numbers.push_front(current_fibonacci_num);
fib_position += 1;
current_fibonacci_num = fibonacci(fib_position);
}
 
let mut temp = num;
let mut output = String::new();
 
for item in fibonacci_numbers {
if item <= temp {
output.push('1');
temp -= item;
} else {
output.push('0');
}
}
 
output
}
 
fn main() {
for i in 1..=20 {
let zeckendorf_representation = zeckendorf(i);
println!("{} : {}", i, zeckendorf_representation);
}
}
</syntaxhighlight>
{{out}}
<pre>
1 : 1
2 : 10
3 : 100
4 : 101
5 : 1000
6 : 1001
7 : 1010
8 : 10000
9 : 10001
10 : 10010
11 : 10100
12 : 10101
13 : 100000
14 : 100001
15 : 100010
16 : 100100
17 : 100101
18 : 101000
19 : 101001
20 : 101010
 
</pre>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def zNum( n:BigInt ) : String = {
 
if( n == 0 ) return "0" // Short-circuit this and return zero if we were given zero
Line 4,109 ⟶ 5,072:
// A little test...
(0 to 20) foreach( i => print( zNum(i) + "\n" ) )
</syntaxhighlight>
</lang>
{{out}}
<pre>0
Line 4,136 ⟶ 5,099:
=={{header|Scheme}}==
{{trans|Java}}
<langsyntaxhighlight lang="scheme">(import (rnrs))
 
(define (getFibList maxNum n1 n2 fibs)
Line 4,166 ⟶ 5,129:
(newline)
(loop (+ i 1))))
</syntaxhighlight>
</lang>
{{out}}
<pre>Z(0): 0
Line 4,192 ⟶ 5,155:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func fib(n) is cached {
n < 2 ? 1
 : (fib(n-1) + fib(n-2))
Line 4,212 ⟶ 5,175:
for n (0..20) {
printf("%4d: %8s\n", n, zeckendorf(n))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 4,240 ⟶ 5,203:
=={{header|Simula}}==
{{trans|Sinclair ZX81 BASIC}}
<langsyntaxhighlight lang="simula">BEGIN
INTEGER N, F0, F1, F2, D;
N := 20;
Line 4,276 ⟶ 5,239:
END; ! 230 next i ;
END;
END</langsyntaxhighlight>
{{out}}
<pre>0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010</pre>
 
=={{header|Sinclair ZX81 BASIC}}==
Works on the 1k RAM model, albeit without much room for manoeuvre. (You'd like the Zeckendorf numbers further over towards the right-hand side of the screen? Sorry, can't spare the video RAM.) If you have 2k or more, you can replace the constant 6 with some higher value wherever it occurs in the program and enable yourself to represent bigger numbers in Zeckendorf form.
<lang basic> 10 DIM F(6)
20 LET F(1)=1
30 LET F(2)=2
40 FOR I=3 TO 6
50 LET F(I)=F(I-2)+F(I-1)
60 NEXT I
70 FOR I=0 TO 20
80 LET Z$=""
90 LET S$=" "
100 LET Z=I
110 FOR J=6 TO 1 STEP -1
120 IF J=1 THEN LET S$="0"
130 IF Z<F(J) THEN GOTO 180
140 LET Z$=Z$+"1"
150 LET Z=Z-F(J)
160 LET S$="0"
170 GOTO 190
180 LET Z$=Z$+S$
190 NEXT J
200 PRINT I;" ";
210 IF I<10 THEN PRINT " ";
220 PRINT Z$
230 NEXT I</lang>
{{out}}
<pre>0 0
Line 4,349 ⟶ 5,264:
 
=={{header|Standard ML}}==
<syntaxhighlight lang="standard ml">
<lang Standard ML>
val zeckList = fn from => fn to =>
 
Line 4,383 ⟶ 5,298:
Zeck ( from + (fromInt i) )))
end;
</syntaxhighlight>
</lang>
output
<syntaxhighlight lang="standard ml">
<lang Standard ML>
List.app ( fn e => print ( (IntInf.toString (#1 e)) ^" : "^ (IntInf.toString (#2 e)) ^ "\n" )) (zeckList 1 21) ;
1 : 1
Line 4,411 ⟶ 5,326:
val it = [(568533155, 100100100101001001001000000100100010100101)]:
: (IntInf.int * IntInf.int) list
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
# Generates the Fibonacci sequence (starting at 1) up to the largest item that
Line 4,442 ⟶ 5,357:
}
return [join $zs ""]
}</langsyntaxhighlight>
Demonstration
<langsyntaxhighlight lang="tcl">for {set i 0} {$i <= 20} {incr i} {
puts [format "%2d:%9s" $i [zeckendorf $i]]
}</langsyntaxhighlight>
{{out}}
<pre> 0: 0
Line 4,470 ⟶ 5,385:
20: 101010</pre>
 
=={{header|uBasic/4tHUNIX Shell}}==
<syntaxhighlight lang="sh">set -- 2 1
<lang>For x = 0 to 20 ' Print Zeckendorf numbers 0 - 20
x=-1
Print x,
while [ $((x += 1)) -le 20 ]
Push x : Gosub _Zeckendorf ' get Zeckendorf number repres.
do
Print ' terminate line
[ $x -gt $1 ] && set -- $(($2 + $1)) "$@"
Next
n=$x zeck=''
 
for fib
End
do
 
zeck=$zeck$((n >= fib && (n -= fib) + 1))
_Fibonacci
done
Push Tos() ' duplicate TOS()
echo "$x: ${zeck#0}"
@(0) = 0 ' This function returns the
done</syntaxhighlight>
@(1) = 1 ' Fibonacci number which is smaller
{{out}}
' or equal to TOS()
<pre>0: 0
Do While @(1) < Tos() + 1
Push (@(1))
@(1) = @(0) + @(1) ' get next Fibonacci number
@(0) = Pop()
Loop ' loop if not exceeded TOS()
 
Gosub _Drop ' clear TOS()
Push @(0) ' return Fibonacci number
Return
 
_Zeckendorf
GoSub _Fibonacci ' This function breaks TOS() up
Print Tos(); ' into its Zeckendorf components
Push -(Pop() - Pop()) ' first digit is always there
' the remainder to resolve
Do While Tos() ' now go for the next digits
GoSub _Fibonacci
Print " + ";Tos(); ' print the next digit
Push -(Pop() - Pop())
Loop
 
Gosub _Drop ' clear TOS()
Return ' and return
 
_Drop
If Pop()%1 = 0 Then Return ' This function clears TOS()</lang>
Output:
<pre>0 0
1 1
2 2
3 3
4 3 + 1
5 5
6 5 + 1
7 5 + 2
8 8
9 8 + 1
10 8 + 2
11 8 + 3
12 8 + 3 + 1
13 13
14 13 + 1
15 13 + 2
16 13 + 3
17 13 + 3 + 1
18 13 + 5
19 13 + 5 + 1
20 13 + 5 + 2
 
0 OK, 0:901</pre>
 
=={{header|VBA}}==
{{trans|Phix}}<lang vb>Private Function zeckendorf(ByVal n As Integer) As Integer
Dim r As Integer: r = 0
Dim c As Integer
Dim fib As New Collection
fib.Add 1
fib.Add 1
Do While fib(fib.Count) < n
fib.Add fib(fib.Count - 1) + fib(fib.Count)
Loop
For i = fib.Count To 2 Step -1
c = n >= fib(i)
r = r + r - c
n = n + c * fib(i)
Next i
zeckendorf = r
End Function
Public Sub main()
Dim i As Integer
For i = 0 To 20
Debug.Print Format(i, "@@"); ":"; Format(WorksheetFunction.Dec2Bin(zeckendorf(i)), "@@@@@@@")
Next i
End Sub</lang>{{out}}
<pre> 0: 0
1: 1
2: 10
3: 100
4: 101
5: 1000
6: 1001
7: 1010
8: 10000
9: 10001
10: 10010
11: 10100
12: 10101
13: 100000
14: 100001
15: 100010
16: 100100
17: 100101
18: 101000
19: 101001
20: 101010</pre>
 
=={{header|VBScript}}==
<lang vb>
Function Zeckendorf(n)
num = n
Set fibonacci = CreateObject("System.Collections.Arraylist")
fibonacci.Add 1 : fibonacci.Add 2
i = 1
Do While fibonacci(i) < num
fibonacci.Add fibonacci(i) + fibonacci(i-1)
i = i + 1
Loop
tmp = ""
For j = fibonacci.Count-1 To 0 Step -1
If fibonacci(j) <= num And (tmp = "" Or Left(tmp,1) <> "1") Then
tmp = tmp & "1"
num = num - fibonacci(j)
Else
tmp = tmp & "0"
End If
Next
Zeckendorf = CLng(tmp)
End Function
 
'testing the function
For k = 0 To 20
WScript.StdOut.WriteLine k & ": " & Zeckendorf(k)
Next
</lang>
 
{{Out}}
<pre>
0: 0
1: 1
2: 10
Line 4,632 ⟶ 5,419:
18: 101000
19: 101001
20: 101010</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">fn main() {
for i := 0; i <= 20; i++ {
println("${i:2} ${zeckendorf(i):7b}")
}
}
fn zeckendorf(n int) int {
// initial arguments of fib0 = 1 and fib1 = 1 will produce
// the Fibonacci sequence {1, 2, 3,..} on the stack as successive
// values of fib1.
_, set := zr(1, 1, n, 0)
return set
}
fn zr(fib0 int, fib1 int, n int, bit u32) (int, int) {
mut set := 0
mut remaining := 0
if fib1 > n {
return n, 0
}
// recurse.
// construct sequence on the way in, construct ZR on the way out.
remaining, set = zr(fib1, fib0+fib1, n, bit+1)
if fib1 <= remaining {
set |= 1 << bit
remaining -= fib1
}
return remaining, set
}</syntaxhighlight>
 
{{out}}
<pre>
0 0
1 1
2 10
3 100
4 101
5 1000
6 1001
7 1010
8 10000
9 10001
10 10010
11 10100
12 10101
13 100000
14 100001
15 100010
16 100100
17 100101
18 101000
19 101001
20 101010
 
</pre>
 
Line 4,638 ⟶ 5,482:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "./fmt" for Fmt
 
var LIMIT = 46 // to stay within range of signed 32 bit integer
Line 4,676 ⟶ 5,520:
 
System.print(" n z")
for (i in 0..20) Fmt.print("$2d : $s", i, zeckendorf.call(i))</langsyntaxhighlight>
 
{{out}}
Line 4,705 ⟶ 5,549:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
 
proc Zeckendorf(N); \Display Zeckendorf number (N <= 20)
Line 4,724 ⟶ 5,568:
Zeckendorf(N); CrLf(0);
];
]</langsyntaxhighlight>
 
Output:
Line 4,750 ⟶ 5,594:
20: 101010
</pre>
 
=={{header|Yabasic}}==
<lang Yabasic>sub Zeckendorf(n)
local i, n$, c
do
n$ = bin$(i)
if not instr(n$,"11") then
print c,":\t",n$
if c = n break
c = c + 1
end if
i = i + 1
loop
end sub
 
Zeckendorf(20)
</lang>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl"> // return powers (0|1) of fib sequence (1,2,3,5,8...) that sum to n
fcn zeckendorf(n){ //-->String of 1s & 0s, no consecutive 1's
if(n<=0) return("0");
Line 4,778 ⟶ 5,604:
.pump(String,fcn(fib,rn){
if(fib>rn.value)"0" else { rn.set(rn.value-fib); "1" } }.fp1(Ref(n)))
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">[0..20].pump(Console.println,fcn(n){ "%2d: %8s".fmt(n,zeckendorf(n)) });</langsyntaxhighlight>
{{out}}
<pre style="height:7em">
Line 4,805 ⟶ 5,631:
</pre>
 
{{omit from|PL/0}}
{{omit from|Tiny BASIC}}
[[Category: Bitwise operations]]
9,476

edits