Collatz Conjecture
SAP Community Coding Challenge - 2
The Collatz conjecture is a conjecture in mathematics that concerns a sequence defined as follows: start with any positive integer n. Then each term is obtained from the previous term as follows:
-
If the previous term is even, the next term is one half of the previous term.
-
If the previous term is odd, the next term is 3 times the previous term plus 1.
The conjecture is that no matter what value of n, the sequence will always reach 1.More Details
Actual conding challange can be seen here
Altough I don’t see any practical applications to the Collatz Conjecture. Let’s see, what this conjecture offers.
Collatz Conjecture is given by,
\(f(n) =
\begin{cases}
n/2, & \text{if $n$ is even} \\[2ex]
3n+1, & \text{if $n$ is odd}
\end{cases}\)
I have written the code in python as well, to actually visualize the data which is provided by Conjecture. Python has libraries which makes the plotting of 2D graph much easier.
import matplotlib.pyplot as plt
import numpy as np
def collatze(i):
count = 0
while i > 1:
if i % 2 == 0:
i = i // 2
else:
i = (3 * i) + 1
count = count + 1
return count
limit = 1000
y = np.zeros(limit, dtype=int)
x = np.arange(limit, dtype=int)
for n in x:
y[n] = collatze(x[n])
fig, ax = plt.subplots()
ax.plot(x, y, '.', ms=4)
plt.show()
Presents a beautiful output
Code in Javascript
See the Pen Collatz Conjecture by Gaurav Chaudhary (@zgaur) on CodePen.
Happy Learning!