# Function to find all prime numbers up to a specified number using the Sieve of Eratosthenes
sieve_of_eratosthenes <- function(n) {
if (n < 2) {
cat("No prime numbers in the specified range.\n")
return()
is_prime <- rep(TRUE, n)
is_prime[1] <- FALSE # 1 is not prime
p <- 2
while (p^2 <= n) {
if (is_prime[p]) {
for (i in seq(p^2, n + 1, by = p)){
is_prime[i] <- FALSE
p <- p + 1
primes <- which(is_prime)
cat("Prime numbers up to", n, "are:\n", primes, "\n")
# Input a number from the user
n <- [Link](readline("Enter a positive integer: "))
sieve_of_eratosthenes(n)
Explanation:
In mathematics, the sieve of Eratosthenes is an ancient algorithm for finding
all prime numbers up to any given limit.
It does so by iteratively marking as composite (i.e., not prime) the multiples of
each prime, starting with the first prime number, 2.
The multiples of a given prime are generated as a sequence of numbers starting
from that prime, with constant difference between them that is equal to that prime.
This is the sieve's key distinction from using trial division to sequentially test
each candidate number for divisibility by each prime.
Once all the multiples of each discovered prime have been marked as composites,
the remaining unmarked numbers are primes.