Advertisement
Guest User

FRACTRAN Prime Machine

a guest
Mar 29th, 2017
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.16 KB | None | 0 0
  1. from fractions import Fraction
  2. from math import log
  3.  
  4. # 1/log(2) calculated because multiplicaiton is more efficient than division
  5. ILOG2 = 1.0/log(2)
  6. log2 = lambda x: log(x)*ILOG2
  7.  
  8. # Returns true if num is a power of 2
  9. def isPowerOfTwo(num):
  10.     return not num == 0 and ((num & (num - 1)) == 0)
  11.  
  12. # John Conway's FRACTRAN prime machine
  13. tape = [
  14.     Fraction(17,91),
  15.     Fraction(78,85),
  16.     Fraction(19,51),
  17.     Fraction(23,38),
  18.     Fraction(29,33),
  19.     Fraction(77,29),
  20.     Fraction(95,23),
  21.     Fraction(77,19),
  22.     Fraction(1,17),
  23.     Fraction(11,13),
  24.     Fraction(13,11),
  25.     Fraction(15,14),
  26.     Fraction(15,2),
  27.     Fraction(55,1)
  28. ]
  29.  
  30. # Interpret a FRACTRAN program
  31. def interpret(tape, n):
  32.     index, output = 0, []
  33.     while index < len(tape):
  34.         # Print the next prime if we have it
  35.         if isPowerOfTwo(n) and n not in output:
  36.             output.append(n)
  37.             print log2(n)
  38.  
  39.         # See if we get an integer, otherwise move on
  40.         lens = n*tape[index]
  41.         if (lens.denominator == 1):
  42.             n, index = lens.numerator, 0
  43.         else:
  44.             index += 1
  45.  
  46. if __name__ == "__main__":
  47.     interpret(tape, 2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement