In: Computer Science
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) Write a function that returns all prime numbers between 1 and a given number n Answer :
prime<-function(n)
{
cat("Prime numbers are between 1 and ",n ,"\n")
for(i in 1:n)
{
c=0
for(j in 1:i)
{
if(i%%j==0)
{
c=c+1;
}
}
if(c==2)
{
cat(i)
cat("\n")
}
}
}
prime(100) #change the value here
Output:
(b) How many prime numbers are there in the range [1, 100], [1, 1000] and [1, 10000]
prime<-function(n)
{
count=0
for(i in 1:n)
{
c=0
for(j in 1:i)
{
if(i%%j==0)
{
c=c+1;
}
}
if(c==2)
{
count=count+1;
}
}
cat("\nThe total Prime numbers are ",count," between 1 and
",n)
}
prime(100) #change the value
prime(1000)
out put :
(c) How many twin prime pairs are there in the range [1, 100], [1, 1000] and [1, 10000]
twinprime <- function(n1,n2)
{
count=0;
cat("The twin Prime numbers are:\n")
for(n1 in 1:n2)
{
x<-n1+2
if(Checkprime(n1) && Checkprime(x))
{
count=count+1
cat(n1," ",x)
cat("\n")
}
}
cat("The total Twin Prime numbers are ",count," between 1 and
",n2)
}
Checkprime <- function(n)
{
f=0
for(i in 1:n)
{
if(n%%i==0)
f<-f+1
}
if(f==2)
TRUE
else
FALSE
}
twinprime(1,100) #change the value here
output :
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).
In number theory, the Prime Number Theorem (PNT) describes the asymptotic distribution of the prime numbers among the positive integers.
the first such distribution found is π(n) ~ n / log(n), where π(n) is the prime-counting function and log(n) is the natural logarithm of n.