-
Notifications
You must be signed in to change notification settings - Fork 0
/
Nikhilam Navatascaramam Dastah Part 4.py
105 lines (85 loc) · 2.92 KB
/
Nikhilam Navatascaramam Dastah Part 4.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import math
import operator
def is_tenth_power(n):
if n <= 0:
return False
while n % 10 == 0:
n //= 10
if n == 1:
return True
else:
return False
def main(num1, num2):
# First priority conditions:
# 1. If any number is equal to 0, return 0
# 2. If any number is equal to 1, return the other number
# 3. If both numbers are less than equal to 5, use the multiple table
if num1 == 0 or num2 == 0:
return 0
if num1 == 1:
return num2
elif num2 == 1:
return num1
if num1 <= 5 and num2 <= 5:
return multiple_table[num1][num2]
# Average between the 2 highest places
# The -1 as the second parameter in round rounds like this: 42->40, 56->60
base = int(round((num1 + num2) / 2, -1))
if base == 0:
return 'Formula Not Applicable'
if num1 < base:
# Part 1 method
right1 = base - num1
sign1 = operator.sub
else:
# Part 2 method
right1 = num1 - base
sign1 = operator.add
if num2 < base:
# Part 1 method
right2 = base - num2
sign2 = operator.sub
else:
# Part 2 method
right2 = num2 - base
sign2 = operator.add
right_ans = main(right1, right2)
left_ans = sign2(num1, right2)
if right_ans == 'Formula Not Applicable':
return right_ans
# If something DOESN'T fully fall under part 1, then multiply the extra thing
if not (is_tenth_power(base) and {sign1, sign2} == {operator.sub}):
left_ans = main(left_ans, int(base / 10))
if left_ans == 'Formula Not Applicable':
return left_ans
# Checks if sign1 and sign 2 are different
if {sign1, sign2} == {operator.add, operator.sub}:
# String manipulation is slower, so we mathematically carry over
# Subtract all but last digit
left_ans -= math.floor(right_ans / 10)
# Cut the right answer to be just the last digit
right_ans = int(str(right_ans)[-1])
if not right_ans == 0:
left_ans -= 1
right_ans = 10 - right_ans
elif {sign1, sign2} == {operator.sub}:
# Carrying
if (right_ans >= 10 and is_tenth_power(base) is False) or (num1 < 10 and num2 < 10):
left_ans += math.floor(right_ans / 10)
right_ans = int(str(right_ans)[-1])
zeros = len(str(base)) - 1
while len(str(right_ans)) < zeros:
right_ans = '0' + str(right_ans)
else:
# Carrying
left_ans += math.floor(right_ans / 10)
right_ans = int(str(right_ans)[-1])
return int(str(left_ans) + str(right_ans))
# Hard-coded 5x5 multiplication table
multiple_table = [[0, 0, 0, 0, 0, 0],
[0, 1, 2, 3, 4, 5],
[0, 2, 4, 6, 8, 10],
[0, 3, 6, 9, 12, 15],
[0, 4, 8, 12, 16, 20],
[0, 5, 10, 15, 20, 25],
]