1

I am doing some studying on the collatz conjecture. I spend a while researching and came across the following exercise in R. I tried it for a while, but couldn't get it to work. I figured out how to make one collatz sequence, but dit not come any further than that.

This is the question: Write a function that expects a positive natural number n and returns the longest Collatz sequence generated by any number smaller than or equal to n. The function must also return the length of this Collatz sequence and the starting value of the sequence. To do this, you can put all the to-be-returned objects in a list and return the list

This is how far I came:

collatz_sequence <- function(p) {
    collatz <- vector()
    collatz[1] <- p
    
    i <- 1
    
    while (p > 1) {
        if (p %% 2 == 0) 
            p <- p / 2
        else
            p <- 3 * p + 1
        
        collatz[i+1] <- p
        
        i <- i + 1
        
        length_seq <- length(collatz)
    }
    
    collist <- list(collatz, length(collatz), collatz[1])
        
    return(collist)
}

I would really appreciate the help!

Phil
  • 7,287
  • 3
  • 36
  • 66
  • Welcome to StackOverflow! Please always make sure to wrap code in three backticks (```) and format it nicely to help others help you. I've edited your question as an example for the future. – Benjamin Schmidt Feb 14 '21 at 15:49

0 Answers0