0

I'm having a lot of trouble understanding Big Oh.

I'm pretty sure that the following code is O(N).

public static int two1 (int n) {
  if (n == 0) {
   return 1;
  } else {
   return 2 * two1(n - 1);
  }
}

In the second example, I'm totally lost. Can someone explain to me what notation this would be?

public static int two2 (int n) {
  if (n == 0) {
   return 1;
  } else {
   return two2(n - 1) + two2(n - 1);
  }
}

3 Answers3

0

When n = 0, it takes 1 step. When n = 1, it takes 1 + t(0) + t(0) = 1 + 1 + 1 = 3 steps. When n = 2, it takes 1 + t(1) + t(1) = 1 + 3 + 3 = 7 steps. When n = 3, it takes 1 + t(2) + t(2) = 1 + 7 + 7 = 15 steps.

This is just 2^n - 1, so O(2^n).

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

The O notation is equal to the answer. O(fib(n)) You eventually turn all the calculations in 1+1+1+1+1+....1 to get the answer this is also the order.

fib(n) is approximately the golden ratio^n or (1+sqrt(5))/2^n.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

It would be O(2^n)

Think about it. The first one, take the inputted n. Say you inputted k. It would take k steps. If you input 2+1, it would take k+1 steps. If you inputted 2k, it would take twice as long.

In the second example, if you inputted 3 for example, you would have to calculate two2(2) + two2(1). If you inputted 4, you would have to do all of the work for two2(3) and all of the work for two2(2).

To better illustrate, think of two2(100). This would require two2(99) + two2(98). Both sides are relatively similar in size. If you had to do two2(101), you would have to do roughly twice as much work.

Does that help?

See this also: Computational complexity of Fibonacci Sequence

Community
  • 1
  • 1
TMR
  • 96
  • 5