Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Java Recursion Method

Tags:

java

recursion

I am having a lot of trouble with this basic recursion problem in java; any pointers would be great.

"Write a static recursive method to print out the nth term of the geometric sequence: 2, 6, 18, 54."

From what I can gather, somewhere in the code I should be recursively multiplying something by 3, but I'm struggling to figure out how to do this. I know I need a termination statement, but when does that occur? Do I need a helper method?

like image 219
user1198037 Avatar asked Feb 16 '26 13:02

user1198037


2 Answers

A Recursive Function is a function whose implementation references itself. Below is some funny example:

public class Inception {
   public void dream() {
      boolean enoughDreaming = false;
      //Some code logic below to check if it's high time to stop dreaming recursively
      ...
      ...

      if(!enoughDreaming) {
           dream(); //Dream inside a Dream
      }
   }
}

And the solution for your problem:

public class GeometricSequence {
    public static void main(String[] args) {
        //Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
        System.out.println(findNthNumber(5, 1, 2));

    }

    public static int findNthNumber(int n, int count, int res) {
        return ((count == n)) ? res : findNthNumber(n, count+1, res *3);
    }
}

EDIT:

The above class uses "int", which is good only for small numbers (because of Integer Overflow problem). The below class is better for all types/numbers:

public class GeometricSequence {
    public static void main(String[] args) {
        //Below method parameters - 5 = n, 1 = count (counter), res = result (Nth number in the GP.
        System.out.println(findNthNumber(2000, 1, new BigInteger("2")));

    }

    public static BigInteger findNthNumber(int n, int count, BigInteger res) {
        return ((count == n)) ? res : findNthNumber(n, count+1, res.multiply(new BigInteger("3")));
    }
}
like image 142
bchetty Avatar answered Feb 18 '26 01:02

bchetty


This is the simplest example of recursion.

You need a method declaration.

You need to check if the end has been reached.

Otherwise you need to call the method again with an operation which makes the difference between one term and the next.

like image 34
Peter Lawrey Avatar answered Feb 18 '26 01:02

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!