is_prime, Prime:
- , 1 , 1 . , x - , x, 1. , 2, x - 1.
def prime?(x)
return false if x < 2
2.upto(x - 1) do |n|
return false if (x % n).zero?
end
true
end
As soon as it x % nhas a remainder, we can break the cycle and say that this number is not prime. This will save you from cycling throughout the range. If all possible numbers have been exhausted, we know that the number is prime.
This is not yet optimal. To do this, you will need sieve or another detection algorithm for trial division. But this is a big improvement to your code. Taking the nth up to you.
source
share