Using R, I need to create a code that checks whether a number x is a prime number or not using RECURSION ONLY (while, for, and any iterative operators are not allowed. I made one but it seems that my code has a problem when I run it : is_prime <- function (x) {
Using R, I need to create a code that checks whether a number x is a prime number or not using RECURSION ONLY (while, for, and any iterative operators are not allowed. I made one but it seems that my code has a problem when I run it :
is_prime <- function (x) {
divisor <- 2
divisor_check <- function (x, divisor) {
if (x <= 2) {
if (x == 2){
return(TRUE)
} else {
return(FALSE)
}
}
else if (x %% divisor == 0) {
return(FALSE)
}
else if (divisor * divisor > x) {
return(TRUE)
} else if (x == 0 || x != floor(x)){
return(NULL)
}
else {
return(FALSE)
}
}
divisor_check(x, divisor+1)
}
above is the code and when I run it, the results are as follows:
> is_prime(1)
[1] FALSE
> is_prime(2)
[1] TRUE
> is_prime(3)
[1] FALSE
> is_prime(4)
[1] TRUE
> is_prime(5)
[1] TRUE
Step by step
Solved in 3 steps with 1 images