Fibonacci problem

From: Brett Trost (btrost_at_shaw.ca)
Date: 01/22/04


Date: 21 Jan 2004 19:22:06 -0800

OK, I wanted to make a recursive fibonacci method in Perl, and I can't
understand why it is not working, especially since I wrote the exact
same thing in Java and it works. Here's the perl code:

#!/usr/bin/perl
sub fib {
        $num = shift;
        return 0 if $num == 1;
        return 1 if $num == 2;
        return fib($num - 1) + fib($num - 2);
}

print fib($ARGV[0]);

And here's the Java code:

class fib
{
        public static void main(String[] args)
        {
                System.out.println(fib(Integer.parseInt(args[0])));
        }

        static int fib(int x) {
                if (x == 1) return 0;
                if (x == 2) return 1;
                return fib(x - 1) + fib(x - 2);
        }
}

The perl one keeps on running forever. If I print out $num, it goes
rapidly into the negatives. Why is this, when the base case should
take care of that, and the Java code has the exact same logic and
works?! It must be an error with my Perl, but I can't find it.
Thanks for any help.



Relevant Pages

  • Re: string seperated by multiple spaces
    ... Use Charles ... > K. Clarkson, as an example. ... He said the exact same thing, ... > that)...I've decided to use euphoria instead of perl for what i'm doing. ...
    (perl.beginners)
  • Re: string seperated by multiple spaces
    ... Use Charles ... > K. Clarkson, as an example. ... He said the exact same thing, ... > that)...I've decided to use euphoria instead of perl for what i'm doing. ...
    (perl.beginners)
  • Re: Bug in Perl
    ... Is that a bug in Perl really? ... Or is it just that floating point operations ... point operations are not exact. ... I am will put my money on your processor being the issue and Perl working ...
    (perl.beginners)
  • Re: Little question on regex.
    ... L> I hate to say it, ... you can cut&paste and run it using the 'OP's exact example ... L> Perl (which I do not put down as you previously claimed and I ... so i decide your posts aren't worth much. ...
    (comp.lang.perl.misc)
  • SUMMARY: Perl Crypt::IDEA - SFTP ?
    ... Thanks to Tod Sandman for the exact answer I needed.... ... Seth ... here are my notes from my last build of perl ... ...
    (SunManagers)