R 中小于 87 的双素数

Twin primes less than 87 in R

我正在尝试列出前 87 个孪生素数。我正在使用 Eratosthenes 方法。这是我到目前为止所做的工作

Eratosthenes <- function(n) {
  # Return all prime numbers up to n (based on the sieve of Eratosthenes)
  if (n >= 2) {
    sieve <- seq(2, n) # initialize sieve
    primes <- c() # initialize primes vector
    for (i in seq(2, n)) {
      if (any(sieve == i)) { # check if i is in the sieve
        primes <- c(primes, i) # if so, add i to primes
        sieve <- sieve[(sieve %% i) != 0] # remove multiples of i from sieve
      }
    }
    return(primes)
  } else {
    stop("Input value of n should be at least 2.")
  }
}

Era <- c(Eratosthenes(87))
i <- 2:86

for (i in Era){
  if (Era[i]+2 == Era[i+1]){
    print(c(Era[i], Era[i+1]))
  }
}

我不明白的第一件事是这个错误:

Error in if (Era[i] + 2 == Era[i + 1]) { : 
  missing value where TRUE/FALSE needed

第二件事是列表中缺少孪生素数,例如 (29,31)

首先,(23,29)不是孪生素数

其次,您的答案可能会在here

中找到

编辑:我试过你的代码,我发现 Era 的长度是 23。

可能当运行 if (Era[i] + 2 == Era[i+1])时,它达到24并导致问题。

for (i in Era) 会将 i 设置为 2,然后是 3,然后是 5 等等,这不是您想要的。使用 for (i in seq_len(length(Era) - 1)).

for (i in seq_len(length(Era) - 1)){
  if (Era[i] + 2 == Era[i + 1]){
    print(c(Era[i], Era[i + 1]))
  }
}
#> [1] 3 5
#> [1] 5 7
#> [1] 11 13
#> [1] 17 19
#> [1] 29 31
#> [1] 41 43
#> [1] 59 61
#> [1] 71 73

在您的 for 循环中,i 不再是索引,而是 Era 中的元素。这种情况下可以尝试用(i+2) %in% Era判断i+2是不是双胞胎

for (i in Era){
  if ((i+2) %in% Era){
    print(c(i,i+2))
  }
}

这给出了

[1] 3 5
[1] 5 7
[1] 11 13
[1] 17 19
[1] 29 31
[1] 41 43
[1] 59 61
[1] 71 73

更简单的方法可能是使用 diff,例如,

i <- Era[c(diff(Era)==2,FALSE)]
print(cbind(i,j = i+2))

这给出了

> print(cbind(i,j = i+2))
      i  j
[1,]  3  5
[2,]  5  7
[3,] 11 13
[4,] 17 19
[5,] 29 31
[6,] 41 43
[7,] 59 61
[8,] 71 73