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) {

C++ Programming: From Problem Analysis to Program Design
8th Edition
ISBN:9781337102087
Author:D. S. Malik
Publisher:D. S. Malik
Chapter15: Recursion
Section: Chapter Questions
Problem 8SA
icon
Related questions
Question

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

Expert Solution
steps

Step by step

Solved in 3 steps with 1 images

Blurred answer
Knowledge Booster
Computational Systems
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
  • SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program…
C++ Programming: From Problem Analysis to Program…
Computer Science
ISBN:
9781337102087
Author:
D. S. Malik
Publisher:
Cengage Learning