Introduction
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. This guide will walk you through writing an R program that checks whether a given number is prime.
Problem Statement
Create an R program that:
- Prompts the user to enter a number.
- Checks if the number is prime.
- Displays a message indicating whether the number is prime or not.
Example:
- Input:
7
- Output:
7 is a prime number
Solution Steps
- Read the Number: Use the
readline()
function to take the number as input from the user. - Convert the Input to Numeric: Convert the input from a character string to a numeric value using the
as.numeric()
function. - Check if the Number is Prime: Use a loop and conditional checks to determine if the number has any divisors other than 1 and itself.
- Display the Result: Use the
print()
function to display whether the number is prime or not.
R Program
# R Program to Check if a Number is Prime
# Author: https://www.javaguides.net/
# Step 1: Read the number from the user
number <- as.numeric(readline(prompt = "Enter a number: "))
# Step 2: Function to check if a number is prime
is_prime <- function(num) {
if (num <= 1) {
return(FALSE)
}
if (num == 2) {
return(TRUE)
}
for (i in 2:sqrt(num)) {
if (num %% i == 0) {
return(FALSE)
}
}
return(TRUE)
}
# Step 3: Check if the number is prime
if (is_prime(number)) {
print(paste(number, "is a prime number"))
} else {
print(paste(number, "is not a prime number"))
}
Explanation
Step 1: Read the Number
- The
readline()
function prompts the user to enter a number. The input is read as a string, so it is converted to a numeric value usingas.numeric()
.
Step 2: Function to Check if a Number is Prime
- The function
is_prime()
checks if a number is prime by iterating through possible divisors from 2 to the square root of the number. If any divisor divides the number without leaving a remainder, the function returnsFALSE
, indicating that the number is not prime. If no divisors are found, the function returnsTRUE
.
Step 3: Display the Result
- The program checks the result from the
is_prime()
function and prints whether the number is prime or not.
Output Example
Example:
Enter a number: 7
[1] "7 is a prime number"
Example:
Enter a number: 10
[1] "10 is not a prime number"
Conclusion
This R program demonstrates how to check if a number is prime by implementing a simple algorithm to test divisibility. It covers key programming concepts such as loops, conditional statements, and functions, making it a useful example for beginners learning R programming.