What is the output of the following Python program?
1 2 3 4 5 6 7 8 9 10 11 12 |
|
Bonus
: What is the output of
func(a,b)
?
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Actually, the cases 1 and 2 in your solution should be a > b > 0 and 0 < a ≤ b respectively.
Also, the cases 0 = a < b and a > b = 0 aren't covered up in your proof and need to be dealt with separately although not much work is needed to show that.
f ( 0 , b ) = 1 + f ( 0 , b − 1 ) = f ( 0 , 0 ) + i = 1 ∑ b 1 = 0 + b = b ∀ b ≥ 1
Similarly, we see that f ( a , 0 ) = 0 + a = a ∀ a ≥ 1 thus showing that f ( a , b ) = a + b holds true for these cases too.
Copying it as it is didn't work as it led to stack overflow. But observing pattern of what it does on smaller inputs does work.
Log in to reply
Yes. After observing the pattern, what we need to do is to prove that it's true.
a and b have no assigned value
Problem Loading...
Note Loading...
Set Loading...
The easiest approach is to copy this code and runs it in your machine. But if you are looking at this solution, I believe you didn't use that method.
There are no efficient way that I know of to figure out what's a recursive function is doing other than looking for patterns and then prove them to be true. Like many other techniques, this requires experiences. For this problem,
func(a,b)
turns out to be a function that returnsa+b
.After identifying this pattern, all you need to do is to prove it. This is very similar to induction .
Base case : a = 0 , b = 0
f ( 0 , 0 ) = 0 + 0 = 0
Hence the base case is true.
Recursive step case 1 : a > b > 0
f ( a , b ) = 1 + f ( f ( a − b , b ) , b − 1 ) = 1 + f ( a − b + b , b − 1 ) = 1 + f ( a , b − 1 ) = 1 + a + b − 1 = a + b
Recursive step case 2 : 0 < a ≤ b
f ( a , b ) = 1 + f ( a − 1 , f ( b − a , a ) ) = 1 + f ( a − 1 , b − a + a ) = 1 + f ( a − 1 , b ) = 1 + a − 1 + b = a + b