Hey guys, I'm starting a programming program and need to program an application in Java that demands a number and then prints for the first time.
The number of Lucas numbers, for example, when 7 is inserted, 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'm not really sure how to programm it in Java. Because I could not translate it into Java code I was thinking for a while, but still could not figure it out. Also, when I had the code to calculate Anth Lucas number, how do I now output all the first Lukan numbers to NF numbers? Can some of you guys help me in the right way or can I suggest me? Thanks a lot!
You have the definition recursive for the Lucas number, that is, the N.A. Lucas number, you need to know N-1 and N-2 already.
A Inexperienced will be the way to do this
Public Int Lucas (Int N) {if (n == 0) returns 2; If (N == 1) returns 1; Return Lucas (N-1) + Lucas (N-2); }
However, you only have to print the number, right? Then it's really very easy.
int L2 = 2; Int L1 = 1; {Int L = L1 + L2; for int i = 2; i & lt; = N; i ++); Print (L); // or whatever output function you have L2 = L1; L1 = L; }
This idea is to keep the last two numbers, which you need to calculate the next two numbers, always in hand.
PS: These Lucas numbers, with different values just like Fibonacci numbers, therefore there will be no algorithm for Fibonacci numbers. If you are really good in mathematics, you can also try to find a closed formula for Lucas numbers, but it is definitely beyond high school mathematics (the search tag will be "linear differential equation with constant coefficient") .
Comments
Post a Comment