简体   繁体   中英

Find a prime number without using def()?

It seems like a lot answers to finding prime numbers in a range involve a define function, but I don't see why what I put below doesn't work?

for num in range(3,1000):
    x=int in range(2,num)
    if num%x!=0:
        print(num)

The error I get is

Traceback (most recent call last):
  File "C:/Users/Jack/PycharmProjects/beginnerworkeraseanddoanything/venv/numbers.py", line 4, in <module>
    if num%(x)!=0:

ZeroDivisionError: integer division or modulo by zero

which doesn't make sense to me. I feel like I should get an error relating to the fact that a number can be both true and false regarding my code (ie 10%5 is 0 but 10%3 is 1) but instead I get the error above.

x=int in range(2,num) is False , because the type int is not in the range 2 to num . False is just a fancy name for 0, so num%x is division by zero. Your error has nothing to do with the fact that it's not in a function.

I'm not sure what you're trying to do with x=int in range(2,num) so I can't really suggest how to fix it.

I think what you want is:

for i in range(3, 100):
    for j in range(2, i):
        if i % j == 0:
            break
    else:
        print(i)

But using this way to find the prime number is too slow (also missed the prime number 2). You can use generator to find the prime number in python. In this way

def _odd_iter():
    n = 1
    while True:
        n += 2
        yield n

def _not_divisible(n):
    return lambda x: x % n > 0

# prime number generator
def primes():
    yield 2
    iter = _odd_iter()
    while True:
        n = next(iter)
        yield n
        iter = filter(_not_divisible(n), iter)

def generate_primes_list(n):
    primes_list = []
    for prime in primes():
        if prime < n:
            primes_list.append(prime)
        else:
            break
    return primes_list

Kindall's answer is the correct one as why you are getting the error. If you are trying to find primes "not defining any function, ie not using def()" you could try this code i wrote a while ago:

top= 1000
primes=[]
for i in range(2,top):  #start from 2 to max number
    add=True
    for j in range(1,int(math.sqrt(i))+1): 
        """
        property of primes, refer to number theory: 
        https://math.stackexchange.com/questions/63276/is-a-prime-factor-of-a-number-always-less-than-its-square-root
        """

        if(j!=1 and i!=j and i%j==0): #this could have been done better
            add=False
            break

    if(add):

        primes.append(i)

print (primes)
print (len(primes))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM