John Roecroft
John Roecroft

Reputation: 23

Trying to write code to list primes up to n

I'm not the best at R but have to write up code that lists all the primes up to 10,000. Earlier we had to calculate whether a number is prime or not and I did that the way they asked like this:

n <- 4
prime <- TRUE

for (i in 2:floor(n^0.5)){
  if(n %% i == 0) {prime <- FALSE} 
  if(n == 2) {prime <- TRUE}
  if(n == 3) {prime <- TRUE}
}

prime

But my code to add them into a list, just doesn't work although it should do in my somewhat illogical mind...

pvec<-c(2,3)
prime<- TRUE

for (i in 4:100){
  for (y in 2:i-1){
    if (i %% y == 0) {prime <- FALSE} 
    if (prime == FALSE) break
    else{pvec<- c(pvec, i)}
  }
}

pvec
prime

Any help would be much appreciated. (Also, I know there must be other ways, but the way I'm after must link somehow to the first prime test part).

Upvotes: 0

Views: 76

Answers (1)

Pierre L
Pierre L

Reputation: 28441

Wrap your process in a function. Then iterate with sapply or a for loop. Also consider vectorizing your code to eliminate the need for a loop:

prime_func <- function(n) {

prime <- TRUE

for (i in 2:floor(n^0.5)){
  if(n %% i == 0) {prime <- FALSE} 
  if(n == 2) {prime <- TRUE}
  if(n == 3) {prime <- TRUE}
}

prime

}

pvec<-c(2,3)
sapply(pvec, prime_func)
#[1] TRUE TRUE

Upvotes: 1

Related Questions