Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Recursive Loops - How to implement "Lucas Numbers" Algorithm?

807589Nov 3 2008 — edited Nov 3 2008
Hey,

I've seen other posts that are criticized to be more specific, so I hope I am clear in my questions.

I am trying to implement the Lucas Numbers series through a recursive loop. The formula is the following:

Ln = Ln-1 + Ln-2 for n>1
L0 = 2
L1 = 1

This is my first attempt at the code, which runs and gives horrible output for obvious reasons; my algorithm is probably incorrect.
//Based on the above algorithm, let Ln be L(int number)
public class RecursiveMethods{
    //int limit = 30;
    public RecursiveMethods(){
        //No Constructor Yet
    }
    public int getLucasSequence(int number){ //Will print out 
        if(number == 1){ //I don't know what to set the base case to.
            return number;
        }
        else{
           // System.out.println(number);
            return number * getLucasSequence((number - 1) + number);  //Is this where the formula goes?  If so, how do I implement it?
        }
}
public static void main(String [] args){
    //System.out.println("Test");
    RecursiveMethods myMethods = new RecursiveMethods();
    //System.out.println(myMethods.getLucasSequence(99));
    //for(int i = 0; i < 10; i++){ //Is this where you set the limit of iterations?
        System.out.println(myMethods.getLucasSequence(4)); //Value must not be one or two
   // }
    
}
}
I have the following questions:

1) Based on the mathematical algorithm, how would I implement it in Java?
2) What would be the base case for a recursive loop that prints a series of Lucas Numbers
3) How would I set the limit on numbers?

I am a beginner programmer, so please explain these in terms I will be able to understand. I don't mind if you give hints too.

Thanks!
Chris
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 1 2008
Added on Nov 3 2008
12 comments
1,722 views