Joe
Joe

Reputation: 379

Repeat function does not stop in R

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!

Upvotes: 1

Views: 172

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 269556

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

Upvotes: 1

Joe
Joe

Reputation: 379

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

Upvotes: 0

Related Questions