Twitter khuong291
Twitter khuong291

Reputation: 11692

How to calculate the lucas number?

Lucas numbers are numbers in a sequence defined like this:

L(n) = 2 if n = 0

L(n) = 1 if n = 1

otherwise

L(n) = L(n - 1) + L(n - 2)

Here is my code:

public class Lucas {
    public static int lucasnum(int n) {
        if (n >= 0) {
            if (n == 0)
                return 2;
            else if (n == 1)
                return 1;
            else
                return lucasnum(n - 1) + lucasnum(n - 2);
        }
        else{
            if (n == 0)
                return -2;
            else if (n == -1)
                return -1;
            else
                return lucasnum(n + 1) - lucasnum(n + 2);
        }
    }

    public static void main(String[] args) {
        System.out.println(Lucas.lucasnum(-5));
    }
}

But I have some problem with negative number. If n == -5 it must return -11 but my code above return 3.

Upvotes: 4

Views: 2619

Answers (2)

Rohcana
Rohcana

Reputation: 359

I think You got the formula for negative indexes backward.

Since,

L(n+2)=L(n+1)+L(n)

=> L(n)=L(n+2)-L(n+1)

So, change

return lucasnum(n + 1) - lucasnum(n + 2);

to

return lucasnum(n + 2) - lucasnum(n + 1);

Faster Algorithms

Your Algorithm is an O(n) algorithm, which is slow for large n. You can do it faster.

Upvotes: 3

Paul Boddington
Paul Boddington

Reputation: 37655

Change

return lucasnum(n + 1) - lucasnum(n + 2);

to

return lucasnum(n + 2) - lucasnum(n + 1);

Upvotes: 2

Related Questions