Trouble following recursive code - java

Just trying to understand how this code works. Say the integer is 4, I understand that 4 is checked against the base case and then the method calls itself again this time with the integer 3 and then same pattern occurs until the integer is 1. My question is how is the summation part being done? What would be the final result?
public int sum(int num)
{
int result;
if (num == 1)
result = 1;
else
result = num + sum(num-1);
return result;
}

As I think you realize based on your post, the magic happens here: result = num + sum(num-1); Think of it as a chain of method calls. Logically, the whole process could be represented like this:
sum(4);
evaluates to
4 + sum(3);
which evaluates to
4 + 3 + sum(2);
which evaluates to
4 + 3 + 2 + sum(1);
which evaluates to
4 + 3 + 2 + 1
which is equal to
10

The summation happens as the recursive calls return back up the stack. See here:
sum(4) # The initial function call
|
|---------------|
| 4 + sum(4-1) | # num + recursive call
|
|---------------|
| 3 + sum(3-1) | # the next num + the next recursive call
|
|---------------|
| 2 + sum(2-1) |
|
|---|
| 1 | # Base case num == 1
If you populate each recursive sum(...) call with the value below it, what do you get? The sums added up. That's where the addition occurs.
Trace this and find out what the value should be for yourself. Or, run the code.

It happens here:
result = num + sum(num-1);
together with
return result;
Iteration n calls sum() again (triggering iteration n+1). The result of n+1 is returned; and added to n; giving the result of n-1 (because of the later return statement).
And for the record: I did not include the final solution in my answer; as you can figure that easily by yourself; either by running that code; or by using a pen and a piece of paper to "run" this code "manually".

Related

How is maximum key compare in binary search (1+log(n)) not log(n)?

I was re going through a more versatile explanation of BS. Which has a preposition that maximum number of key compare in a binary search is (1+log(n)). I tried to form an intuition as to how is that possible. I understand the ruining time of BS is (log(n)). Also i speculate that the worse time/maximum key lookups will happen in scenario when we search for a element which is not present in the array. But each time i go over a hypothetical array doing a BS i end up with (log(n)) compares/steps never more than that. Here is the code which was used to form that preposition.
public static int binarySearch(int[] a, int key){
int lo = 0, hi = a.length-1;
while (lo <= hi){
int mid = lo + (hi - lo) / 2;
if (key < a[mid])
hi = mid - 1;
else if (key > a[mid])
lo = mid + 1;
else
return mid;
}
return -1;
}
Probably my speculation is wrong or i am missing some point. If you could explain how maximum possible key compares would be (1+log(n)) it would be great thanks.
Don't forget that even when you have only 1 element, you still have to guess it, because it is possible that the target is not in the array. So we need to add on the +1 for the last guess when we are down to the final remaining element.
It may be clearer if you think about when n=1. We still need 1 guess, but log_2(1) = 0. So we need to add a +1 to fix up the formula.
When n is not a power of 2, we can just go up to the next higher power of 2. For an array whose length is 1000, the next higher power of 2 is 1024, which is 10. Therefore, for a 1000-element array, binary search would require at most 11 (10 + 1) guesses.
Why?
In the worst case, binary search would need 10 steps to separate the remaining numbers and 1 final step to check whether the only one number left is what you want, or it's not in the array.
Here's a different way to think about what you're doing. Rather than thinking of binary search as searching over the elements of the array, think of binary search as searching over the separators between the elements in the array. Specifically, imagine numbering the array like this:
+-----+-----+-----+-----+-----+
| 0 | 1 | 2 | ... | n-1 |
+-----+-----+-----+-----+-----+
Now, number the separators:
+-----+-----+-----+-----+-----+
| 0 | 1 | 2 | ... | n-1 |
+-----+-----+-----+-----+-----+
0 1 2 3 .. n-1 n
Notice that there are n+1 total separators, one before each element and one after the very last element.
Whenever you do a binary search, you're probing the index of the middle separator (do you see why?) and throwing half of the separators away. You can only throw half of a collection of k items away log2 k times before you're down to a single remaining element. This means that the number of probes needed will be ⌈log2 (n+1)⌉, and it happens to be the case that
log2 n < ⌈log2 (n+1)⌉ ≤ log2 n + 1,
so the "1 + log n" bit ends up arising more from "throw away half the separators" than from other sources.
Hope this helps!
Imagine an array of size 8.
l=0, h = 7, mid = 0 + (7-0)/2 = 3 go right
l=4, h = 7, mid = 4 + (7-4)/2 = 5 go right
l=6, h = 7, mid = 6 + (7-6)/2 = 6 go right
l=7, h = 7, mid = 7 + (7-7)/2 = 7 go left
l=7, h=6 ====> terminates
Total comparisons = 1 + Log 8 = 4
EDIT1: Imagine this array and use a pen and paper and trace out the above steps. Search for value 13.
index: 0 1 2 3 4 5 6 7
------------------------------
element: 1 3 5 6 7 9 11 15

Recursive Outputs

