Check Prime number with While loop in R
Write a R program function to check if a given number is prime using a while loop.
Sample Solution :
R Programming Code :
# Define a function to check if a given number is prime
is_prime <- function(n) {
# Base case: if the number is less than 2, it's not prime
if (n < 2) {
return(FALSE) # Return FALSE for numbers less than 2
}
# Initialize divisor and counter
divisor <- 2 # Start checking divisibility from 2
counter <- 0 # Initialize counter to 0
# Continue loop until divisor squared is greater than or equal to n
while (divisor * divisor <= n) {
# If n is divisible by the current divisor, it's not prime
if (n %% divisor == 0) {
return(FALSE) # Return FALSE if n is divisible by divisor
}
# Increment divisor
divisor <- divisor + 1 # Move to the next divisor
}
# If the loop completes without finding a divisor, n is prime
return(TRUE) # Return TRUE if no divisor found
}
# Test the function with example inputs
test_number <- 37 # Example input to test if it's prime
is_test_prime <- is_prime(test_number) # Call the is_prime function
# Print the result
if (is_test_prime) {
cat(test_number, "is prime.\n") # Print if the number is prime
} else {
cat(test_number, "is not prime.\n") # Print if the number is not prime
}
Output:
37 is prime.
Explatnaion:
In the exercise above,
- Define the function "is_prime":
- This function takes a single parameter 'n', representing the number to check for primality.
- Base Case:
- If the input number 'n' is less than 2, it's not prime, so the function returns 'FALSE'.
- Initialization:
- 'divisor' is initialized to 2, as we start checking for divisibility from 2 onwards.
- 'counter' is initialized to 0.
- While loop:
- The while loop continues until the square of 'divisor' is greater than or equal to 'n'.
- Inside the loop, it checks if 'n' is divisible by the current 'divisor'. If it is, the function immediately returns 'FALSE', indicating that 'n' is not prime.
- Result:
- If the loop completes without finding a divisor, it means that 'n' is prime, and the function returns 'TRUE'.
- Testing the function:
- The function is tested with an example input ('test_number'), and the result is stored in 'is_test_prime'.
R Programming Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Fibonacci series with While loop in R.
Next: Multiplication Table with For loop in R.
Test your Programming skills with w3resource's quiz.
What is the difficulty level of this exercise?
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics