生成R中向上素数的列表,以一定数目素数、数目、列表

由网友(懞昧僦湜滈興)分享简介:嘿,我试图产生低于1十亿质数的列表。我想这一点,但这种结构是pretty的低劣。有什么建议?A< - 1:10亿D< - 0b将 - 为(i的一个){对于(j在1:ⅰ){如果(!我%% J = 0){D&所述; - C(D,I)}}}解决方案 这是埃拉托色尼的筛的实现算法在研发。筛<...

嘿,我试图产生低于1十亿质数的列表。我想这一点,但这种结构是pretty的低劣。有什么建议?

  A<  -  1:10亿
D<  -  0
b将 - 为(i的一个){对于(j在1:ⅰ){如果(!我%% J = 0){D&所述;  -  C(D,I)}}}
 

解决方案

这是埃拉托色尼的筛的实现算法在研发。

 筛<  - 功能(N)
{
   N'LT;  -  as.integer(N)
   如果(N> 1e6个)站(N过大)
   素数<  - 代表(TRUE,N)
   素数[1];  - 假
   last.prime<  -  2L
   为(在我last.prime:地板(开方(N)))
   {
      素数[seq.int(2L * last.prime,N,last.prime)]<  - 假
      last.prime&所述;  -  last.prime +分钟(其中(素数[(last.prime + 1)中,n]))
   }
   其中(质数)
}

 筛(1000000)
 
delphi列名和所提供值的数目与表定义不匹配 求解

Hey, I'm trying to generate a list of primes below 1 billion. I'm trying this, but this kind of structure is pretty shitty. Any suggestions?

a <- 1:1000000000
d<- 0
b <- for (i in a) {for (j in 1:i) {if (i %% j !=0) {d <- c(d,i)}}}

解决方案

This is an implementation of the Sieve of Eratosthenes algorithm in R.

sieve <- function(n)
{
   n <- as.integer(n)
   if(n > 1e6) stop("n too large")
   primes <- rep(TRUE, n)
   primes[1] <- FALSE
   last.prime <- 2L
   for(i in last.prime:floor(sqrt(n)))
   {
      primes[seq.int(2L*last.prime, n, last.prime)] <- FALSE
      last.prime <- last.prime + min(which(primes[(last.prime+1):n]))
   }
   which(primes)
}

 sieve(1000000)

阅读全文

相关推荐

最新文章