开发者

How to calculate Lucas Numbers in Java

I am a starting programmer and need to program an application in java which ask for a number and then prints the first n number of Lucas Numbers. for exam开发者_如何学Cple when 7 is put in, it outputs: 2, 1, 3, 4, 7, 11, 18.

Just to be clear, lucas numbers are defined as:

2 if n = 0

1 if n = 1

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

I am really not sure howver how to programm this in java. Because I cannot translate this into java code. I've been thinking for a while now but still can't figure it out. Also when i would have the code for calculating the Nth lucas number, i would now how to output all the first Lucan Numbers up until the Nth number. Can some of you guys help me gte on the right way or give me tips? Thanks a lot!


The definition you have for the Lucas number is recursive, i.e., to calculate the Nth lucas number, you already need to know the N-1th and the N-2nd.

A naive way to do this would be

public int lucas(int N) {
    if( N == 0 ) return 2;
    if( N == 1 ) return 1;
    return lucas(N-1) + lucas(N-2);
}

However, you only have to print the numbers, don't you? Then it's quite easy, actually.

int L2 = 2;
int L1 = 1;
for( int i = 2; i <= N; i++ ) {
    int L = L1 + L2;
    print(L); //or whatever output function you have
    L2 = L1;
    L1 = L;
 }

The idea is to keep the last two numbers, which you need to compute the next two numbers, always at hand.

PS: These Lucas numbers are just like the Fibonacci numbers with different starting values, so any algorithm for the Fibonacci numbers will do. If you're really good at math, you can even try to find a closed formula for the Lucas numbers, but it's definitely beyond high school math (search tag would be "linear difference equation with constant coefficients").


If you're not sure how to do the whole thing, break the problem down into smaller pieces until you can start.

Try taking each case, one at a time. Implement the '2 if n=0' case, test that it works. The calculation is trivial, but you will have to write the code that calls your implementation, too. The trivial case helps you check that the code around it works properly.

Then implement the next one, check it still works, implement the final one. It'll become clearer as you go.


Just in case someone is looking for a formula and happens on this page then maybe this will help. In Windows take the following line and replace each N with the desired integer, copy the modified line and paste it into Windows' calculator:

(5@/2+0.5)yN+(-(5@/2+0.5))y(-N)=

For example if you want to find the Lucus number for 7 you would paste this line into Windows' calculator:

(5@/2+0.5)y7+(-(5@/2+0.5))y(-7)=

And the result will be 29.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