Ruby determines whether a number is prime (prime) sample _ruby topics

Source: Internet
Author: User

Ruby determines whether a number is prime

Prime numbers are also called primes. A natural number greater than 1, if it is not divisible by other natural numbers except for 1 and itself, (except for 0), otherwise known as composite numbers. According to the basic theorem of arithmetic, each integer that is larger than 1 is either itself a prime number or a product of a series of prime numbers, and if the order of these primes in the product is not taken into account, the written form is unique.

Copy Code code as follows:

Def Prime? (num)
res = [1]
Res << num

If num = 0 | | num = 1
return False
End

2.upto (Ten) do |x|
#如果有自己的话, just skip the next round.
if num = = X
Next
End

Divide the number between #看看是否能被 2-10, and the remainder equals grouping
If num% x = 0
Res << x
End
End

Res.length > 2? False:true
End

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.