Reputation: 21
I'm an extremely basic java user. I'm doing it for this class, and I've written the entire program, I just can't for the life of me figure out the algorithm that I need to get the desired output, so I was wondering if any Java or Math gurus can help a simple fellow like myself out. The assignment is due tomorrow and this is the final question. Any help is appreciated.
This is the code in my main method with the desired output commented in, followed by the sequence 2 method.
for(int i = 0; i < 10; i++) {
System.out.print(sequence2(i) + " "); // 1, 2, 4, 5, 7, 8, 10, 11, 13, 14
}
public static int sequence2(int n) {
if(n == 0)
return 1;
if(n == 1)
return 2;
if(n == 2)
return 4;
if(n == 3)
return 5;
return sequence(n-3) + sequence(n-3);}
I'm not sure if it's an issue with my bases, or with my calculation at the bottom. Any help is greatly appreciated!
Upvotes: 0
Views: 105
Reputation: 159114
Update
Since it has to be a recursive method, this will do it:
public static int sequence2(int n) {
return (n <= 1 ? n + 1 : 3 + sequence2(n - 2));
}
Original Answer
This will do it:
public static int sequence2(int n) {
return n / 2 * 3 + n % 2 + 1;
}
Output
1 2 4 5 7 8 10 11 13 14
To see how it adds up, here are the intermediate values:
n 0 1 2 3 4 5 6 7 8 9
-----------------------------------------------------
n / 2 0 0 1 1 2 2 3 3 4 4
n / 2 * 3 0 0 3 3 6 6 9 9 12 12
n % 2 0 1 0 1 0 1 0 1 0 1
1 1 1 1 1 1 1 1 1 1 1
=====================================================
result 1 2 4 5 7 8 10 11 13 14
Upvotes: 1