r program to get all prime no upto a given number
- User
r program to get all prime no upto a given number
- Assistant
Here is an R program to find all prime numbers up to a given number:
is_prime <- function(n) { if (n <= 1) return(FALSE) for (i in 2:sqrt(n)) { if (n %% i == 0) return(FALSE) } return(TRUE) } get_primes <- function(n) { primes <- c() for (i in 2:n) { if (is_prime(i)) primes <- c(primes, i) } return(primes) } # Example usage number <- 50 primes <- get_primes(number) print(primes)In the above code, the
is_primefunction tests whether a given numbernis prime or not. It uses a simple algorithm to check ifnis divisible by any number from 2 to the square root ofn. If it finds any divisor, it is not prime.The
get_primesfunction takes an inputnand gets all prime numbers up ton. It iterates through all numbers from 2 ton, and if a number is prime, it adds it to theprimesvector. Finally, it returns theprimesvector containing all prime numbers.In the example usage, the code finds all prime numbers up to 50 and prints them. You can modify the
numbervariable to any positive integer to find prime numbers up to that number.