Fibonacci number in while loop
Posted on December 19th, 2007 by linux
Using single while loop to calculate Fibonacci number. This script is in Perl but can be easily translated to any other language:
#!/usr/bin/perl
$i=0;
$fibonacci_number=0;
$a=1;
$b=0;
while ($i < 30) {
$b = $fibonacci_number;
$fibonacci_number = $a + $b;
print $fibonacci_number . “,”;
$a = $b;
$i++;
}
print “\n”;
Output:
./fibonacci.pl
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
10946,17711,28657,46368,75025,121393,196418,317811,514229,832040,
Filed under: Perl, Uncategorized