Jump to content

Zeckendorf number representation: Difference between revisions

→‎{{header|QuickBASIC}}: Added a solution.
(Dialects of BASIC moved to the BASIC section.)
(→‎{{header|QuickBASIC}}: Added a solution.)
Line 961:
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
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% = 0
WHILE FPos% >= 1
IF Rest% <= 0 THEN
Result$ = Result$ + "0"
ELSEIF SkipDigit% THEN ' we used the previous digit
SkipDigit% = 0
Result$ = Result$ + "0"
ELSEIF Rest% < Fib&(FPos%) THEN ' cannot use the digit at FPos%
SkipDigit% = 0
Result$ = Result$ + "0"
ELSE ' can use this digit
SkipDigit% = -1
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}}===
512

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.