collatz <- function(raw_x, max_iter) { stopifnot("Length of x must be 1" = length(raw_x) == 1) x <- as.integer(raw_x) stopifnot("Cannot interprete x as integer" = !is.na(x)) sequ <- c(x) len <- NA for (n in (1:(max_iter-1))) { if (x == 1) { len <- n break } else if (x %% 2 == 0) { x <- x / 2 } else { x <- 3*x+1 } sequ <- c(sequ, x) } return(list(seq=sequ, len=len)) } str(collatz(1, 1e4)) ## List of 2 ## $ seq: int 1 ## $ len: int 1 str(collatz(2, 1e4)) ## List of 2 ## $ seq: int [1:2] 2 1 ## $ len: int 2 str(collatz(3, 1e4)) ## List of 2 ## $ seq: int [1:8] 3 10 5 16 8 4 2 1 ## $ len: int 8 str(collatz(3, 5)) ## List of 2 ## $ seq: int [1:5] 3 10 5 16 8 str(collatz("4", 1e4)) ## List of 2 ## $ seq: int [1:3] 4 2 1 ## $ len: int 3 str(collatz("four", 1e4)) ## Warning in collatz("four", 10000): NAs introduced by coercion ## Error in collatz("four", 10000): Cannot interprete x as integer str(collatz(1:5, 1e4)) ## Error in collatz(1:5, 10000): Length of x must be 1 str(collatz(5.0, 1e4)) ## List of 2 ## $ seq: int [1:6] 5 16 8 4 2 1 ## $ len: int 6 str(collatz(5.1, 1e4)) ## List of 2 ## $ seq: int [1:6] 5 16 8 4 2 1 ## $ len: int 6 str(collatz(5.9, 1e4)) ## List of 2 ## $ seq: int [1:6] 5 16 8 4 2 1 ## $ len: int 6