Skip to content

Instantly share code, notes, and snippets.

@WinstonCampeau
Created January 15, 2019 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WinstonCampeau/f61eb1b97ce463f87e0d3c08a4ebab4d to your computer and use it in GitHub Desktop.
Save WinstonCampeau/f61eb1b97ce463f87e0d3c08a4ebab4d to your computer and use it in GitHub Desktop.
Collatz in R
#Collatz Conjecture
#Will produce graph and number of steps to converge to 1
collatz <- function(start_val, show_me) {
if(missing(show_me)){
show_me <- start_val
}
n <- start_val
comp <- c()
j <- 0
for(i in 1:n){
steps <- 0
j <- j + 1
while(i!=1) {
#print(n)
if(i%%2 == 0){
i <- i/2
} else i <- (3*i) + 1
steps <- steps + 1
}
comp[j] <- steps
}
numbers <- c(1:n)
plot(comp~numbers, xlab="Starting Number", ylab="Steps", pch=19, col="blue", cex=0.2)
paste(show_me, "took", comp[show_me], "steps to converge to 1")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment