In: Computer Science
A twin prime is a pair of primes (x, y), such that y = x + 2. Construct a list of all twin primes less than 1000. The result should be stored in a list of numeric vectors called twin_primes, whose elements are the twin primes pairs. Print the length of the list twin_primes and print the 10th and the 15th elements of the list, i.e. twin_primes[[10]] and twin_primes[[15]].
Please use R-code.
SOLUTION -
CODE -
TwinPrimesLong = function(n) {
if (n < 5) stop("Input value of n should be at least 5.")
primesLessThanN = Eratosthenes(n)
#Combine differenced sets with original prime set
twin_Prime = cbind( (primesLessThanN-2) ,primesLessThanN)
#Keep only those rows where differenced numbers are also primes
i.e. belong to prime set
twin_Prime = data.frame(matrix(twin_Prime[(primesLessThanN-2) %in%
primesLessThanN,],ncol=2))
colnames(twin_Prime)=c("TwinPrime1","TwinPrime2")
cat("The twin primes less than n = ",n,"in row form are :\n")
cat(paste0("(",twin_Prime[,1],",",twin_Prime[,2],")",collapse=","),"\n")
cat("\n\nThe twin primes less than n = ",n,"in table form are :\n")
print(twin_Prime)
}
TwinPrimesShort = function(n) {
if (n < 5) stop("Input value of n should be at least 5.")
primesLessThanN = Eratosthenes(n)
#Use diff function to compute difference with previous value and
check if == 2
TwinPrime1 = primesLessThanN[diff(primesLessThanN)==2]
TwinPrime2 = TwinPrime1 + 2
#Keep only those rows where differenced numbers are also primes
i.e. belong to prime set
twin_Prime =
data.frame(TwinPrime1=TwinPrime1,TwinPrime2=TwinPrime2)
cat("The twin primes less than n = ",n,"in row form are :\n")
cat(paste0("(",twin_Prime[,1],",",twin_Prime[,2],")",collapse=","),"\n")
cat("\n\nThe twin primes less than n = ",n,"in table form are :\n")
print(twin_Prime)
}
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I WILL
SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------