用循环1测试素数:sqrt(x)

时间:2019-04-04 18:38:52

标签: r loops

我正在学习循环,我有这段代码可以检查数字是否为质数,但是不起作用。错误在哪里?

x <- 7
y <- seq(1,sqrt(x),by=1)
for(i in 1: sqrt(x)){
 if(y[x%%y == 0]) {
   print("FALSE")
 }else{
   print("TRUE")
 }
}

这为我提供了正确的解决方案,但它会重复回答i中元素数量的次数。我也想问一下如何在for if中使用函数:

i <- c(1: sqrt(x))
y3 <- x%%i == 0
y4 <- y3[-1] 
for(value in i){
  if(y4 == FALSE) {
    print("TRUE")
  }else{
    print("FALSE")
  }
}

版本3,为我提供了解决方案,但针对i中的evey元素:

x <- 107
i <- c(1: sqrt(x))
y3 <- c(x%%i == 0)
y4 <- y3[-1] 
for(value in i){
  if(all(y4==F)) {
    print("TRUE")
  }else{
    print("FALSE")
  }
}

2 个答案:

答案 0 :(得分:0)

您可以这样做-

check_prime <- function(num) {
    if (num == 2) {
        TRUE
    } else if (any(num %% 2:(num-1) == 0)) {
        FALSE
    } else { 
        TRUE
    }
}

> check_prime(7)
[1] TRUE

答案 1 :(得分:0)

由于您提到必须使用循环,因此以下代码将起作用:

x <- 7
y <- seq(1, ceiling(sqrt(x)), by=1)

# is.factor is a vector which checks whether each element in y is a factor or not
# initialize to F
is.factor = F

# Start at y = 2 because 1 will be a factor
for(i in 2:length(y) ){

  # Check whether current value in vector is a factor of x or not
  # if not a factor, set value in index to F, otherwise set to T 
  ifelse( x%%y[i] != 0, is.factor[i] <- F, is.factor[i] <- T)

  # If we are at the last element in y, print a result
  if(i == length(y)){

    # check if we have any factors. 
    # if we have any factors (i.e. any index in is.factor vector is T), then number is not prime
    ifelse( any(is.factor), print("FALSE"), print("TRUE") ) 
  }

}