The Prime number is an integer with no other positive divisors other than 1 and that number itself. All other numbers except the prime numbers are Composite numbers. For example, 2, 3, 5, 7, 11, 13, etc are prime numbers because they have only 2 divisors, and the number '4', '6', which have more than two divisors are composite numbers.
Note: The number '1' is not a prime number as it has only one divisor.
Given below are the steps for checking a number is a prime.
In this R program, we accept the user's value into num by providing an appropriate message to the user using 'prompt
'. We can use the readline()
function to take input from the user (terminal). Here the prompt
argument can choose to display an appropriate message for the user. Check the given number is greater than 1 because prime numbers must be greater than one. Check if num is exactly divisible by any number from 2 to num – 1 and if find a factor in that range then set isPrime = 0 otherwise isPrime = 1. Print the message as the number is a prime number if the isPrime == 1 otherwise the number is not prime.
STEP 1: Accept user input using readline()
into variable num
STEP 2: Set isPrime = 0 at first
STEP 3: Check if the num is greater than 1, if yes do steps 4,5
STEP 4: Set isPrime = 1
STEP 5: Start a for loop
from 2 to num – 1 and check if num is exactly divisible by any number,
STEP 5.1: If we find a factor in that range then reset isPrime = 0 and break
from loop
STEP 6: If num is 2 then set isPrime =1
STEP 7: Check if isPrime == 1 then print
the number is a prime number, else print
the number is not a prime number
num = as.integer(readline(prompt = "Enter a number: "))
# num = 15
isPrime = 0
if (num > 1) {
isPrime = 1
for (i in 2: (num - 1)) {
if ((num %% i) == 0) {
isPrime = 0
break
}
}
}
if (num == 2) isPrime = 1
if (isPrime == 1) {
print(paste(num, "is a prime number"))
} else {
print(paste(num, "is not a prime number"))
}
Enter a number: 15 [1] "15 is not a prime number" Enter a number: 13 [1] "13 is a prime number"