如何求 R 中 (1:n) 数字列表的 GCD?
GCD=function(a, b){
m=min(a, b)
while(a%%m>0|b%%m>0){m=m-1}
return(m)}
这是我查找两个整数的 GCD 的代码,如何修改它以查找从 1 到 n 的数字列表的 GCD,而不需要对原始代码进行太多更改? 非常感谢!
您可以使用
any
功能:
GCD <- function(x) {
m = min(x)
while (any(x %% m > 0)){
m = m - 1
}
return(m)
}
GCD(c(12, 24, 28, 36, 200))
# [1] 4
GCD(c(6, 24, 28, 36, 200))
# [1] 2
您可以基于
gcd
定义函数 GCD
,如下所示
gcd <- function(...) Reduce(GCD,list(...))
你可以尝试
> gcd(6, 24, 28, 36, 200)
[1] 2
如果你想要
GCD
的递归,你可以尝试
GCD <- function(...) {
args <- c(...)
if (length(args) == 2) {
if (args[2] == 0) {
return(args[1])
} else {
return(Recall(args[2], args[1] %% args[2]))
}
}
Recall(args[1], Recall(args[-1]))
}
这样
> GCD(6, 24, 28, 36, 200)
[1] 2
> GCD(12, 24, 28, 36, 200)
[1] 4