简体   繁体   中英

Check whether the number in a range is a prime number, if not, return all factors

Let's say we want to look at range(2,10).

I have written the following code:

for n in range(2,10):
    for x in range(2,n):
        if n%x == 0:
            print(n,'equals',x,'*',n//x)  
            break
    else:
        print(n, "is a prime number") 

The above way can do checking correctly but it also returns one factor.

But if I replace break to continue:

for n in range(2,10):
    for x in range(2,n):
        if n%x == 0:
            print(n,'equals',x,'*',n//x)  
            continue
    else:
        print(n, "is a prime number") 

It couldn't do the checking correctly anymore. So is there any better way to get both checking and all factors correctly? Your answer will be of great help to me!!

Do not use either break or continue, but make and use a bool variable prime as follows.

for n in range(2,10):
    prime = True
    for x in range(2, n):
        if n%x == 0:
            print(n,'equals',x,'*',n//x)  
            prime = False
    if prime:
        print(n, "is a prime number")

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