R Program to Check Prime Number

Example to check whether an integer (entered by the user) is a prime number or not using control statements.

To understand this example, you should have the knowledge of the following R programming topics:

A positive integer greater than 1 which has no other factors except 1 and the number itself is called a prime number.

Numbers 2, 3, 5, 7, 11, 13 etc. are prime numbers as they do not have any other factors.

But, 6 is not prime (it is composite) since, 2 x 3 = 6.

Example: Check Prime Number

# Program to check if the input number is prime or not

# take input from the user
num = as.integer(readline(prompt="Enter a number: "))

flag = 0
# prime numbers are greater than 1
if(num > 1) {
    # check for factors
    flag = 1
    for(i in 2:(num-1)) {
        if ((num %% i) == 0) {
            flag = 0

if(num == 2)    flag = 1
if(flag == 1) {
    print(paste(num,"is a prime number"))
} else {
    print(paste(num,"is not a prime number"))

Output 1

Enter a number: 25
[1] "25 is not a prime number"

Output 2

Enter a number: 19
[1] "19 is a prime number"

Here, we take an integer from the user and check whether it is prime or not. Numbers less than or equal to 1 are not prime numbers.

Hence, we only proceed if the num is greater than 1. We check if num is exactly divisible by any number from 2 to num - 1.

If we find a factor in that range, the number is not prime. Else the number is prime.

We can decrease the range of numbers where we look for factors.

In the above program, our search range is from 2 to num - 1.

We could have used the range, [2, num / 2] or [2, num ** 0.5]. The later range is based on the fact that a composite number must have a factor less than square root of that number. Otherwise the number is prime.

Did you find this article helpful?