This is the following code I had for a recursion question
Is anyone able to run me through how the output is 24?
To prove how confused I am, I thought the output would have been 6, 12, 20 ,1
package Examples;
public class QuestionDemo {
public static void main(String[] args) {
System.out.println(recCall(2));
}
public static int recCall(int num) {
if (num == 5) {
return 1;
} else {
return num * recCall(++num);
}
}
}
You have 4 recursive calls
first one when you call recCall(2)
then recCall(3), recCall(4) and recCall(5)
recCall(5) returns 1
recCall(4) returns 4*1
recCall(3) returns 3*4*1
recCall(2) returns 2*3*4*1 = 24
recCall(int num):
recall(2)
| |
2 * recall(3)
| |
3 * recall(4)
| |
4 * recall(5)
|
1
recall(2) = 24
| |
2 * 12 = 24
| |
3 * 4 = 12
| |
4 * 1 = 4
|
1
Its because you are using the recCall(++num), and you are using pre-increment operator which increases value before calling the method.
Please read how ++ pre increment works in java :- How do the post increment (i++) and pre increment (++i) operators work in Java?
So your recursive calls will look like below
f(2)= 2*f(3)=2*12 = 24.
f(3)=3*f(4)= 3*4=12
f(4)=4*f(5) = 4*1
f(5)= 1
hence it returns 24.
This recursion takes a bottom-up approach. First going deepest to find the value of the base case, before you can get the value of other recursive calls.
This is why you're getting output = 24:
_
/|\
/ | \
recCall(4) = 4 * recCall(5) = 4 + / | \ // recCall(5) is your base case.
recCall(3) = 3 * recCall(4) = 12 + |
----------------------------------- |
recCall(2) = 2 * recCall(3) = 24 | // This was your first call to the recursive function.
You're not traversing through values, but rather adding them all up.
Yes, if you try to move recall(++num) and put the new number which is ++num so result will be = 2 * 3 * 4 and in 5 it will return 1, so 2 * 3 * 4* 1.

Java Recursion Total Breakdown

ArithmSumRec(n)
1. If n = 1
1.1 return 1
2. Else
2.1 return ArithmSumRec(n-1) + n
So for example we want to calculate when n = 5. it will look something like this.
Executing ArithmSumRec(5) ⇒ 5 calls to ArithmSumRec(...)
ArithmSumRec(5)
ArithmSumRec(4)
ArithmSumRec(3)
ArithmSumRec(2)
ArithmSumRec(1)
return 1 // base case
return 1 + 2 (= 3)
return 3 + 3 (= 6)
return 6 + 4 (= 10)
return 10 + 5 (= 15)
But my question is now, when the method returns the first time it's:
return ArithmSumRec(5-1) + 5;
But what happens to that 5 that's outside the parentheses. Why doesn't the method return 9 (since (5-1)+5 = 9?) and instead it returns a 4? And where does that +n go?
And if there's a good thread already that I haven't found or website that thoroughly explains recursive methods, I would appreciate that a lot.
This is order of operations. A function call takes precedence over addition. Thus, when you call
func(5-1) + 5
... the first operation is 5-1, giving 4. Now the run-time system executes the call func(4). After this is done, it finally adds the 5.
Compare your situation with a different function call:
sqrt(5-1) + 5
This is equivalent to having the square root sign over "5-1" with a "+ 5" after all of that. This simplifies to sqrt(4) + 5, or 7. It does not evaluate to 9 (following your original statement as written), nor does it evaluate to 3 (from sqrt(5-1 + 5)).
Does that help?
Recursive calls do not return anything until you stop the recursion. If there wouldn't be the
if (n==1) return 1;
the program would hang there.
But when you hit the return 1, then the whole calculation is clear and you can actually return a number:
5 + 4 + 3 + 2 + 1 = 15

Analyzing runtime of a short algorithm

