Here is the complete R code for the given task. I have added comments for a better understanding of the code.
# Prompt the user for input:
pmpt = "Please enter a number to check if it is prime:"
number = as.integer(readline(prompt=pmpt))
isPrime = 0
if(number > 1) {
isPrime = 1
for(i in 2:(number-1)) {
# if there is a factor then the number is not prime
if ((number %% i) == 0) {
isPrime = 0
break
}
}
}
# if the number is 2
if(number == 2) isPrime = 1
if(isPrime == 1) {
# The number is a prime number
print(paste(number ,"is prime!"))
} else {
# The number is not a prime number
print(paste(number,"is not prime!"))
}
Screenshot of the code:
Sample Output:
Input: 5
Output:
You can comment below the answer, for any doubts, and I will be happy to help!
Please give a thumbs up if my answer could be of help!
All the best!
Get Answers For Free
Most questions answered within 1 hours.