To check whether the given number is Prime or Composite using an R program, we must understand the following.
The Prime number is an integer with no other positive divisors other than 1 and that number itself. All other numbers except the prime numbers are Composite numbers.
For example, 2, 3, 5, 7, 11, 13, etc are prime numbers because they have only 2 divisors and the number '4', '6', which have more than two divisors are composite numbers.
Let us take an example as the number '5' is a prime number because the number '5' has only two divisors: '1' and '5'. But, 4 is not prime (it is composite) since 4 has more than two divisors, 1 , 2 and 4.
Note: The number '1' is not a prime number as it has only one divisor.
Here we are explaining how to check whether a number is prime or not.
Given below are the steps which are used in the R program to read a value and check for the prime. In this R program, we accept the user's value into num by providing an appropriate message to the user using 'prompt
'. We can use the readline()
function to take input from the user (terminal). Here the prompt
argument can choose to display an appropriate message for the user. Check the given number is greater than 1 because prime numbers must be greater than one. Check if num is exactly divisible by any number from 2 to num – 1 and if find a factor in that range then set isPrime = 0 otherwise isPrime = 1. Print the message as the number is a prime number if the isPrime == 1 otherwise the number is not prime.
STEP 1: Take user input using readline()
into variable num prompting appropriate messages to the user
STEP 2: Set isPrime = 0 at first
STEP 3: Check if the num is greater than 1, if yes do steps 4,5
STEP 4: set isPrime = 1
STEP 5: Start a for loop
from 2 to num – 1 and check if num is exactly divisible by any number,
break
from loopSTEP 6: if num is 2 then set isPrime =1
STEP 7: Check if isPrime == 1 then print
the number is a prime number, else print
the number is not a prime number
num = as.integer(readline(prompt = "Enter a number: "))
# num = 15
isPrime = 0
if (num > 1) {
isPrime = 1
for (i in 2: (num - 1)) {
if ((num %% i) == 0) {
isPrime = 0
break
}
}
}
if (num == 2) isPrime = 1
if (isPrime == 1) {
print(paste(num, "is a prime number"))
} else {
print(paste(num, "is not a prime number"))
}
Enter a number: 15 [1] "15 is not a prime number" Enter a number: 13 [1] "13 is a prime number"