R Examples

R Program - Find all Prime Numbers in a given Interval



A Prime number is a natural number greater than 1 and divisible by 1 and itself only, for example: 2, 3, 5, 7, etc.

Objective: Write a r code to find all prime numbers in a given internal.

Method 1: Using function to find prime number

In the example below, a function called primenumber() is created which takes two numbers as arguments and checks every number between them for prime number by dividing it with all natural numbers starting from 2 to N/2.

primenumber <- function(MyNum1, MyNum2) {
  prime_nums = c()

  for (MyNum in c(MyNum1:MyNum2)) {
    n <- 0
    i <- 2
    Numbers <- c(2:(MyNum%/%2 + 1))
    
    for (i in Numbers) {
      if (MyNum %% i == 0) {
        n <- n + 1
        break      
      }
    }

    #storing all the prime numbers in prime_nums vector
    if ((MyNum == 2 || n == 0) && MyNum >= 2) {
      prime_nums = c(prime_nums, MyNum)
    }    
  }

  #returning prime_nums vector
  return(prime_nums)
}

x <- 10
y <- 50

sprintf("Prime numbers between %d and %d are:", x, y)
print(primenumber(x, y))

The above code will give the following output:

[1] "Prime numbers between 10 and 50 are:"
[1] 11 13 17 19 23 29 31 37 41 43 47

Method 2: Optimized Code

  • Instead of checking the divisibility of given number from 2 to N/2, it is checked till square root of N. For a factor larger than square root of N, there must the a smaller factor which is already checked in the range of 2 to square root of N.
  • Except from 2 and 3, every prime number can be represented into 6k ± 1.
primenumber <- function(MyNum1, MyNum2) {
  prime_nums = c()

  for (MyNum in c(MyNum1:MyNum2)) {
    n <- 0
    i <- 2
    if (MyNum == 2 || MyNum == 3) {
      #storing all the prime numbers in prime_nums vector
      prime_nums = c(prime_nums, MyNum)
    } else if (MyNum %% 6 == 1 || MyNum %% 6 == 5) {
      while (i*i <= MyNum) {
        if (MyNum %% i == 0) {
          n <- n + 1
          break        
        }
        i <- i + 1       
      }
      
      #storing all the prime numbers in prime_nums vector
      if (n == 0) {
        prime_nums = c(prime_nums, MyNum)
      }
    }
  }

  #returning prime_nums vector
  return(prime_nums)
}

x <- 100
y <- 200

sprintf("Prime numbers between %d and %d are:", x, y)
print(primenumber(x, y))

The above code will give the following output:

[1] "Prime numbers between 100 and 200 are:"
[1] 101 103 107 109 113 127 131 137 139 149 151 157 163 167 173 179 181 191 193
[20] 197 199