Ruby determines whether a number is prime
Prime numbers are also called prime numbers. A natural number greater than 1, if it can not be divided by other natural numbers except 1 and itself; (except 0), otherwise it is called a composite number. According to the basic theorem of arithmetic, every integer larger than 1 can either be a prime number itself or be written as the product of a series of prime numbers. Moreover, if the order of these prime numbers in the product is not considered, the written form is unique.
Copy codeThe code is as follows: def prime?(num)res = [1]
res << num
if num == 0 || num == 1
return false
end
2.upto(10) do |x|
If you have yourself, skip the next cycle
if num == x
next
end
Let’s see if it can be divided by the number between 2-10. The remainder is equivalent to grouping
if num % x == 0
res << x
end
end
res.length > 2 ? false : true
end