R Program to check prime number

How to check the given number is a prime number or not

Here we are explaining how to write an R program to take number from the user and check it is a prime number or not. 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. A positive integer greater than 1 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.

How prime number check is implemented in R Program

We are using readline() function for taking the user's input. Given below are the steps which are used in the R program to read value for prime check. In this R program, we accept the user's values into num by providing an appropriate message to the user using 'prompt'. 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 find a factor in that range then set flag=0 otherwise flag=1. Print the message as a number is a prime number if the flag=1 otherwise the number is not prime.

ALGORITHM

STEP 1: prompting appropriate messages to the user

STEP 2: take user input using readline() into variables num

STEP 3: set flag=0 at first 

STEP 4:check if the num is greater than 1 or not if yes set flag=1

STEP 5:check if num is exactly divisible by any number from 2 to num – 1 

STEP 6:If we find a factor in that range set flag=0

STEP 7:if flag=1 print number is a prime number

STEP 8:else if flag=0 print number is not a prime number

R Source Code

                                          num = as.integer(readline(prompt = "Enter a number: "))
flag = 0
if (num > 1) {
    flag = 1
    for (i in 2: (num - 1)) {
        if ((num %% i) == 0) {
            flag = 0
            break
        }
    }
}
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

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

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