Skip to main content
3 of 5
added 190 characters in body
core1024
  • 1.8k
  • 13
  • 16

Perl

$b = ($i = <>) - ~-$i;
{
    ($b, $a)=($a + $b, $b);
    redo if --$i
}
print "$a\n";

This takes an input from STDIN and prints the n-th Fibonacci number.

($i = <>) initializes $i with the input. Then $b is set to 1 by a bit of bit manipulation and subtraction. The "magic" here is done by the redo operator. It makes it possible to reevaluate the same block, without the need of loop. The calculation of $a and $b is redone until the subtraction of one by $i evaluates to False i.e. 0. I think that the print statement in the end is self-explanatory.

Here's one more solution using map instead of redo:

print ~~ (
    map {
        ($b, $a) = ($a + $b, $b)
    } ++$b .. <>
)[-1] . $/;
core1024
  • 1.8k
  • 13
  • 16