R语言 判断一个数是否是质数,如果不是,打印该数的因子

r1wp621o  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(154)

我写了一个R函数来检查一个数x是否是质数。如果不是,就打印这个数的因子。在代码中,除了打印一个非质数的因子外,一切似乎都很好。我尝试了很多技巧,但都不起作用。我需要帮助。

prime = function(x){
   if(x>1){
      for(i in 2:(x/2+1)){
         if(x%%i==0){
            print(paste(x,"is not a prime number"))
            print(paste("The factors of",x,"are:"))
            for (j in 1:(x+1)){
               if(x%%j==0){
                  print(paste(j,""))
               break
               }
            }
         }else{
            print(paste(x, "is a prime number"))
            break
         }
      }   
   }else{
      print(paste("Enter value is that is greater than 1"))
   }
}

当我调用这个函数时,它给出了下面的输出

> prime(0)
[1] "Enter value is that is greater than 1"
> prime(19)
[1] "19 is a prime number"
> prime(4)
[1] "4 is not a prime number"
[1] "The factors of 4 are:"
[1] "1 "
[1] "4 is a prime number"

一切正常,但我无法打印不是素数的x的因子。谢谢

vltsax25

vltsax251#

验证码:

  • 因为当你报告这个数不是质数的时候,你想要返回这个数的所有因子,所以你不应该在for循环中使用print;
  • 你寻找其他因子的内部循环不应该从1开始,因为它总是一个因子;理想情况下,它应该从i+1开始,因为您已经知道2:(i-1)不是因子。
  • 同样,在for循环中,你永远不应该报告它"是一个质数",因为......你还没有完成for循环,因此不知道你是否已经穷尽了可能的因子的完整列表。

我建议使用矢量化操作,而不是for循环。

isprime <- function(x) {
  stopifnot("Value must be greater than 1" = x > 1)
  nums <- seq_len(ceiling(x / 2))
  factors <- setdiff(nums[x %% nums == 0], c(1, x))
  if (length(factors)) {
    message(x, " is not a prime, factors are: ", toString(factors))
  } else message(x, " is a prime")
  invisible(!length(factors) > 0)
}

演示:

isprime(1)
# Error in isprime(1) : Value must be greater than 1
isprime(7)
# 7 is a prime
isprime(60)
# 60 is not a prime, factors are: 2, 3, 4, 5, 6, 10, 12, 15, 20, 30

如果您必须使用for循环,并且需要报告数字的所有因子,那么我建议将已知因子附加到向量,并在for循环之外检查其长度以进行报告。

isprime_for <- function(x) {
  factors <- integer(0)
  if (x > 1) {
    for (i in 2:floor(x / 2)) {
      if (x %% i == 0) factors <- c(factors, i)
    }
  } else stop("value must be greater than 1")
  if (length(factors) > 0) {
    message(x, " is not a prime, factors are: ", toString(factors))
  } else {
    message(x, " is a prime")
  }
  length(factors) == 0L
}

演示

isprime_for(1)
# Error in isprime_for(1) : value must be greater than 1
isprime_for(7)
# 7 is a prime
# [1] TRUE
isprime_for(20)
# 20 is not a prime, factors are: 2, 4, 5, 10
# [1] FALSE

相关问题