How to calculate Lucas Numbers in Java

Hi guys, I'm a beginner programmer and you need to program an application in java that asks for a number and then prints the first n number of Lucas Numbers. for example, when you enter 7, it displays: 2, 1, 3, 4, 7, 11, 18.

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 how to program this in java. Because I cannot translate this into java code. I’ve been thinking for a long time, but still can’t understand. Also, when I have the code to calculate the Nth lucas number, I will now output all the first Lucan numbers to the Nth number. Can some of you guys help me on the right track or give me advice? Many thanks!

+3
source share
3 answers

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

A naive way to do it 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 need to print the numbers, right? Then it's pretty simple.

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 you need to calculate the next two numbers, always at hand.

PS: Lucas , , . , , ( " " ).

+5

, , , .

, . "2 if n = 0", , . , , . .

, , , . , .

+1

, - , , . Windows N , Windows:

(5@/2+0.5) Yn + (- (5@/2+0.5)) (-N) =

, Lucus 7, Windows:

(5@/2+0.5) Y7 + (- (5@/2+0.5)) (-7) =

29.

0

Source: https://habr.com/ru/post/1766540/


All Articles