I am trying to create a function to test if a given integer is a prime number, I tried using the following:
tpn <- function(prime.num){
if(prime.num==2){
print("PRIME")
} else {
if(prime.num%%(2:(prime.num-1))!=0){
print("PRIME")
} else {
print("NOT PRIME")
}}}
This doesn't work, although I cant understand why. I am checking to see if the given number can be divided by any of the integers up to this number with no remainders. If it cant, then the number is prime.
Another solution I found was:
tpn <- function(pn){
if(sum(pn/1:pn==pn%/%1:pn)==2)
print("prime")
}
This works. Although, I cant get my head around what sum(pn/1:pn == pn%/%1:pn) == 2
is actually testing for.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…