Skip to content

Instantly share code, notes, and snippets.

@zyuiop
Created November 10, 2016 18:24
Show Gist options
  • Save zyuiop/a2154b6615a9ff10bd0f53fc0f458136 to your computer and use it in GitHub Desktop.
Save zyuiop/a2154b6615a9ff10bd0f53fc0f458136 to your computer and use it in GitHub Desktop.
I really thought I had found an incredible algorithm for better multiplication times. It's not the case so I think I underevaluated the time of an instruction somewhere :D
import random, math, time
def multiply(n, k):
result = 0
if k & 1 == 1:
result = n
for i in range(1, math.ceil(math.log(k, 2))): # log(k)
if (k >> i) & 1 == 1: # O(1) shift
result = result + (n << (i)) # O(log(n)) [summation] + O(1) [shift]
return result # O(log(n) ^2) (better than O(n) ?)
def test(n, k):
begin = time.time()
classic = n * k
classicTime = time.time() - begin
begin = time.time()
custom = multiply(n,k)
customTime = time.time() - begin
print(n,k,n*k, multiply(n,k), (classicTime * 1e6), (customTime * 1e6))
for i in range(1, 10):
test(random.randrange(1, 1e100), random.randrange(1, 1e100))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment