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
Related
Ok, here is my problem. When I initialize x with 5, the while loop doesn't terminate but initializing it with an even number such as 6 terminates the loop:
int x = 6;
while(x != 0){
x = x + 2;
}
Surprisingly for me, this terminates even though I thought it would not. However,the following similar loop, with odd value for x loops infinitely:
int x = 5
while(x != 0){
x += 2;
}
It seems this happens only with the while loop in Java as I didn't get similar results with the for loop. Please help explain this to me as I'm currently confused. Thanks
Integer overflows at 2147483647 and if you add 1, it will goes to -2147483648 . So when you start from even number you will get back to zero again. But when you start from odd number you will never get back to zero.
Not going to much into depth here, but its because of the overflow. An integer is 32 bit, so its a finite amount of numbers. Since its signed it means that the numbers range from −2.147.483.648 to 2.147.483.647. So in this example: 2.147.483.647 + 1 = -2.147.483.648 is an overflow.
This means if u have x+1 in your while loop will always terminate. Because once the 0 is reached, the while loop condition is broken. If you add 2 it seems to work because the number x reaches 0 at some point.
Hope it helps mate.
You can see the same effect on a regular 12 hour wall clock. Pick any hour. Until you reach 12, add two hours.
You'll notice that if you start on an even hour, you'll always stop. For example, 6:
6 + 2 = 8
8 + 2 = 10
10 + 2 = 12 // stop
However, if you start on an odd hour, you'll never stop. For example:
5 + 2 = 7
7 + 2 = 9
9 + 2 = 11
11 + 2 = 1
1 + 2 = 3
3 + 2 = 5
5 + 2 = 7
...
A Java int works the same way, but instead of 12 hours, it has 2^32 = 4294967296 values. Instead of wrapping from 12 to 1, it wraps from 2147483647 to -2147483648.
Note that for loops do behave the same way: for(int x=6; x!=0; x+=2) {} does indeed stop while x=5 does not.
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".
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).
First off, it's not homework. I'm practicing examples from http://codingbat.com/java/Recursion-1. Every time I think I'm beginning to understand recursion, I run into a problem that makes me realize I have no idea, and the only thing tutors or internet explanations ever say is that "the function calls itself until the base case is met."
public int sumDigits(int n) {
if(n < 10) {
return n;
} else return sumDigits(n/10) + n % 10;
}
If I pass 115 to this on my computer, the output is 7 (as it should), but I don't understand how the program comes to this conclusion. Here is how I see it:
115 is not less than 10, so return the program with 115/10 (which is 11). 11 is not less than 10, so return the program with 11/10 (which is 1). Add this to 115%10 (which is 5). So how does this program get 7???
It seems like no matter how many examples I look at, I cannot find a pattern in how this works.
You may find it easier to reason about this code if you swap the two operands of the +, that is, change it to read:
return (n % 10) + sumDigits(n / 10)
i.e.
sumDigits(115) = 5 + sumDigits(11)
sumDigits(11) = 1 + sumDigits(1)
sumDigits(1) = 1
so expanding that:
sumDigits(115) = 5 + (1 + sumDigits(1))
= 5 + 1 + 1
= 7
Here is how it happens explained with a diagram
You have it almost correct, you just missed one step when returning out of the recursion - when returning from the 11/10, you add another 1:
call for 115
115 > 10, call recursively for 11
11 > 10, call recursively for 1
1 < 10, return 1
return the 1 from recursive invocation + 11%10 = 1 + 1 = 2
return the 2 from recursive invocation + 115%10 = 2 + 5 = 7
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 :)