Reputation: 25
How to find GCD for a list of (1:n) numbers in R ?
GCD=function(a, b){
m=min(a, b)
while(a%%m>0|b%%m>0){m=m-1}
return(m)}
Here is my code to find GCD for two integers, how can I modify it to find GCD for a list of numbers from 1 to n without too much changes on my original code? Thankyou very much !
Upvotes: 0
Views: 663
Reputation: 102261
You can define function gcd
based on GCD
like below
gcd <- function(...) Reduce(GCD,list(...))
and you can try
> gcd(6, 24, 28, 36, 200)
[1] 2
If you want a recursion for GCD
(your origin answer has a slow convergence due to m <- m -1
), you can try
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]))
}
such that
> GCD(6, 24, 28, 36, 200)
[1] 2
> GCD(12, 24, 28, 36, 200)
[1] 4
Upvotes: 2
Reputation: 10771
You can use the any
function:
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
Upvotes: 2