What does “in constant time” imply?

后端 未结 8 1323
梦谈多话
梦谈多话 2021-01-30 17:21

I work as a programmer, but have no computer science background, so recently I\'ve been following along with the excellent MIT OpenCourseWare intro to Computer Science and Progr

8条回答
  •  一生所求
    2021-01-30 17:58

    "In constant time" means that no matter what the input is, the program will not run longer than a known amount of time.

    Consider the factorial function as a counterexample. The factorial of, say, 5 is calculated like:

    5! = 5 * 4 * 3 * 2 * 1 = 120
    

    This will obviously take less time to compute than the factorial of 10 because to do the latter, the program has to do five more multiplications:

    10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1
    

    So, "constant time" does not mean that we know how long the program will run in each case but that it will never run longer than a known amount of time (the upper bound).

提交回复
热议问题