R Program to Check Prime Number

1. Introduction

A prime number is a number greater than 1 that is not a product of two smaller natural numbers. In other words, it's a number that can only be divided by 1 and itself without leaving a remainder. Determining if a number is prime is a classic computational task with applications ranging from cryptography to number theory. In this guide, we will construct an R program that examines if a given number is prime.

2. Program Overview

The primary objective of the program is to prompt the user for a number and then verify if that number is prime. 

Following the assessment, the program will inform the user whether the given number is prime or not.

3. Code Program

# Function to check if a number is prime
is_prime <- function(num) {
    if (num <= 1) {
        return(FALSE)
    }
    for (i in 2:sqrt(num)) {
        if ((num %% i) == 0) {
            return(FALSE)
        }
    }
    return(TRUE)
}

# Ask the user for a number
cat("Enter a number to check if it's prime: ")
input_num <- as.integer(readLines(n=1))

# Check and display whether the number is prime or not
if (is_prime(input_num)) {
    cat(input_num, "is a prime number.\n")
} else {
    cat(input_num, "is not a prime number.\n")
}

Output:

Enter a number to check if it's prime: 17
17 is a prime number.

4. Step By Step Explanation

1. Our journey begins with the creation of the is_prime function that evaluates if a number is prime.

2. For numbers 1 and below, the function immediately returns FALSE as they aren't prime.

3. To optimize the check, we loop only up to the square root of the number. If the number isn't divisible by any integer up to its square root, then it won't be divisible by any number greater than that, making it prime.

4. Inside the loop, if the number is divisible by any i (remainder is zero when num is divided by i), the function returns FALSE, indicating it's not prime.

5. If the loop completes without finding any divisors, the function acknowledges the number as prime, returning TRUE.

6. The main section of the program prompts the user for a number, utilizing the cat function.

7. After obtaining the user's input through readLines(n=1) and converting it to an integer via as.integer, the is_prime function is invoked to evaluate the number's primality.

8. Depending on the function's verdict, the program uses the cat function to inform the user if the number is prime or not.

Comments