Write A Program To Find If A Number Is Prime

[Solved] Write A Program To Find If A Number Is Prime | Swift - Code Explorer | yomemimo.com
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

Answers related to write a program to find if a number is prime or not

Code Explorer Popular Question For Swift