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 :

# Define a function 'prime_numbers' that takes a single argument 'n'
prime_numbers <- function(n) {

  # Check if 'n' is greater than or equal to 2
  if (n >= 2) {
    
    # Create a sequence from 2 to 'n'
    x = seq(2, n)
    
    # Initialize an empty vector to store prime numbers
    prime_nums = c()
    
    # Loop through each number in the sequence from 2 to 'n'
    for (i in seq(2, n)) {
      
      # Check if 'i' is in the sequence 'x'
      if (any(x == i)) {
        
        # Add 'i' to the 'prime_nums' vector
        prime_nums = c(prime_nums, i)
        
        # Remove multiples of 'i' from the sequence 'x'
        x = c(x[(x %% i) != 0], i)
      }
    }
    
    # Return the vector of prime numbers
    return(prime_nums)
  }
  else {
    # Stop the function execution and display an error message if 'n' is less than 2
    stop("Input number should be at least 2.")
  }
} 

# Call the 'prime_numbers' function with an argument of 12
prime_numbers(12)

Output:

[1]  2  3  5  7 11                         

Explanation:

  • Define Function: prime_numbers <- function(n) defines a function named prime_numbers that takes a single argument n.
  • Check Input Validity: if (n >= 2) checks if n is at least 2. If not, it stops execution and returns an error message.
  • Initialize Sequence: x = seq(2, n) creates a sequence of integers from 2 to n.
  • Initialize Prime List: prime_nums = c() initializes an empty vector to store prime numbers.
  • Loop Through Numbers: for (i in seq(2, n)) iterates over each number i from 2 to n.
    • Check for Prime: if (any(x == i)) checks if i is still in the sequence x (i.e., it has not been marked as a non-prime).
    • Add to Prime List: prime_nums = c(prime_nums, i) adds i to the prime_nums vector if it is prime.
    • Mark Multiples as Non-Prime: x = c(x[(x %% i) != 0], i) removes all multiples of i from x and retains i.
  • Return Result: return(prime_nums) returns the vector of prime numbers found.
  • Function Call: prime_numbers(12) calls the function with n = 12 to get all prime numbers up to 12.

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?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/r-programming-exercises/basic/r-programming-basic-exercise-6.php