简体   繁体   中英

I am trying to create a Collatz sequence with while loop in R. What am i doing wrong in this while loop here?

I am trying to create a Collatz sequence with while loop in R.

vector <-  NULL
n <- 10
while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- (n * 3) + 1
  }
  vector <- c(vector, cbind(n))
  print(vector)
}

After running the code, I got:

[1] 5
[1]  5 16
[1]  5 16  8
[1]  5 16  8  4
[1]  5 16  8  4  2
[1]  5 16  8  4  2  1

How do I do it such that it only shows the last row? What went wrong in my code? Thanks for any help on this.

You have several ways to deal with print(vector)

  • add if condition before print(vector) , ie,
vector <-  NULL
n <- 10
while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- (n * 3) + 1
  }
  vector <- c(vector, cbind(n))
  if (n==1)  print(vector)
}
  • move it outside while loop, ie,
vector <-  NULL
n <- 10
while (n != 1) {
  if (n %% 2 == 0) {
    n <- n / 2
  } else {
    n <- (n * 3) + 1
  }
  vector <- c(vector, cbind(n))
}
print(vector)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM