The code below creates a function that produces a plot of the number of iterations taken for the Collatz function (3x + 1) to reach 1 against each ascending integer
CollatzLoop <- function(x, n){
vector2 <- c()
for(x in 1:n){
vector <- c()
for(i in 1:1000){
if (x == 1){
vector <- c(vector, x)
break
} else {
if (x %% 2 == 0){
vector <- c(vector, x)
x <- x/2
} else {
vector <- c(vector, x)
x <- 3*x + 1
}
}
}
vector2 <- c(vector2, length(vector))
}
vector3 <- c(1:n)
plot(vector3, vector2, xlab = "Value of n", ylab = "Iterations to reach 1")
}
The following example provides the plot for the first 500 integers:
CollatzLoop(x, n = 500)