I am interested in creating a function that would provide a length of a Colatz sequence. To do that I am using a repeat function to go through the sequence. However, it seems that the repeat function does not stop calculating values.
What is a Collatz sequence
Collatz sequence takes a number (call it n) and checks whether it is even or odd. If it is even, then the number is divided by 2 (n<-n/2). If it is odd, then the number is divided by 3n+1 (n<-(3n+1)). It ends when the number equals to 1 ( when n=1).
Initially, I thought that the repeat function does not work simply because of the floatation/integer issue. So I've added isTRUE(all.equal(...)) as advised here. That did not solve a problem.
I suppose that the error is in my logic then. However, I cannot find it.
Code
colatzSeq<-function(n){
  tempVar<-n
  count<-1
  repeat{
    if(isTRUE(all.equal(tempVar%%2,0))){
      tempVar<-tempVar/2
    }else{
      if(isTRUE(all.equal(tempVar,1))){
        tempVar<-1
      }else{
      tempVar<-tempVar/(3*tempVar+1)
      }
    }
    count<-count+1
    if(isTRUE(all.equal(tempVar,1))){
      print(count)
      break
    }
  }
}
The code supposed to return a number of items in a sequence. For example, colatzSeq(20) should return 8 (meaning it took 7 times to change the number 20 to get to 1 according to the Collatz sequence).
As mentioned above, there is no error. Just infinite division.
Thanks!
 
    