@simontiger/

BigNumber Class for Python

Python

No description

fork
loading
Files
  • main.py
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import time

secs = 0
start_time = time.time()

def seconds():
  secs = time.time() - start_time
  return secs

def eval_performance(func, acuraccy, show_done=True):
  avg = 0
  per = acuraccy/100
  for i in range(acuraccy):
    now = seconds()
    func()
    avg += seconds() - now
    if i % per == 0 and show_done:
      print(str((i*100) // acuraccy) + "% done")
  avg /= acuraccy
  return avg

class BigNumber:
  def __init__(self, string):
    self.string = str(string)
  
  def __repr__(self): return self.string
  def __str__(self): return self.string
  def __add__(self, other): return self.add(other)
  def __sub__(self, other): return self.sub(other)
  def __mul__(self, other): return self.mul(other)

  def digits(self):
    return [int(i) for i in str(self)]
  
  def add(self, other):
    digits1 = self.digits()
    digits2 = other.digits()
    length = max(len(digits1), len(digits2)) + 1
    while len(digits1) < length: digits1 = [0] + digits1
    while len(digits2) < length: digits2 = [0] + digits2
    answer = [0 for i in range(length)]
    carry = [0 for i in range(length)]

    for i in range(length-1, -1, -1):
      answer[i] = digits1[i] + digits2[i] + carry[i]
      if answer[i] >= 10:
        answer[i] -= 10
        if i > 0: carry[i-1] += 1
        else: answer[i-1] += 1
    
    finalAnswer = ""
    for i in answer: finalAnswer += str(i)
    return BigNumber(finalAnswer)
  
  # TODO: Fix if the second number is bigger than the first
  def sub(self, other):
    digits1 = self.digits()
    digits2 = other.digits()
    length = max(len(digits1), len(digits2))
    while len(digits1) < length: digits1 = [0] + digits1
    while len(digits2) < length: digits2 = [0] + digits2
    answer = [0 for i in range(length+1)]
    carry = [0 for i in range(length)]

    for i in range(length-1, -1, -1):
      answer[i+1] = digits1[i] - digits2[i] + carry[i]
      if answer[i+1] < 0:
        answer[i+1] += 10
        if i > 0: carry[i-1] -= 1
        else: answer[i] = "-"
    
    finalAnswer = ""
    for i in answer: finalAnswer += str(i)
    return BigNumber(finalAnswer)
  
  #def mul(self, other):
  #  digits1 = self.digits()
  #  digits2 = other.digits()

print(eval_performance(lambda: BigNumber(2) + BigNumber(2), 10000000, True))