【问题标题】:Determine if a number is prime. If not, print the factors of the number判断一个数是否为素数。如果不是,打印数字的因数
【发布时间】:2023-02-02 04:35:26
【问题描述】:

我编写了一个 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 的非素数因子。 谢谢

【问题讨论】:

  • 我建议你可以找到更多信息即刻通过进行更有针对性的搜索。例如,StackOverflow [r] prime factors 本身就很有特色,甚至 Google "r" "prime" "factor" 也有一些其他关于这个问题的好博客/帖子/问答。

标签: r


【解决方案1】:

你的代码:

  • 既然你想在报告它不是质数时返回数字的所有因子,你不应该在 printing for 循环内;
  • 寻找其他因素的内循环应该不是从 1 开始,因为这总是一个因素;理想情况下,它应该从 i+1 开始,因为您已经知道 2:(i-1)不是因素。
  • 同样,在 for 循环中,您永远不应该报告它“是质数”,因为...您还没有完成 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

【讨论】:

    猜你喜欢
    • 2011-05-24
    • 2017-03-05
    • 2010-12-05
    • 2016-02-10
    • 1970-01-01
    • 2015-02-08
    • 2016-01-25
    相关资源
    最近更新 更多