Debian Codegraph @

etc/additionchain.py

raw symbols SCIP
1 #!/usr/bin/python3
2 # The purpose of this file is to assist with reverse-engineering addition
3 # chains from imperative code. One would find an implementation with a good
4 # addition chain, translate the code to python (vim macros are your friends),
5 # and replace the middle section of this file with the addition chain. This
6 # script prints back-indices in the format that AdditionChainExponentiation.v
7 # accepts.
8
9 values = [1]
10 chain = []
11
12 def mul(x,y):
13 i = values.index(x)
14 j = values.index(y)
15 assert values[i] + values[j] == x+y
16 chain.insert(0, (i, j))
17 values.insert(0, x+y)
18 return x+y
19
20 def sqr(x):
21 return mul(x,x)
22
23 ### ==== cut here ==== ###
24
25 z = 1
26 z2 = sqr(z) # 2
27 t1 = sqr(z2) # 4
28 t0 = sqr(t1) # 8
29 z9 = mul(t0, z) # 9
30 z11 = mul(z9, z2) # 11
31 t0 = sqr(z11) # 22
32 z2_5_0 = mul(t0, z9) # 2^5 - 2^0 = 31 = 22 + 9
33
34 t0 = sqr(z2_5_0) # 2^6 - 2^1
35 t1 = sqr(t0) # 2^7 - 2^2
36 t0 = sqr(t1) # 2^8 - 2^3
37 t1 = sqr(t0) # 2^9 - 2^4
38 t0 = sqr(t1) # 2^10 - 2^5
39 z2_10_0 = mul(t0, z2_5_0) # 2^10 - 2^0
40
41 t0 = sqr(z2_10_0) # 2^11 - 2^1
42 t1 = sqr(t0) # 2^12 - 2^2
43 for i in range(2, 10, 2): # 2^20 - 2^10
44 t0 = sqr(t1)
45 t1 = sqr(t0)
46 z2_20_0 = mul(t1, z2_10_0) # 2^20 - 2^0
47
48 t0 = sqr(z2_20_0) # 2^21 - 2^1
49 t1 = sqr(t0) # 2^22 - 2^1
50 for i in range(2, 20, 2): # 2^40 - 2^20
51 t0 = sqr(t1)
52 t1 = sqr(t0)
53 z2_40_0 = mul(t1, z2_20_0) # 2^40 - 2^0
54
55 t0 = sqr(z2_40_0) # 2^41 - 2^1
56 t1 = sqr(t0) # 2^42 - 2^2
57 for i in range(2, 10, 2): # 2^50 - 2^10
58 t0 = sqr(t1)
59 t1 = sqr(t0)
60 z2_50_0 = mul(t1, z2_10_0) # 2^50 - 2^0
61
62 t0 = sqr(z2_50_0) # 2^51 - 2^1
63 t1 = sqr(t0) # 2^52 - 2^2
64 for i in range(2, 50, 2): # 2^100 - 2^50
65 t0 = sqr(t1)
66 t1 = sqr(t0)
67 z2_100_0 = mul(t1, z2_50_0) # 2^100 - 2^0
68
69 t0 = sqr(z2_100_0) # 2^101 - 2^1
70 t1 = sqr(t0) # 2^102 - 2^2
71 for i in range(2, 100, 2): # 2^200 - 2^100
72 t0 = sqr(t1)
73 t1 = sqr(t0)
74 z2_200_0 = mul(t1, z2_100_0) # 2^200 - 2^0
75
76 t0 = sqr(z2_200_0) # 2^201 - 2^1
77 t1 = sqr(t0) # 2^202 - 2^2
78 for i in range(2, 50, 2): # 2^250 - 2^50
79 t0 = sqr(t1)
80 t1 = sqr(t0)
81 t0 = mul(t1, z2_50_0) # 2^250 - 2^0
82
83 t1 = sqr(t0) # 2^251 - 2^1
84 t0 = sqr(t1) # 2^252 - 2^2
85 t1 = sqr(t0) # 2^253 - 2^3
86 t0 = sqr(t1) # 2^254 - 2^4
87 t1 = sqr(t0) # 2^255 - 2^5
88 t0 = mul(t1, z11) # 2^255 - 21
89
90 ### ==== cut here ==== ###
91
92 print (list(reversed(chain)))