Python打印素数
任务:编写一个程序,打印出10000以下的所有素数。 提示:您需要使用%来表示除法运算的剩余部分。 所以x=11%5会给出1作为11/5=2余数1 我发现了这段代码,有人能在解释发生了什么的所有行旁边添加注释吗?我完全不理解这段代码Python打印素数,python,Python,任务:编写一个程序,打印出10000以下的所有素数。 提示:您需要使用%来表示除法运算的剩余部分。 所以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"
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)
number=[]
对于范围(010001)内的i:
数字。追加(“”)#我们现在只在每个框中加空格
数字[0]=“X”
数字[1]=“X”
firstFree=2
虽然firstFree已经告诉过你,但你不应该这样学习。另外,以我的拙见,您发现的这个代码非常难看,很难阅读
这是一个更好的例子
#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))
阅读大量教程,进行培训和学习。这并不像你自己已经尝试了很多,也很难得到任何帮助。这不是一个教程/教学网站,而是一个问答。获取一个代码,然后尝试理解它。。。这不是正确的方法。正确的方法是先构建逻辑,然后尝试用编程语言实现逻辑。@AhsanulHaque我目前正在学习Python中的列表,这是我必须完成的最后一项任务,也是我唯一不知道如何完成的任务。恕我直言,这不是一个值得回答的问题。继续读下去。还要考虑你的问题对未来读者也有帮助。除非他们处理的是这个确切的代码,否则它可能毫无意义。这就是为什么这不仅仅是一个编写代码、调试或诸如此类的服务。如果您需要解释每一行代码,那么这可能是您在尝试编写/理解某些代码之前必须后退一步并学习该语言的标志。常见问题解答。