Question : write a solution to determine if a number is a prime number
Answered by : silkworm
def is_prime?(number) # Prime numbers are greater than 1 return false if number <= 1 # Check for divisors from 2 to the square root of the number (to optimize the algorithm) # If any divisor is found, the number is not prime (2..Math.sqrt(number)).each do |divisor| return false if number % divisor == 0 end # If no divisors are found, the number is prime return true
end
# Test cases
puts is_prime?(2) # Output: true
puts is_prime?(17) # Output: true
puts is_prime?(29) # Output: true
puts is_prime?(30) # Output: false
puts is_prime?(100) # Output: false
Source : https://chat.openai.com/?model=text-davinci-002-render-sha | Last Update : Fri, 04 Aug 23