Imagine you need to create a function in R that checks if a number is prime. How would you do this?

  • is_prime <- function(n) { if (n <= 1) { return(FALSE) } for (i in 2:sqrt(n)) { if (n %% i == 0) { return(FALSE) } } return(TRUE) }
  • is_prime <- function(n) { if (n <= 1) { return(TRUE) } for (i in 2:sqrt(n)) { if (n %% i == 0) { return(TRUE) } } return(FALSE) }
  • is_prime <- function(n) { if (n <= 1) { return(FALSE) } for (i in 2:sqrt(n)) { if (n %% i != 0) { return(TRUE) } } return(FALSE) }
  • All of the above
To create a function in R that checks if a number is prime, you can use the following code: is_prime <- function(n) { if (n <= 1) { return(FALSE) } for (i in 2:sqrt(n)) { if (n %% i == 0) { return(FALSE) } } return(TRUE) }. The function takes a number n as input and iterates from 2 to the square root of n, checking if any of these numbers divides n. If a divisor is found, the function returns FALSE; otherwise, it returns TRUE.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *