Created
January 15, 2019 17:14
-
-
Save WinstonCampeau/f61eb1b97ce463f87e0d3c08a4ebab4d to your computer and use it in GitHub Desktop.
Collatz in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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