简体   繁体   中英

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 .

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.

Change

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM