Learn R Online
 Home            

R Program to check Prime Number

In this example you will learn how to check if a number is prime or composite in R Programming. You will also print a list of prime numbers from 2 to a given number.

What is a Prime Number

A prime number is defined as any positive number which is only divisible by 1 and itself. Any number which is not prime is called composite. 1 is considered as neither prime nor composite. Example of prime numbers are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, .....

If you want to check if a number is prime or not, simply see its factors. If it has only two factors, i.e 1 and the number itself then it is a prime number. 

Check if 10 is a prime number. The factors of 10 are 1,2,5,10. Hence it is not a prime number

Check if 17 is a prime number. The factors of 17 are 1,17. Hence it is a prime number.

Example: Check a Number is Prime or not?

To find if a number is prime or not, we define a function isprime.


isprime <- function(n) {
    lim <- n/2
    prime <- T
    for( i in 2:lim) {
      if(n %% i == 0)
        prime <- FALSE
     
  }

if(n==2) prime <- T
    if(prime) print(paste(n," is a Prime Number"))
    else print(paste(n," is a Composite Number"))
}

Output:

> isprime(10)
[1] "10 is a Composite Number"
> isprime(17)
[1] "17 is a Prime Number"

In this example the function isprime() checks if a number is prime. First a variable lim is created which is half of the original number. It is to cut iteration of for loop in to half as there are no more factors possible after half of a number. The variable prime contains T or TRUE initially, and if the number is not prime, it will be changed into F.

Example: List of Prime numbers


To create a list of prime numbers from 2 to a certain range, we can use this function with a for loop

for(j in 2:100)
      isprime(j)

The general syntax will be

for( variable in 2:limit)
     isprime(variable)