R Program to check prime number


February 4, 2023, Learn eTutorial
5834

What are prime numbers and composite numbers?

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. 

check prime number

Note:  The number '1' is not a prime number as it has only one divisor.

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

Given below are the steps for checking a number is a prime.

  1. Accept a number from the user.
  2. Find all factors of that number. The integers that could divide a number completely will be a factor of that number.
  3. If the number of factors is more than 2, then the input number is not prime otherwise it is a prime number.  

How to write an R program for checking the number is 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.

ALGORITHM

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

R Source Code

                                          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"))
}
                                      

OUTPUT

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

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