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")
}}
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")
}}
There's a few issues here.
all
command.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"