1

I made this code and now I wanna find the smallest prime number greater than a x? For example, given 4, I need 5; given 7, I need 11.

my_number = function(n) {
    rangeOfNumbers = 2:(n-1)
    if(any(n%%rangeOfNumbers == 0)){
      return(FALSE)
    }
    else return(TRUE)
  }
tjebo
  • 21,977
  • 7
  • 58
  • 94

1 Answers1

0

This would be an option using a while loop, based on this function to find if a number is a prime number

first_prime <- function(n){

  is.prime <- function(n) {
    if (n == 2) {
      TRUE
    } else if (any(n %% 2:(n-1) == 0)) {
      FALSE
    } else { 
      TRUE
    }
  }
n <- n+1

while(is.prime(n) == FALSE) {
  n <- n+1
}
print(n)
}

> first_prime(10)
[1] 11
> first_prime(11)
[1] 13
> first_prime(12)
[1] 13
> first_prime(14)
[1] 17
> first_prime(20)
[1] 23
tjebo
  • 21,977
  • 7
  • 58
  • 94
  • As this risks to be concerned by performances, you may replace the "n %% 2:(n-1)" by "n %% 2:int(sqrt(n))" – Vince Dec 18 '18 at 13:02
  • @Vince May work (although trying it throwed an error in my session). Moreover, it requires `rlang::int` and does not work with `base` alone. – tjebo Dec 18 '18 at 13:16
  • Sorry, I don t know well R, maybe the int conversion should be done otherwise. – Vince Dec 18 '18 at 13:22
  • You could use `ceiling(sqrt(n))` to round up to the next highest integer – qdread Dec 18 '18 at 13:30
  • In addition to @Vince , you can increment n by 2 if the starting n is odd to speed up a bit more when dealing with large numbers – P1storius Dec 18 '18 at 13:58