Problem 3 Write code in R or Rstudio (Programming)
A prime number is an integer greater than one whose only factors are one and itself. For example, the first ten prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23 and 29. A twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes. For example, the five twin prime pairs are (3, 5), (5, 7), (11, 13), (17, 19) and (29, 31). (a) Write a function that returns all prime numbers between 1 and a given number n Answer: (b) How many prime numbers are there in the range [1, 100], [1, 1000] and [1, 10000] (c) How many twin prime pairs are there in the range [1, 100], [1, 1000] and [1, 10000] (d) In number theory, the prime number theorem (PNT) indicates that for a large enough n, the number of primes in the range [1, n] approximates to n/log(n). Please verify it by trying wider range.
a)
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.")
}
}
num <- as.integer(readline(prompt="Enter a number:"))
prime_numbers(num)
b)
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(length(prime_nums))
}
else
{
stop("Input number should be at least 2.")
}
}
prime_numbers(100)
prime_numbers(1000)
prime_numbers(10000)
c)
Get Answers For Free
Most questions answered within 1 hours.