Advertisement
rdrewd

problem14_nocache.py

May 27th, 2013
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.30 KB | None | 0 0
  1. #! `env python` -t
  2. def seq(n):
  3.     """
  4.    Generate the sequence for Project Euler problem 14.
  5.    ===================================================
  6.  
  7.    n is a positive integer that is the first number in the sequence.
  8.  
  9.    I'm told that although it hasn't been proven, that it is believed that
  10.    regardless of the starting number, the sequence eventually gets to 1,
  11.    which is where we stop.
  12.             1         2          3         4         5         6         7         8
  13.    123456789012345678901234567989012345678901234567890123456789012345678901234567890
  14.    """
  15.  
  16.     while True:
  17.         if n % 2 == 0:
  18.             next=n/2
  19.         else:
  20.             next=3*n+1
  21.         yield n
  22.         if n == 1:
  23.             return
  24.         n=next
  25.  
  26. # end seq
  27.  
  28.  
  29. def runlen(n):
  30.     """
  31.    runlen returns the length of the sequence
  32.    generated by seq(n)
  33.    """
  34.  
  35.     count=0
  36.     for s in seq(n):
  37.         count += 1
  38.     # end "for s"
  39.     return count
  40. #end runlen
  41.  
  42. def main():
  43.     longest=0
  44.     basis=0
  45.     for i in xrange(1, 1000000):
  46.         r=runlen(i)
  47.         if r > longest:
  48.             basis=i
  49.             longest=r
  50.         # print 'runlen(', i,')=', runlen(i)
  51.         #   end "for i"
  52.     print "longest=", longest,\
  53.         "generated from", basis
  54.     return basis
  55. # end main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement