LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   need perl help calculating fibonacci numbers (https://www.linuxquestions.org/questions/programming-9/need-perl-help-calculating-fibonacci-numbers-126471/)

WorldBuilder 12-16-2003 08:22 PM

need perl help calculating fibonacci numbers
 
Hi all,

I have a script that I am trying to get to write fibonacci numbers. Here's what I need to do:
Code:

Write a program that prints out the first n fibonacci series numbers.

*The fibonacci series start out like this:

n=0        n=1        n=2        n=3        n=4        n=5        n=6        n=...
1        1        2        3        5        8        13        ...

In math terms, each element is the sum of the preceding two elements: F(0)=1, F(1)=1, F(n) = F(n-1) + F(n-2) for n>1

Here's how I wrote it so far:
Code:

#! /usr/bin/perl

print "Please type in how many fibonacci numbers you would like displayed. n: ";
$n = <STDIN>;
$x = 1;
$y = 0;
$a = 0;

while ($a <= $n) {
        process($x, $y, $a);
        $a++;
}

sub process {
        $z = $_[0] + $_[1];
        $y = $_[0];
        $x = $z;
        print "n=$_[2]\t$z\n";
}

The output of this script if I input n equal to 5 is:
Code:

n=0    1
n=1    2
n=2    3
n=3    5
n=4    8
n=5    13

Obviously, that is not right. What am I doing wrong?! Thanks!

AltF4 12-16-2003 09:34 PM

you need to init fib(0)=1 and fib(1)=1 first
the program should start at fib(2) ..

#! /usr/bin/perl

print "Please type in how many fibonacci numbers you would like displayed. n: ";
$n = <STDIN>;
$x = 1;
$y = 1;
$a = 2;

print "n=0\t1\n";
print "n=1\t1\n";

while ($a <= $n) {
process($x, $y, $a);
$a++;
}

sub process {
$z = $_[0] + $_[1];
$y = $_[0];
$x = $z;
print "n=$_[2]\t$z\n";
}

WorldBuilder 12-16-2003 09:44 PM

Thanks! You're absolutely right. I didn't even see that. I appreciate it, bro!

AltF4 12-16-2003 09:59 PM

no problem - you're welcome

ToniT 12-16-2003 10:25 PM

Ther's more than one way to do it.

An example impementation with easy possibility for precalculating the values.
Code:

#! /usr/bin/perl

@values = (1,1);

sub calculateOneMore {
  push @values,$values[$#values-1]+$values[$#values-2];
}
sub Next {
  calculateOneMore();
  shift @values;
}
print "n=$_\t" . Next() . "\n" foreach (0 .. shift);


Berng 12-17-2003 01:41 AM

:D
But, of couse the simpliest way to correct this program is to swap the first $x, $y values(5-6 lines):
instead of
$x = 1;
$y = 0;
put
$x = 0;
$y = 1;
:D :D :D
Best Regards,
Oleg.


All times are GMT -5. The time now is 08:24 PM.