1

So there is a recursive method (can not use any loop), that has one parameter n, and the program will print out 2^n "*", for example, if n was 2, the output is ****, and if n was 3, the output is ********.

I'm stuck with this problem because I ran into some infinite recursion issues.

First I had this: but I soon realize that n will never reach the check.

enter image description here

↑↑↑ That was supposed to be n+1 (even though it doesn't work)

Then I tried this:

public class test {

    public static void main(String[] args) {
        printPowerOfTwoStars(3);

    }

    public static void printPowerOfTwoStars(int n){
        n = (int)Math.pow(2, n);
        if(n == 0){
            return;
        }
        else{
            System.out.print("*");
            printPowerOfTwoStars(n-1);
        }

    }

}

Ran into some infinite recursion again.

This seems like a simple program with simple logic, but I'm having trouble with the condition check, because what's being compared with n keeps changing.

How should I fix this problem?

Without using any helper method or creating any static variables.

Thank you

0

1 Answer 1

4

You need to use the fact that 2 to the power of n is just 2 to the power of n-1, doubled. Your base case is that 2 to the power of 0 is 1.

public static void printPowerOfTwoStars(int n){
    if(n <= 0){
        System.out.print("*");
    }
    else{
        printPowerOfTwoStars(n-1);
        printPowerOfTwoStars(n-1);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

That's brilliant! Now I'm just curious if there is a way to use Math.pow in this case. Thank you!
If the question was to print 3^n times, how would I implement this problem? Using the same logic, 3 ^n is just 3^n-1, tripled (3^n-1) x 3 = 3^n... how would you do that? Is it just printPowerOfTwoStars(n-1); three times?
Well, you could just have printPowerOfThreeStars(n-1) three times inside the else clause. Or put a loop inside the else clause. Or use two dimensional recursion - which is probably a whole other question.
Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.