大o符号表示算法的最坏的情况,这与其典型的运行时不同。证明O(1/n)算法是O(1)算法很简单。根据定义,
O (1 / n)——> T (n) & lt; = 1 / n, n > = C > 0
O (1 / n)——> T (n) & lt; = 1 / C,因为1 / n & lt;所有n > = 1 / C = C
O(1/n)——> O(1),因为大O表示法忽略常数(即C的值不重要)
function foo(list input) {
int m;
double output;
m = (1/ input.size) * max_value;
output = 0;
for (int i = 0; i < m; i++)
output+= random(0,1);
return output;
}
def 1_by_n(n, C = 10): #n could be float. C could be any positive number
if n <= 0.0: #If input is actually 0, infinite loop.
while True:
sleep(1) #or pass
return #This line is not needed and is unreachable
delta = 0.0001
itr = delta
while delta < C/n:
itr += delta