Time complexity of integer comparison in python

烈酒焚心 提交于 2020-01-04 02:13:04

问题


What is the time complexity of integer comparison in Python for very large integers? For example, if we calculate factorial of 1000 using 2 functions, then check equality, is it O(1)?

def fact(n):
    prod = 1
    for i in range(n):
        prod = prod * (i + 1)
    return prod

i = fact(1000)
j = fact(1000)

# Complexity of this check?
if i == j:
    print "Equal"

回答1:


There isn't a simple answer, but the answer is nevertheless obvious ;-)

That is, if two integers are in fact equal, it's impossible to know that without comparing all their bits. So in case of equality, the time needed is proportional to the number of bits (which is proportional to log(abs(N)) if N is one of the comparands).

If they're not in fact equal, there are several cases, all related to implementation internals. Long ints are stored as a vector of "digits" in a power-of-2 base. If the vectors don't have the same lengths, then the ints aren't equal, and that takes constant time.

But if they do have the same lengths, then the "digits" have to be compared until finding the first (if any) mismatching pair. That takes time proportional to the number of digits that need to be compared.

Then complicate all the above to account for possible mixtures of signs.



来源:https://stackoverflow.com/questions/44061735/time-complexity-of-integer-comparison-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!