-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path01-gen_collatz.R
54 lines (42 loc) · 976 Bytes
/
01-gen_collatz.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
library(tidyverse)
library(tibble)
# Create gen_collatz function --------------------------------------------------
gen_collatz <- function(n) {
if (!is.integer(n) || n <= 0) {
stop("Input must be a positive integer")
}
seq <- c(n)
while (n != 1) {
if (n %% 2 == 0) {
n <- n / 2
} else {
n <- 3 * n + 1
}
seq <- c(seq, n)
}
return(seq)
}
# Create collatz_df tibble -----------------------------------------------------
start <- 1:10000
seq <- list()
for (i in start) {
collatz_seq <- gen_collatz(i)
seq[[i]] <- collatz_seq
}
length <- double()
for (i in start) {
length[i] <- length(gen_collatz(i))
}
parity <- ifelse(start %% 2 == 0,
"Even",
"Odd")
max_val <- double()
for (i in start) {
max_val[i] <- max(gen_collatz(i))
}
collatz_df <- tibble(start,
seq,
length,
parity,
max_val)
collatz_df