Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100755 81 lines (71 sloc) 1.971 kB
a46e025 @benthaman decode and encode messages into numbers
authored
1 #!/usr/bin/python
2
3 import sys
4 import random
5 import itertools
6 from math import sqrt
7
8 class Pfactor(object):
9 def __init__(self):
10 # bah, not implemented
11 self.cache = []
12
13 def __call__(self, x):
14 factorlist = []
15
16 if x == 1:
17 factorlist.append(x)
18 while x % 2 == 0:
19 factorlist.append(2)
20 x /= 2
21 limit = 1 + int(sqrt(x))
22 for factor in range(3, limit, 2):
23 while x % factor == 0:
24 factorlist.append(factor)
25 x /= factor
26 if x > 1:
27 factorlist.append(x)
28
29 return factorlist
30 pfactor = Pfactor()
31
32 if len(sys.argv) != 1 + 1:
33 msg = "What a load of nonsense"
34 else:
35 msg = sys.argv[1]
36 charset_letters = sorted(list(set(msg)))
37 # optional, output different results
38 random.shuffle(charset_letters)
39 modulo = len(charset_letters)
40 while len(pfactor(modulo)) != 1:
41 modulo += 1
42
43 limit = 9999
7725f34 @benthaman comment about limit
authored
44 # The limit is there for two reasons:
45 # * it's in original.py
46 # * I'm not certain that all charset permutations are valid, that would be the
47 # case if the following conjecture is verified:
48 # m is prime, n is part of the natural numbers
49 # there is no i part of the natural numbers and i < m such that
50 # n * m + i is never prime
51 # In this case, n is candidate, m is modulo and i is index
a46e025 @benthaman decode and encode messages into numbers
authored
52 for charset in itertools.permutations(charset_letters):
53 factor = []
54 n = 0
55 for letter in msg:
56 index = charset.index(letter)
57 candidate = n * modulo + index + 1
58 # find the smallest n such that:
59 # factor[i] = n * modulo + index + 1 is prime and
60 # factor[i] > factor[i - 1]
61 while candidate < limit and not (
62 len(pfactor(candidate)) == 1 and (len(factor) == 0 or
63 candidate > factor[-1])):
64 n += 1
65 candidate = n * modulo + index + 1
66
67 if candidate >= limit:
68 continue
69 else:
70 print "factor= %d, %d * %d + %d + 1" % (candidate, n, modulo, index,)
71 factor.append(candidate)
72
73 if candidate >= limit:
74 print "next try"
75 continue
76 else:
77 print modulo
78 print "".join(charset)
79 print reduce(lambda o1, o2: o1 * o2, factor)
80 sys.exit()
Something went wrong with that request. Please try again.