The equivalent function 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def fun1(a,b):
    if b==0:
        return 0
    return a + fun1(a, b-1)

def fun2(a,b):
    if b==0:
        return 1
   else:
        return fun1(a, fun2(a, b-1))

Which of the following is equivalent to the fun2() function shown above?

Assumptions

a , b a,b are non-negative integers.

a ( a + b ) a*(a+b) a b a^{b} a 2 + b a^{2}+b a + b 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.

3 solutions

Christopher Boo
May 18, 2016

You can easily deduce the purpose of a recursive function by looking at how it combines the result of a sub solution.

For example, fun1(a,b) will keep adding a until b goes to 0 . Each time b is reduced by 1 , the result is added with a . Hence it is equivalent to a a sum itself b b times, which is just a b ab .

Then, fun2(a,b) is very similar except each time b is reduced by 1 , the result is multiplied by a . This is equivalen to a a multiplies itself b b times, which is just a b a^b .

Anoorag Nayak
Nov 24, 2015

Just see the first condition for function 2- If b=0, then it will return 1. Now since only one option must be true when b=0, a^b is the answer.

Elijah Frank
Dec 7, 2020

two solutions the dumb and the mathematical: mathematical: we can do a=2, b=3. so is the same for the minus 1 like 2 2 2 or 2^3 dumb: def fun1(a,b): if b==0: return 0 return a + fun1(a, b-1) # a + a * (b-1) 1+1 1 or a b

def fun2(a,b): if b==0: return 1 else: return fun1(a, fun2(a, b-1)) # a (a (b-1)) 3 3 4 or a^b print(fun2(2, 3))

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...