I got the following code given:
public class alg
{
public static int hmm (int x)
{
if (x == 1)
{
return 2;
}
return 2*x + hmm(x-1);
}
public static void main (String[] args)
{
int x = Integer.parseInt(args[0]);
System.out.println(hmm(x));
}
}
So first question is, what does this algorithm count?
I have just typed and runned it in eclipse
so I can see better what it does (it was pseudocode before, I couldn't type it here so I typed the code). I have realized that this algorithm does following: It will take the input and multiply it by its following number.
So as examples:
input = 3, output = 12 because 3*4 = 12.
Or Input = 6, output 42 because 6*7 = 42.
Alright, the next question is my problem. I'm asked to analyze the runtime of this algorithm but I have no idea where to start.
I would say, at the beginning, when we define x, we have already got time = 1
The if loop gives time = 1 too I believe.
Last part, return 2x + alg(x-1) should give "something^x" or..?
So in the end we got something like "something^x" + 2, I doubt thats right : /
edit, managed to type pseudocode too :)
Input: Integer x with x > 1
if x = 1 then
return 2;
end if
return 2x + hmm(x-1);
When you have trouble, try to walk through the code with a (small) number.
What does this calculate?
Let's take hmm(3) as an example:
3 != 1, so we calculate 2 * 3 + hmm(3-1). Down a recursion level.
2 != 1, so we calculate 2 * 2 + hmm(2-1). Down a recursion level.
1 == 1, so we return 2. No more recursions, thus hmm(2-1) == hmm(1) == 2.
Back up one recursion level, we get 2 * 2 + hmm(1) = 2 * 2 + 2 = 4 + 2 = 6. Thus hmm(2) = 6
Another level back up, we get 2 * 3 + hmm(2) = 6 + 6 = 12
If you look closely, the algorithm calculates:
2*x + ... + 4 + 2
We can reverse this and factor out 2 and get
2 * (1 + 2 + ... + x).
Which is an arithmetic progression, for which we have a well-known formula (namely x² + x)
How long does it take?
The asymptotic running time is O(n).
There are no loops, so we only have to count the number of recursions. One might be tempted to count the individual steps of calculation, but those a are constant with every step, so we usually combine them into a constant factor k.
What does O(n) mean?
Well ... we make x - 1 recursion steps, decreasing x by 1 in every step until we reach x == 1. From x = n to x = 1 there are n - 1 such steps. We thus need k * (n - 1) operations.
If you think n to be very large, - 1 becomes negligible, so we drop it. We also drop the constant factor, because for large n, O(nk) and O(n) aren't that much different, either.
The function calculates
f(x) = 2(x + x-1 + x-2 + ... + 1)
it will run in O(x), i.e. x times will be called for constant time O(1).

Program flow on recursion with strings and ints

I don't understand how this works. I know basic factoral recursion, but this is of a mixed type. Could someone explain step by step on what's going on with the output based on this exact code snippet? Even just a few of the first values (commented at the end of the code)?
Thanks :)
public class recursion1st
{
public static String recFun(int x)
{
if (x <= 0) return "/";
return recFun(x-3) + x + recFun(x-2) + x;
}
public static void main(String[] args)
{
System.out.println(recFun(8));
}
}
//Produces '/2/25/3/1/1358/3/1/136/1/14/2/2468 '(?)
3| function taking an int argument
5| this is your base case, return "/" if...
6| this is your recursion, call recFun(x-3) + x /*this is your current value */ recFun(x-2) + x. basically this is going to go until you're x reaches 0 or less. Note the right root recursive call will go through more recursions before it hits the base case because it is passing x - 2 everytime instead of x-3. Also realize this statement calls recursively twice.
Make a chart on a big piece of paper and map out passing 8 in:
8
root
return recFun(5) + 8 + recFun(6) + 8
1st branch
return recFun(2) + 5 + recFun(3) + 8
2nd branch
return recFun(3) + 6 + recFun(4) + 6
.......................
Keep going it will become clear.
In the main function, it is calling recFun() to print the data. In that function, which is recursive, the first if condition is to break out of recursion, when that condition is met (when x is negative or equal to zero).
Else it will return a string, in turn again calling itself.
Here, in the first return, it calls recFun(5) and and recFun(6) and likewise, if you analyse step by step, the cycle continues till the break condition is met. Basically the return statement is concatenation of strings, and it separates the data by placing "/" on breaking out of recursion.
EDIT:
Value returned by return statement is
rec(5)+8+rec(6)+8......(1)
where
rec(5) returns rec(2)+5+rec(3)+5......(2)
and
rec(6) returns rec(3)+6+rec(4)+6.......(3)
where
rec(3) returns "/"+3+rec(1)+3.......(4)
and
rec(4) returns rec(1)+4+rec(2)+4.....(5)
and
rec(2) returns "/" +2 +"/"+2.....(6)
and
rec(1) returns "/"+1+"/"+1 .......(7)
Substitute (7) and (6) in (5)
Substitute (7) in (4)
Substitute (4) and (5) in (3)
Substitute (4) and (6) in (2)
and substitute (2) and (3) in (1)
You will need a sheet for this. Try and work it out using this. Hope it helps. :)
take a paper and write down step by step what the function does:
recFun(5)
|
recFun(2) + 5 + recFun(3)+5
| |
recFun(-1)+2+recFun(0)+2 recFun(0)+3+recFun(1)+3
| | | |
"/" "/" "/" recFun(-2)+1+recFun(-1)+1
| |
"/" "/"
1 call recFun with 5
2 5 leads to recFun with 2 & recFun with 3
3 2 leads to recFun with -1 & recFun with 0 , 3 leads to recFun with 0 & recFun with 1
4 -1 leads to "/", 0 leads to "/", 0 leads to "/", 1 leads to recFun with -2 & recFun(-1)
5 -2 leads to "/", -1 leads to "/"
Until every singe call is finished executing (until the x <= 0 and a "/" is returned) no call made before will return anything. The function starts returning Strings from the end of that chain of calls (in this pyramid: bottom to top and from right to left)
/ 1 / 1
/ 2 / 2 / 3 3
5 5
-> / 2 / 2 5 / 3 / 1 / 1 3 5
I know, recursion is confusing. The only thing that helps me is: first make every last call of the recursive function and only when the last call returns anything then roll back. Sorry if this isn't any more precise :)

Categories

Resources