As part of personal studies, I was leaning how to build R packages and deploy through Github. Essentially, as a practice exercise, I wanted to model the famous Collatz conjucture and visualize the plot for various random numbers.
The problem
Consider an arbitrary positive integer n:
- If n is even, divide it by 2.
- Else, if n is odd, multiply it by 3 and add 1 to the product.
Therefore, we can define a function fi(n) such that:
\( f(n) = \begin{cases} n/2 & \text{if } n \equiv 0 \mod 2, \\ 3n+1 & \text{if } n \equiv 1 \mod 2. \end{cases} \)
Subsequently, we need to loop the above equation sequencially by taking the result at the previous step as the starting value at the next such that:
\( k_i = \begin{cases}
n & \text{for } i = 0, \\
f(k_{i-1}) & \text{for } i > 0
\end{cases} \)
The conjecture states that this process will eventually reach the number 1, regardless of which arbitrary positive integer is chosen as the starting (initial) value n. Once the process reaches unity, a perpetual loop is reached: 4,3,2,1,4,3,2,1... Therefore, we stop the loop once we reach 1.
Currently, the highest arbitrary integer that has been officially proven to concur with this behaviour is 2100,000 - 1. Can this 3n + 1 hold for bigger integers beyond this?
Usage
Generate hailstone sequences
You can now generate the hailstone sequences of any arbitrary integer between 1 - 21024. To do this, simply type collatz_sequence()
and input your integer inside the parentheses and run it. For instance, if I want to see the Collatz sequence for 123456789, i would:
collatz_sequence(3732423)
Visualize the plot
To view the plot for this number:
visualize_collatz(3732423)
How many steps or stopping times are there for this number before reaching 1?
collatz(3732423)
#alternatively:
collatz_sequence(3732423)$step
Identify the maximum value in the sequence:
max_collatz(3732423)
#alternatively:
collatz_sequence(3732423)$max_value
Other operations
The CollatzR package can also perform operations such as:
-
Determining if a number is odd or even:
is.even(3732423)
-
Determining if a number is whole:
is.wholenumber(3732423)
Happy interacting with the tool!