如何在R中找到小于n的整数的n的GCD

How to find GCD of n with integers smaller than n in R

我试图找到整数“n”的 GCD,所有整数都小于“n”。例如,如果 n=6 ,我找到 6 和 1,2,3,4,5 的 GCD。这是我找到 2 个整数的 GCD 的代码:

y=function(a,b){
m=min(a,b)
while(a%%m>0|b%%m>0){m=m-1}
return(m)}

我尝试使用下面的代码,但它只显示第一个答案。

y=function(a){
m=a
for(i in 1:a){
while(a%%m>0|i%%m>0){m=m-1}
return(m)}

如何修改我的代码以获得 GCD?提前谢谢你!!

我不能很好地理解你的尝试,所以我不能快速查明哪里出了问题,但你肯定需要启动一个向量来存储结果并将结果附加到循环的每次迭代中。

names 位只是为了结果的可读性,并非绝对必要。

get_gcd <- function(a, b) {
  m <- min(a,b)
  while(a %% m>0 | b %% m>0) {
    m <- m-1
  }
  return(m)
}

get_vec_of_gcd <- function(a) {
  # initiate vector for results 
  res <- rep(NA, length(a))
  for (i in 1:a) {
    res[i] <- get_gcd(a, i)
    # names just for better output interpretability 
    names(res)[i] <- paste(i, a, sep = ":")
  }
  res
}
get_vec_of_gcd(10)
#>  1:10  2:10  3:10  4:10  5:10  6:10  7:10  8:10  9:10 10:10 
#>     1     2     1     2     5     2     1     2     1    10

reprex package (v1.0.0)

于 2021-03-25 创建