R (460 자)
R을 사용하는 다른 버전.
"input"파일에서 읽고 "output"파일로 출력
d=as.list(as.integer(scan("input","",sep="\n")));n=36;f=rep(1,n);for(i in 3:n){f[i]=f[i-2]+f[i-1]};d2=lapply(d,function(x){a=vector("integer");i=1;while(x>0){id=which(f>=x)[1];if(x==f[id]){x=x-f[id];a[i]=f[id]}else{x=x-f[id-1];a[i]=f[id-1]}i=i+1}a});d=mapply(c,d,d2,SIMPLIFY=0);for(i in 1:length(d)){t=d[[i]];l=length(t);if(l==1){d[[i]]=paste(t[1],t[1],sep=": ")}else{d[[i]]=paste(t[1],": ",paste(t[2:l],collapse="+"),sep="")}}lapply(d,write,"output",append=1)
"입력"예
0
47
3788
1646
25347
677
343
3434
"출력"예
0: 0
47: 34+13
3788: 2584+987+144+55+13+5
1646: 1597+34+13+2
25347: 17711+6765+610+233+21+5+2
677: 610+55+8+3+1
343: 233+89+21
3434: 2584+610+233+5+2
더 읽기 쉬운 버전 :
dt <- as.list(as.integer(scan(file = "input", what = "", sep = "\n")))
n <- 36
fib <- rep(1, n)
for(i in 3:n){fib[i] <- fib[i-2] + fib[i-1]}
dt2 <- lapply(dt, function(x){answ <- vector(mode = "integer")
i <- 1
while(x > 0){
idx <- which(fib>=x)[1]
if(x == fib[idx]){
x <- x - fib[idx]
answ[i] <- fib[idx]
}
else {
x <- x - fib[idx-1]
answ[i] <- fib[idx-1]
}
i <- i + 1
}
answ})
dt <- mapply(FUN = c, dt, dt2, SIMPLIFY = FALSE)
for(i in 1:length(dt)){
t1 <- dt[[i]]
t1.len <- length(t1)
if(t1.len == 1){
dt[[i]] <- paste(t1[1], t1[1], sep=": ")
} else {
dt[[i]] <- paste(t1[1], ": ", paste(t1[2:t1.len], collapse = "+"), sep="")
}
}
lapply(dt, write, "output", append=TRUE)