How to calculate prime numbers within 100 using Python?
迷茫
迷茫 2017-06-12 09:24:00
0
3
928
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import math 

L = range(0,101)

def isprime(n):
    if n<= 1:
        return False
    for i in range(2,int(math.sqrt(n)) + 1):
        if n % i == 0:
            return False
    
    return True **# 这个return为什么要放到for的下面?为什么不放到 if n % i == 0 下面?**

y = filter(isprime, L )

print y
迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(3)
女神的闺蜜爱上我

Determine whether a number n is a prime number:

从 2 到 sqrt(n):
   存在一个 n 为因数,不为素数,返回 False
不存在,为素数,返回 true

So, return True is when it is judged that every number from 2 to sqrt(n) is not a factor, it is a prime number, and returns True. So it is outside the loop, not inside.

阿神

Because if in the for loop body, if a number that can be divided evenly is found, it means that this n is not a prime number, and it will return False immediately. If the for loop body has finished running, no number that can be divided evenly has been found. , this means that this n is a prime number, so return True needs to be placed under for.

In addition, you can refer to the ideas in my blog: Python prints prime numbers within a certain value

扔个三星炸死你

If you return in the loop body, the loop will be terminated and returned when it encounters the first n % i != 0 number. There is no way to verify whether n is not divisible by every number within 100 (except 1 and itself), so return needs to be in the loop in vitro.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!