生成R中向上素数的列表,以一定数目 [英] Generate a list of primes in R up to a certain number

查看:165
本文介绍了生成R中向上素数的列表,以一定数目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我试图产生低于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)
 

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)

这篇关于生成R中向上素数的列表,以一定数目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