0
def foo(x):
    if x > 5:
        return foo(x–1) – foo(x-1)
    else:
        return 77

def bar(a,b):
    if (b > 0):
        return bar( bar(a, b+1) , b-1 )
    else:
        return 0 

Could someone walk me through on how to find the running times for these? For foo, my guess is that it is O(n^2) due to 2 recursive calls. Could it be Θ(n^2) as well?

For bar, I have no clue since it's infinite recursion.

phant0m
  • 16,595
  • 5
  • 50
  • 82
Leon Kingston
  • 73
  • 1
  • 1
  • 6
  • Stop guessing and compare the running time of `foo(x)` and `foo(x-1)`. – Henrik Nov 29 '12 at 07:58
  • 1
    Are you sure `bar` is correct? That looks like it never terminates for positive values of `b`. As for `O(n^2)`: No, that is incorrect. – phant0m Nov 29 '12 at 08:30
  • possible duplicate of [running time in big o notation and lazy evaluation](http://stackoverflow.com/questions/13620069/running-time-in-big-o-notation-and-lazy-evaluation) – amit Nov 29 '12 at 09:10

2 Answers2

0

Obviously foo(n) is not in polynomial time:

T(n) = 2T(n-1)  , if n > 5
     = Theta(1) , otherwise

Thus

T(n) = Theta(2^n)

bar(a,b) never ends as long as b > 0

xiaoyi
  • 6,641
  • 1
  • 34
  • 51
0

For the function

          _________  77  if(x<=5)
         /
        /
 foo(x)- 
        \
         \_________    foo(x-1) - foo(x-1)   if(x>5)


let f(x) be time function for foo(x)

f(x) =   f(x-1) - f(x-1) // 2 (2^1)calls of f(x-2) happened for 1 level depth
f(x) =   [f(x-2) - f(x-2)] - [ f(x-2) - f(x-2)] (expanding f(x-1)) // 4(2^2) calls of f(x-2) happened for 2nd level depth
f(x)={[ f(x-3) - f(x-3)]-[ f(x-3) - f(x-3)]} - {[ f(x-3) - f(x-3)]-[ f(x-3) - f(x-3)]} // 8(2^3) calls  of  f(x-2) happened for 3rd level depth

let i calls has happened to complete program....

but program terminates when x<=5,
 so program terminates in call f(x-i) when x-i<=5
that means i>=x-5 , 
at level i there are 2power(i) calls 
 ==> 2^i calls of f(x-i).
 since f(<=5)=1(1 is unit of measure) for i>=x-5 

so f(n) = 2^(x-5)*(1) =>O(2^x) where x is input size . if we replace x with n complexity is O(2^n) .

for second question

          _________  0  if(b<=0)
         /
        /
 bar(a,b)
        \
         \_________  foo( bar(a,b+1) ,b-1 )  if(b>0)

let t(n) be time function for bar(a,b) where n is proportional to b as b is deciding factor for termination .

expanding reccurence

t(a,b) = t( t(a,b+1), b-1) .
first  t(a,b+1) is executed it inturn calls t(a,b+2) and so on.... 
it will be infinite recursion .....   for b > 0  . 

To my knowledge ,since we don't have limit for infinity(neither lower limit nor upper limit, so no theta notation and no big-oh notation so as omega notation) we cant measure complexity function as well .(Please correct me if i'm wrong)

But if b<0 then it will be done in O(1) time...

Imposter
  • 2,666
  • 1
  • 21
  • 31