Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

R Programming: Get all prime numbers up to a given number

R Programming: Basic Exercise-6 with Solution

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

Sample Solution :

R Programming Code :

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                         

R Programming Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a R program to get the first 10 Fibonacci numbers.
Next: Write a R program to print the numbers from 1 to 100 and print "Fizz" for multiples of 3, print "Buzz" for multiples of 5, and print "FizzBuzz" for multiples of both.

Test your Programming skills with w3resource's quiz.

What is the difficulty level of this exercise?