我有一个问题:构造一个所有小于1000的孪生素数的列表。
到目前为止,我的代码是:
isPrime <- function (n ) n==2L || all (n %% 2L:max (2, floor(sqrt(n)))!=0)我很难构建真正的清单,有什么建议吗?
发布于 2018-10-22 12:35:59
您可以使用sapply命令获取素数,然后使用diff函数对
(谢谢Rui指出sapply比lapply更适合这里!)
testThese <- 1:1000
primes <- testThese[sapply(testThese,isPrime)]
pairs.temp <- which(diff(primes)==2)
pairs <- sort(c(pairs.temp, pairs.temp+1))
matrix(primes[pairs], ncol=2, byrow=TRUE)
[,1] [,2]
[1,] 3 5
[2,] 5 7
[3,] 11 13
[4,] 17 19
[5,] 29 31
... ... ...发布于 2018-10-22 13:23:58
下面是一个使用埃拉托斯提尼筛的解决方案
E <- rep(TRUE, 1000)
E[1] <- FALSE
for (i in 2:33) {
if (!E[i]) next
E[seq(i+i, 1000, i)] <- FALSE
}
P <- which(E) ## primes
pp <- which(diff(P)==2) ## index of the first twin
cbind(P[pp], P[pp+1]) ## the twins如果您需要一个函数isPrime(),您可以:
isPrime <- function(i) E[i]
isPrime(c(1,2,4,5)) ## Test发布于 2018-10-22 12:37:32
下面是如何使用您的函数构造一个素数列表(虽然不是很有效):
primes_list <- vector(length = 0, mode = "integer")
for (i in 1:1000) {
if (isPrime(i)) primes_list <- c(primes_list, i)
}你应该可以把它扩展到处理孪生素数。
https://stackoverflow.com/questions/52929423
复制相似问题