I have been learning functional programming and I come to idea, to assemble mathematical operators.
counting -> addition -> multiplication -> power -> ... Naturally came out simple and most naive code to express this and it works! Problem is that I really have no idea why it works so well and whit such large outputs.
question is:
What is complexity of this function?
Code is in python:
def operator(d):
if d<=1:
return lambda x,y:x+y
else:
return lambda x,y:reduce(operator(d-1),(x for i in xrange(y)))
#test
f1 = operator(1) #f1 is adition
print("f1",f1(50,52)) #50+52
f2 = operator(2) #f2 is multiplication
print("f2",f2(2,20)) #2*20
f3 = operator(3) #f3 is power, just look how long output can be
print("f3",f3(4,100)) #4**100
f4 = operator(4) #f4 is superpower, this one does not work that well
print("f4",f4(2,6)) #((((2**2)**2)**2)**2)**2
f5 = operator(5) #f5 do not ask about this one,
print("f5",f5(2,4)) #
output (instantly):
('f1', 102)
('f2', 40)
('f3', 1606938044258990275541962092341162602522202993782792835301376L)
('f4', 4294967296L)
('f5', 32317006071311007300714876688669951960444102669715484032130345427524655138867890893197201411522913463688717960921898019494119559150490921095088152386448283120630877367300996091750197750389652106796057638384067568276792218642619756161838094338476170470581645852036305042887575891541065808607552399123930385521914333389668342420684974786564569494856176035326322058077805659331026192708460314150258592864177116725943603718461857357598351152301645904403697613233287231227125684710820209725157101726931323469678542580656697935045997268352998638215525166389437335543602135433229604645318478604952148193555853611059596230656L)
The disassembly tells you that no magic optimizations have been applied here, it’s really just a reduce over a genexpr. Python just seems to be up to this task, even if it surprises you.
If you specifically look at your
f5(2,4)call, it doesn’t perform so many operations, actually:65k additions, let alone the 297 for the exponentiation, are not even worth speaking of when it comes to hilariously optimized modern CPUs, so it’s no wonder that this finishes in the blink of an eye. Try increasing one of the arguments to see how this hits the border of quick evaluation very rapidly.
By the way,
operatoris a built-in module and you shouldn’t name your own functions like that.