Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 55
#defined for positive integers def collatz(n): if n == 1: return 1 elif n%2 == 0: return n/2 else: return 3*n+1
collatz(5)
16
collatz(20)
10
def collatz_iterates(n): print n if n == 1: return None elif n%2 == 0: return collatz_iterates(n/2) else: return collatz_iterates(3*n+1)
def collatz_iterates_with_count(n, count): print count, n if n == 1: return None elif n%2 == 0: return collatz_iterates_with_count(n/2, count+1) else: return collatz_iterates_with_count(3*n+1, count+1)
collatz_iterates_with_count(10, 1)
1 10 2 5 3 16 4 8 5 4 6 2 7 1
collatz_iterates_with_count(173,1)
1 173 2 520 3 260 4 130 5 65 6 196 7 98 8 49 9 148 10 74 11 37 12 112 13 56 14 28 15 14 16 7 17 22 18 11 19 34 20 17 21 52 22 26 23 13 24 40 25 20 26 10 27 5 28 16 29 8 30 4 31 2 32 1
collatz_iterates(10)
10 5 16 8 4 2 1
collatz_iterates(173)
173 520 260 130 65 196 98 49 148 74 37 112 56 28 14 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
3 in L
True
4 in L
False
L=[1,2,3] L.remove(4)
Error in lines 2-2 Traceback (most recent call last): File "/projects/sage/sage-7.5/local/lib/python2.7/site-packages/smc_sagews/sage_server.py", line 982, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> ValueError: list.remove(x): x not in list
#reyurns a list of the pure collatz numbers up to n def collatz_sieve(n): L = [2..n] #result = 2 for x in L: result = collatz(x) while result != 1: if result > x and result in L: L.remove(result) result = collatz(result) return L
collatz_sieve(10)
[2, 3, 6, 7, 9]
collatz_sieve(100)
[2, 3, 6, 7, 9, 12, 15, 18, 19, 21, 24, 25, 27, 30, 33, 36, 37, 39, 42, 43, 45, 48, 51, 54, 55, 57, 60, 63, 66, 69, 72, 73, 75, 78, 79, 81, 84, 87, 90, 93, 96, 97, 99]
#defined for positive integers def collatz(n): if n == 1: return 1 elif n%2 == 0: return n/2 else: return 3*n+1 #returns number of iterations before reaching 1 def number_collatz_iterates(x): count = 0 while x!= 1: #print "{}. {}".format(count,x) x = collatz(x) count = count + 1 #print "{}. {}".format(count,x) return count
number_collatz_iterates(5)
5
number_collatz_iterates(16)
4
#returns inputs where the number of iterations is larger than any previous input largest = 1 for i in [1..10000]: result = number_collatz_iterates(i) if result > largest: print i, result largest = result
3 7 6 8 7 16 9 19 18 20 25 23 27 111 54 112 73 115 97 118 129 121 171 124 231 127 313 130 327 143 649 144 703 170 871 178 1161 181 2223 182 2463 208 2919 216 3711 237 6171 261
L = [3,4,7,9] prod(L)
756
#defined for positive integers def collatz(n): if n == 1: return 1 elif n%2 == 0: return n/2 else: return 3*n+1 #returns number of iterations before reaching 1 def number_collatz_iterates(x): count = 0 while x!= 1: #print "{}. {}".format(count,x) x = collatz(x) count = count + 1 #print "{}. {}".format(count,x) return count
number_collatz_iterates(3^5)
96