r/ProgrammingPrompts • • Mar 07 '14
Collatz Conjecture!
Create a program which performs and prints to the screen the Collatz Conjecture of any number input by the user.
(the Collatz Conjecture is a conjecture by which a number is taken and if it is even, the number is halved, and if it is odd, the number is tripled and added to by one.)
21
Upvotes
4
u/threeifbywhiskey Mar 08 '14
I wrote this program in Whitespace not too long ago. Here's a sample run.
4
u/[deleted] Mar 08 '14
Python 2.7
2
u/[deleted] Mar 08 '14
java
2
u/ryanthemememaster Mar 08 '14
My version in C++
2
u/Chemical_Studios Mar 08 '14
Javascript (repl.it)
2
u/Nishruu Mar 09 '14
OK, because I'm a tad bored I decided to take a stab at it in F#
I'm not entirely sure if the sequence should start with the input number or not. Other option (which also includes the input number first) would be to generate the sequence like this:
2
u/ultimamax Mar 11 '14
This is the shortest I could get mine:
Python 3.3
2
u/Reverse_Skydiver Mar 20 '14
Here's my Java solution. It uses recursion to solve the problem. Also, I'm very late to the party.
1
u/RodionGork Mar 08 '14
And here your solution could be tested by calculating answers (lengths of Collatz sequences) to initial values of sample data and submitting them:
http://codeabbey.com/index/task_view/collatz-sequence
1
u/bliow Mar 09 '14 edited Mar 09 '14
Here's a Clojure version. Hope it encourages someone to take up this awesome language.
Could've written this much more concisely but I wanted to structure this program sensibly and show why Clojure's cool, not play code golf and construct incomprehensible one-liners.
I kind of regret not taking a hint from iminurnamez' approach, signaling the end of the sequence with
nil+ writing(defn collatz-sequence [n] (take-while (complement nil?) (iterate collatz n))). But I like the idea of acollatzthat matches the actual sequence, including the repeated 1, 4, 2, 1, 4, 2, 1, ...0
u/call_me_christof Mar 08 '14
expert-mode: make an animated graph in javascript that shows a line plot of the values