(From Ch. 4 ‘More in Depth’)
(Note that 1 -> 4 -> 2 -> 1 …, cycling forever.)
No matter what positive number you start with, the Collatz procedure will eventually get you back to 1.
This simple conjecture has never been proven or disproven!
Some numbers take a surprisingly long time to get down to 1, and they often have an exciting journey along the way.
collatz <- function(n, limit = 10000) {
# collatz numbers will go in this vector
numbers <- numeric(limit)
# keep count of how many numbers we have made:
counter <- 0
while ( n > 1 & counter < limit) {
# need to make a new number
counter <- counter + 1
# put the current number into the vector
numbers[counter] <- n
# make next Collatz number
n <- collatzRule(n)
}
# find how many Collatz numbers we made:
howMany <- min(counter, limit)
# print them out:
print(numbers[1:howMany])
}
collatz <- function(n, limit = 10000) {
numbers <- numeric(limit)
counter <- 0
while ( n > 1 & counter < limit) {
counter <- counter + 1
numbers[counter] <- n
n <- collatzRule(n)
}
howMany <- min(counter, limit)
cat("The Collatz sequence has ", howMany, " elements.\n", sep = "")
show <- readline("Do you want to see it (y/n)? ")
if ( show == "y" ) {
print(numbers[1:howMany])
}
}
collatz <- function(n, limit = 10000) {
# record initial number because we will change n
initial <- n
numbers <- numeric(limit)
counter <- 0
while ( n > 1 & counter < limit) {
counter <- counter + 1
numbers[counter] <- n
n <- collatzRule(n)
}
howMany <- min(counter, limit)
steps <- 1:howMany
cat("The Collatz sequence has ", howMany, " elements.\n", sep = "")
show <- readline("Do you want to see it (y/n)? ")
if ( show == "y" ) {
print(numbers[steps])
}
# use initial value to make plot title:
plotTitle <- paste0("Collatz Sequence for n = ", initial)
# make the plot
ggplot(mapping = aes(x = steps, y = numbers[steps])) +
geom_point() + geom_line() +
labs( x = "Step", y = "Collatz Value at Step",
title = plotTitle)
}