A number a
is divisible by a number b
if the result of the division a / b
is equal to the result of the integer division a %/% b
. Any integer pn
can be divided by at least two numbers: 1
and pn
. Prime numbers are those than can only be divided by those two. Breaking out the code:
pn / 1:pn
are the results of the divisions by1
,2
, …,pn
pn %/% 1:pn
are the results of the integer divisions by1
,2
, …,pn
sum(pn / 1:pn == pn %/% 1:pn)
are how many of these are equal, i.e., the number of integer divisors ofpn
. If this number is2
, you have a prime.
What was wrong with your code: if
needs to test if something is TRUE
or FALSE
but you were passing it a whole vector. Also, your logic was wrong. It should have been:
is.prime <- function(num) {
if (num == 2) {
TRUE
} else if (any(num %% 2:(num-1) == 0)) {
FALSE
} else {
TRUE
}
}
And once you’ve settled on returning a logical, you can make your code a lot shorter:
is.prime <- function(n) n == 2L || all(n %% 2L:max(2,floor(sqrt(n))) != 0)
(which incorporates @Carl’s comment about not checking all numbers.)