Ruby - Check if a Number is Prime

1. Introduction

A prime number is a natural number greater than 1 that cannot be formed by multiplying two smaller natural numbers. In simpler terms, if a number is only divisible by 1 and itself, then it is prime. Prime numbers play a foundational role in number theory and have applications in fields like cryptography. In this guide, we'll develop a Ruby program to check if a given number is prime.

2. Program Steps

1. Set up your Ruby development environment.

2. Prompt the user to input a number.

3. Implement a method to determine if the provided number is prime.

4. Return and display the result to the user.

3. Code Program

# Prompting the user for a number
puts "Enter a number to check if it's prime:"
number = gets.chomp.to_i
# Define a method to check primality
def is_prime?(num)
  return false if num <= 1
  2.upto(Math.sqrt(num).to_i) do |i|
    return false if num % i == 0
  end
  true
end
# Check if the provided number is prime
result = is_prime?(number)
# Display the result
if result
  puts "#{number} is a prime number."
else
  puts "#{number} is not a prime number."
end

Output:

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

Explanation:

1. gets: Gathers user input. It defaults to capturing the input as a string.

2. chomp: Eliminates the newline character appended when the user presses Enter.

3. to_i: Converts the input string into an integer.

4. is_prime?: This custom method returns false if the number is less than or equal to 1, as 1 isn't prime.

5. 2.upto(Math.sqrt(num).to_i): An efficient way to check for factors of the number. If a number is non-prime, it must have a factor less than or equal to its square root.

6. %: The modulo operator. If num % i is zero, i is a factor of num, implying num isn't prime.


Comments