-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp14.R
More file actions
87 lines (74 loc) · 1.46 KB
/
Copy pathp14.R
File metadata and controls
87 lines (74 loc) · 1.46 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#main
# [1] 837799
# user system elapsed
# 8.597 0.006 8.607
# > main2()
# [1] 837799
# user system elapsed
# 13.162 0.038 13.206
main <- function(){
pmt <- proc.time()
num <- 1e6
x <- integer(num)
x[1] <- 1
for(i in 2:num){
#print(i)
n <- i
terms <- 0
repeat{
if(n<i){
x[i] <- x[n]+terms
break
}
if(n%%2==0){
n <- n/2
}else{
n <- 3*n + 1
}
terms <- terms+1
}
}
print(which(x==max(x)))
print(proc.time()-pmt)
}
main2 <- function(){
pmt <- proc.time()
num <- 1e6
x <- integer(num)
x[1] <- 1
for(i in seq(3,1e6,2)){
#print(i)
n <- i
terms <- 0
repeat{
#print(n)
#print(x[n])
if(!is.na(x[n])){
if(x[n]!=0){
x[i] <- x[n]+terms
break
}
}
if(n%%2==0){
n <- n/2
}else{
n <- 3*n + 1
}
terms <- terms+1
}
}
print(which(x==max(x)))
print(proc.time()-pmt)
}
collatz <- function(n){
terms <- 1
repeat{
if(n==1){return(terms)}
if(n%%2==0){
n <- n/2
}else{
n <- 3*n + 1
}
terms <- terms+1
}
}