【问题标题】:How to find GCD of n with integers smaller than n in R如何在R中找到小于n的整数的n的GCD
【发布时间】:2023-04-04 21:14:01
【问题描述】:

我试图找到所有小于“n”的整数的整数“n”的 GCD。例如,如果 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?提前谢谢你!!

【问题讨论】:

  • n = 6 的预期输出是多少?
  • GCD 为 6 和 1,2,3,4,5 分别为 1,2,3,2,1

标签: r for-loop while-loop greatest-common-divisor


【解决方案1】:

我无法很好地遵循您的尝试,因此无法快速确定出错的位置,但您肯定需要启动一个向量来存储结果并将结果附加到循环的每次迭代中。

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 创建

【讨论】:

  • 谢谢,有帮助!! @Marcelo Avila
  • 太棒了。如果它解决了您的问题,请考虑接受答案(左侧有一个复选标记,旁边是向上和向下投票按钮)
猜你喜欢
  • 2012-01-06
  • 1970-01-01
  • 2015-06-07
  • 2012-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
相关资源
最近更新 更多