What does “in constant time” imply?

后端 未结 8 1325
梦谈多话
梦谈多话 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).

    0 讨论(0)
  • 2021-01-30 18:00

    "Constant time" has the same meaning as "O(1)", which doesn't mean that an algorithm runs in a fixed amount of time, it just means that it isn't proportional to the length/size/magnitude of the input. i.e., for any input, it can be computed in the same amount of time (even if that amount of time is really long).

    0 讨论(0)
提交回复
热议问题