-->

Thursday, January 23, 2014

Python Collatz Conjecture Script

One of my current ongoing projects is to teach myself to code in Python. While I have been going through the lessons in Learn Python the Hard Way, (I've been on lesson 23 for a few weeks now), I have been on the lookout for things to code with Python.

Then, the Collatz Conjecture popped up on my Google Plus feed...

The Conjecture states that for any natural number:

  • If even, divide by 2.
  • If odd, multiply by 3 and add 1.
  • Repeat these steps until you end up with 1. 
The conjecture states that as long as you are using a natural number, you will eventually end up with the number one.

Sounds like a good thing to practice coding with. Here's what I've got:

i = 0
x = int(raw_input("Please input a number> "))

while x != 1:
 i = i + 1
 if x % 2 == 0:
  x = x/2
  print "%d> %d" % (i, x)
 elif x != 1:
  x = 3 * x + 1
  print "%d> %d" % (i, x)
 else:
  print "%d> %d" % (i, x)
For every step, it prints out the step number and the current number. Example output:

Please input a number> 94
1> 47
2> 142
3> 71
4> 214
5> 107
6> 322
7> 161
8> 484
9> 242
10> 121
11> 364
12> 182
13> 91
14> 274
15> 137
16> 412
17> 206
18> 103
19> 310
20> 155
21> 466
22> 233
23> 700
24> 350
25> 175
26> 526
27> 263
28> 790
29> 395
30> 1186
31> 593
32> 1780
33> 890
34> 445
35> 1336
36> 668
37> 334
38> 167
39> 502
40> 251
41> 754
42> 377
43> 1132
44> 566
45> 283
46> 850
47> 425
48> 1276
49> 638
50> 319
51> 958
52> 479
53> 1438
54> 719
55> 2158
56> 1079
57> 3238
58> 1619
59> 4858
60> 2429
61> 7288
62> 3644
63> 1822
64> 911
65> 2734
66> 1367
67> 4102
68> 2051
69> 6154
70> 3077
71> 9232
72> 4616
73> 2308
74> 1154
75> 577
76> 1732
77> 866
78> 433
79> 1300
80> 650
81> 325
82> 976
83> 488
84> 244
85> 122
86> 61
87> 184
88> 92
89> 46
90> 23
91> 70
92> 35
93> 106
94> 53
95> 160
96> 80
97> 40
98> 20
99> 10
100> 5
101> 16
102> 8
103> 4
104> 2
105> 1

No comments:

Post a Comment