1

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!

Joe
  • 337
  • 6
  • 21
  • 2
    The number never equals 1. The sequence as defined is 20, 10, 5, 0.3125, ... You can check by adding `message(tempVar); Sys.sleep(0.5)` in the loop. – Roland Oct 16 '19 at 12:57
  • @Roland Hmm... I see now. Also, realised that instead of `n/(3n+1)` it should be `3n+1`. Thanks for spotting that! – Joe Oct 16 '19 at 13:01

2 Answers2

1

Fixing the definition in the question as per https://en.wikipedia.org/wiki/Collatz_conjecture and improving the code we have:

collatzSeq<-function(n) {
  N <- n
  while(n != 1) {
    n <- if (n %% 2 == 0) n/2 else 3*n + 1
    N <- c(N, n)
  }
  N
}

collatzSeq(20)
## [1] 20 10  5 16  8  4  2  1
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

Turns out that I have misread the definition. Odd numbers get replaced by 3n+1 not n/(3n+1). The rest works fine.

Joe
  • 337
  • 6
  • 21