0

Why isn't my R code working (i.e. doesn't find prime numbers)?

x <- c(1:50)
prime <- function(x){if(x %% (2:(x-1)) == 0) {
  print("p")
} 
else {
  print("np")
}}
Rnewbie
  • 51
  • 4
  • 2
    `if` requires its condition to be length 1, yours is far beyond that. Perhaps `!any(x %% ...)`? Notably, if you included any of the warnings you get when trying your function, you would see `numerical expression has 50 elements: only the first used` which is hint #1, then `longer object length is not a multiple of shorter object length`, which is included in many SO questions/answers, as is `the condition has length > 1 and only the first element will be used`. – r2evans Aug 26 '20 at 17:01
  • 1
    BTW: a function like this that *prints* something is in my experience almost useless. Consider **`return`ing** a value instead of `print`ing one. Further, consider returning a logical (`TRUE` or `FALSE`). – r2evans Aug 26 '20 at 17:04
  • 1
    And while my first comments hints at it -- assumine that `"p"` means prime and `"np"` means not-prime -- your logic is wrong. If there are any 0s in `x %% (2:(x-1))`, then it is *not* a prime, as it is divisible by something other than 1 and itself. – r2evans Aug 26 '20 at 17:06

1 Answers1

2

There's a few issues here.

  1. Per @r2evans comment, the if condition needs to take an input parameter of length 1. You can get around this using the all command.
  2. Your if condition is logically wrong. If the mod operator is equal to 0 then it is NOT prime. If fact you want to do != 0.
  3. 2 is considered to be a prime number. Your logic won't work for 2 because 2%2 = 0. As such you need to handle that case differently. Or the function needs to start working at 3.

Here is a working version:

prime <- function(x){
  if(x == 2){
    print("p")
  }
  else if(all(x %% (2:(x-1)) != 0)) {
  print("p")
} else {
    print("np")
  }
}


> prime(2)
[1] "p"
> prime(3)
[1] "p"
> prime(4)
[1] "np"
> prime(5)
[1] "p"
> prime(6)
[1] "np"
> prime(7)
[1] "p"
user1357015
  • 11,168
  • 22
  • 66
  • 111