lhs = "1234728" rhs = "38910" def carry(l): output = [] cval = 0 for x in l[::-1]: v = x+cval output.insert(0,v%10) if v > 9: cval = v/10 else: cval = 0 while cval > 0: output.insert(0,cval%10) cval /= 10 return output def add(l, r): if len(l) < len(r): while len(l) < len(r): l.insert(0,0) else: while len(r) < len(l): r.insert(0,0) result = [0]*len(l) for i in enumerate(l): i = i[0] result[i] = l[i] + r[i] return carry(result) def mult(l, r): isNegative = False # Yes there's a more elegant way to handle this # Thanks for asking if l[0] == "-": #Negative isNegative = True l = l[1:] if r[0] == "-": isNegative = False r = r[1:] elif r[0] == "-": isNegative = True r = r[1:] if len(l) < len(r): # Trivial loop optimization t = l r = l l = r results = [] p = 0 for c in r[::-1]: # Reverse iterate over the smaller number out = [] for d in l[::-1]: out.insert(0,int(c)*int(d)) out += [0] * p out = carry(out) results.append(out) p += 1 final = [] for x in results: final = add(final,x) return ''.join([str(x) for x in final]) print mult(lhs, rhs) print str(int(lhs)*int(rhs))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question