2
$\begingroup$

This question already has an answer here:

How exaclty do you determine this specific codes runtime is theta(n^2)??I can see theres two while loops which go from i and j to n but would like a more precise way of determing this? If someone could explain is simple terms as I am very new to this I would appreciate it.

def f(n):

i = 0

  while i < n:

   j = 0

     while j < n:

      j = j + 1

 i = i + 5
$\endgroup$

marked as duplicate by Yuval Filmus, David Richerby, Evil, Juho, hengxin Apr 4 '17 at 11:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • $\begingroup$ ^that question is more broad in nature.. I am looking specifically at time complexity and in this case the algorithm in question. $\endgroup$ – 78lee Mar 21 '17 at 17:05
  • 2
    $\begingroup$ I suggest you try studying the material there, apply it to this specific situation, work through the math, and see if you can solve the question on your own. If you're still stuck, edit the question to show us how you applied those techniques, how far you got, and where you got stuck. We're happy to help you learn the general techniques, but just handing you the answer to exercises is unlikely to achieve that -- you'll need to put in some work on your own to study the material and try to apply it. $\endgroup$ – D.W. Mar 21 '17 at 17:12
  • $\begingroup$ This question is utterly standard. In addition to the reference Mario links, try any of the many questions in algorithm-analysis+loops. $\endgroup$ – Raphael Mar 21 '17 at 19:03
0
$\begingroup$

Solution 01) Analysis what code does.

Your code execute the first loop n times.

And for each executions on first loop it will execute n times.

So the result will be n * n = n^2

Solution 02) Try to count how many times execute the instruction

def f(n):
count = 0
i = 0
  while i < n:
   j = 0
     while j < n:
      j = j + 1
      print("execute:" + count)
      count = count + 1
 i = i + 1
$\endgroup$
  • $\begingroup$ 1) is a decent sketch, but very brief. Why is any of them true? What exactly are you counting? What is the meaning of getting $n^2$? 2) is not a solution at all; you can at best use it to form a hypothesis to prove later. $\endgroup$ – Raphael Mar 21 '17 at 19:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.