Input is an integer n.
First example: a pair of short programs that use the fact that O notation is an upper bound, so a program that is O(1) is also O(n) and O(n^2), etc...
Program 1:
def prog1(n)
1.upto(n) do |i|
end
end
Program 2:
def prog2(n)
return
end
Program 1 is O(n) and program 2 is O(n*n) as well as O(n) and O(1) and O(n^n^n^n^n).
Yet program 2 is faster than program 1.
Second example: A pair of programs that use the fact that O notation depends on behavior as n gets big.
Program 1: same as before
Program 2:
def prog2(n)
if n < 10^100
return
else
1.upto(n) do |i|
1.upto(n) do |j|
end
end
end
end
Program 1 is O(n) and program 2 is O(n*n).
Yet program 2 is faster than program until n >= 10^100.