1

I want to make a program to output this number sequence: (2),(5),(11),(23),...
where xi = 2*xi-1 + 1, and x0=2.

Here's my code:

    public static int num(int n){
        if(n <= 0)
            return 2;
        else
            return ((2 * 2)+1);

    }

I'm having trouble finding a way to output the numbers 11, 23 and onwards. Would it work if I set a counter variable and continuously loop around the second return statement?

2
  • 2
    return ((2 * num(n-1))+1); Commented Mar 26, 2015 at 18:19
  • 1
    check what you are returning, you should use n there so return ((2 * 2) +1); should be return ((2 * num(n-1))+1); Commented Mar 26, 2015 at 18:20

1 Answer 1

2

Well seeing as you want it to be recursive, let's make it recursive!

public static int num(int n){
    if(n <= 0)
        return 2;
    else
        return (2 * num(n-1))+1; //Recursive call here
}

With a quick runnable method to check it:

public static void main(String[] args){
    for(int i = 0; i < 10; i++){
        System.out.println("num(" + i + ")=" + num(i));
    }
}

Output:

num(0)=2
num(1)=5
num(2)=11
num(3)=23
num(4)=47
num(5)=95
num(6)=191
num(7)=383
num(8)=767
num(9)=1535
Sign up to request clarification or add additional context in comments.

Comments

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.