Task 1: Zeckendorf Representation
"The Fibonacci Game: Finding the Unique Sum!"
This week's first task involves representing a positive integer as a sum of non-consecutive Fibonacci numbers. This is known as Zeckendorf's theorem.
The Strategy: Generate Fibonacci numbers up to the input. Then greedily select the largest Fibonacci number that fits, ensuring no two consecutive numbers are used.
Perl Implementation
sub zeckendorf {
my $n = shift;
my @f = (1, 2);
push(@f, $f[-1] + $f[-2]) while $f[-1] <= $n;
pop @f;
my @r;
for (my $i = $#f; $i >= 0; $i--) {
if ($f[$i] <= $n) { push @r, $f[$i]; $n -= $f[$i]; }
}
return join ",", @r;
}
Python Implementation
def zeckendorf(n: int) -> str:
f = [1, 2]
while f[-1] <= n:
f.append(f[-1] + f[-2])
f.pop()
r = []
i = len(f) - 1
while i >= 0:
if f[i] <= n:
r.append(f[i])
n -= f[i]
i -= 1
return ",".join(str(x) for x in r)