Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from fractions import Fraction
- from math import log
- # 1/log(2) calculated because multiplicaiton is more efficient than division
- ILOG2 = 1.0/log(2)
- log2 = lambda x: log(x)*ILOG2
- # Returns true if num is a power of 2
- def isPowerOfTwo(num):
- return not num == 0 and ((num & (num - 1)) == 0)
- # John Conway's FRACTRAN prime machine
- tape = [
- Fraction(17,91),
- Fraction(78,85),
- Fraction(19,51),
- Fraction(23,38),
- Fraction(29,33),
- Fraction(77,29),
- Fraction(95,23),
- Fraction(77,19),
- Fraction(1,17),
- Fraction(11,13),
- Fraction(13,11),
- Fraction(15,14),
- Fraction(15,2),
- Fraction(55,1)
- ]
- # Interpret a FRACTRAN program
- def interpret(tape, n):
- index, output = 0, []
- while index < len(tape):
- # Print the next prime if we have it
- if isPowerOfTwo(n) and n not in output:
- output.append(n)
- print log2(n)
- # See if we get an integer, otherwise move on
- lens = n*tape[index]
- if (lens.denominator == 1):
- n, index = lens.numerator, 0
- else:
- index += 1
- if __name__ == "__main__":
- interpret(tape, 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement