Python打印素数

时间:2016-01-01 18:24:34

标签: python

任务:编写一个打印出10,000以下所有素数的程序。 提示:您需要使用%来表示除法运算的剩余部分。 因此x = 11%5将得到1,因为11/5 = 2余数1

我找到了这个代码,有人可以在解释发生了什么的所有行旁边添加注释。我完全不理解这段代码。

    numbers=[]
for i in range(0,10001):
    numbers.append(" ") #We just put spaces in each box for now
numbers[0]="X"
numbers[1]="X"

firstFree=2
while firstFree<10001:
multiple=firstFree*2
  while multiple<10001: #Mark all multiples of firstFree as X
      numbers[multiple]='X'
      multiple=multiple+firstFree

     firstFree=firstFree+1
      while firstFree<10000 and numbers[firstFree]=='X':
    firstFree=firstFree+1

  for i in range(0,10001):
         if(numbers[i]!='X'):
              print(i)

1 个答案:

答案 0 :(得分:0)

正如你被告知的那样,你不应该这样学习。另外,根据我的拙见,您发现的这段代码非常难看且难以阅读。

这是一个很好的例子。

#Main loop, this is self explanatory.
for dividend in range(2, 10000):

    #This loops through all divisors available.
    for divisor in range(2, dividend):

        #Check against reminder of division.
        if dividend % divisor == 0:

            #Prints all composites of prime number that failed against check.
            print('{} equals {} * {}'.format(dividend, divisor, dividend//divisor))

            #Breakes second loop.
            break

    #Find answer for this thing yourself. It is interesting.
    else:
        #Enters here when have not found division factor.
        print('{} is one of the prime numbers.'.format(dividend))

阅读大量的教程,训练和学习。