Skip to main content
5 of 5
added 2 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] . $/;

This generates an array of up to the requested number of the Fibonacci sequence and prints the last entry. ++$b initializes $b to 1. Then the end of the rage, generated by .., is read by <>. map iterates it and the calculation is returned as an array. Then [-1] uses the last element to print.

core1024
  • 1.8k
  • 13
  • 16