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.
Loading...
Related Quiz
- Can a data frame in R contain columns of different data types?
- What are some functions in R that operate specifically on data frames?
- How does the ifelse() function in R differ from the if-else statement?
- Can you describe how to round a decimal number to the nearest integer in R?
- In R, you can define a custom function called ______ to calculate the mode of a numeric vector.