Q:

Write a R program to get all prime numbers up to a given number (based on the sieve of Eratosthenes)

0

Write a R program to get all prime numbers up to a given number (based on the sieve of Eratosthenes).

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

prime_numbers <- function(n) {
if (n >= 2) {
 x = seq(2, n)
 prime_nums = c()
 for (i in seq(2, n)) {
 if (any(x == i)) {
 prime_nums = c(prime_nums, i)
 x = c(x[(x %% i) != 0], i)
 }
 }
 return(prime_nums)
 }
 else 
 {
 stop("Input number should be at least 2.")
 }
 } 
prime_numbers(12)

Sample Output:

[1]  2  3  5  7 11

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now