Python uses an unrestricted array to achieve the prime number, without limiting prime numbers, using a filtering Method!

Source: Internet
Author: User
Tags square root

#相信很多人能写出比我还精简的算法

#但你能写出比Python还优雅的算法吗?!


Import Math #动用并 imports into the math function

A=[] #定义一个数组并且不初始化, because I don't know how many elements this array will use.
# x is dividend, J is the inner loop variable, a[j] is the divisor used for the test


A.append (1) #A [0]=1 The initial value for the array because it is easy to cycle
A.append (2) #A [1]=2


X=1 #2 ==x to perform the first cycle
While True: #无限循环
X=x+1
Isprime=1 #默认 (assuming) X is a prime number?? Until we know that X is not a prime number. That's what makes isprime=0
X1=int (Math.sqrt (X)) #第二个退出条件是: J is greater than the square root of X (+1) i.e. X2
#第一个退出条件是: A[j] greater than the square root of X (i.e. x1)
X2=x1+1
For j in range (1, x2):
If A[j]> (x1):
Break
If 0==X%A[J]:
Isprime=0
Break
If 1==isprime: #终于找到一个X is prime number,
A.append (X) #压栈,
Print (X) #并输出吧!

Python uses an unrestricted array to achieve the prime number, without limiting prime numbers, using a filtering Method!

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.