简体   繁体   中英

Find prime numbers less than or equal to the number the user has entered with loops. How do I do that?

With this code, I only get to test if the number the user entered is prime or not. How do I add another loop to my original code in order to find all the prime numbers less than or equal to the number the user has entered?

num = int(input("Enter a number: "))
if num > 1:
    prime = True
    for n in range(2, num):
        if (num % n) == 0:
            print ("Number", num, "is not prime")
            break
    else:
        print("Number", num, "is prime")

You can'not print both in one loop, you can do one thing add a loop above your current loop and display each number like this :

num = int(input("Enter a number: "))
if num > 1:
    prime = True
    for n in range(2, num):
        if (num % n) == 0:
            print ("Number", num, "is not prime")
            break
    else:
            print("Number", num, "is prime")

#your current code ends here

    for j in range(2, num + 1):
      # prime numbers are greater than 1
      for i in range(2, j):
          if (j % i) == 0:
              break
      else:
          print(j)

Aside from small things (unused boolean variable) your prime test is also super inefficient. Let's go through this step by step.

First: To test if a number is prime, you don't need to check all integers up to the number for divisors. Actually, going up to sqrt(num) turns out to be sufficient. We can write a one-liner function to find out if a number is prime like so:

from numpy import sqrt

def is_prime(n):
    return n > 1 and all(n%i for i in range(2,int(sqrt(n))+1))

range(2,some_num) gives an iterator through all numbers from 2 up to some_num-1 and the all() function checks if the statement n%i is true everywhere in that iterator and returns a boolean. If you can guarantee to never pass even numbers you can start the range from 3 (of course with the loss of generality). Even if you don't want to use that function, it's cleaner to separate the functionality into a different function, because in a loop of numbers up to your input you will probably have to check each number for being prime separately anyways.

Second: From here, finding all primes smaller or equal than your input should be pretty easy.

num = int(input("Enter a number:"))
assert num>0, "Please provide a positive integer" # stops with an assertion error if num<=0
prime_lst = [2] if num > 1 else [] 
for x in range(3,num+1,2):
    if is_prime(x):
        prime_lst.append(x)

The list prime_lst will contain all your sought after prime numbers. I start the loop from 1 such that I can loop through only the odd numbers, even numbers are divisible by two. So this way none of the numbers will be divisible by two. Unfortunately this requires me to check if the number itself may be 2, which is a prime. By the twin-prime conjecture we can not simplify this range further without knowing about the input.

Finally: If you really want to find the primes in one loop, change your loop to something along the lines of:

prime_lst = [2] if num > 1 else []

for x in range(3,num+1,2): # outer loop
    for i in range(3,int(sqrt(x))+1): # inner loop for check if x is prime
        if x%i == 0:
            break # breaks the inner loop, number is not prime
    else:
        prime_lst.append(x)

Edit: Just saw that the second answer here has a good explanation (and an even better way) of writing the one-liner for finding out if a number is prime.

Your code only check the number entered is prime or not , but you questioned about to get prime numbers from 2 to n (n = number entered by user) for this you run below code with the help of flag bit it will little bit easy for you. i hope it will help you.

Try This i run this code It will Surely help you to find your answer it work in python 3.0 or above

num = int(input("Enter The Number"))
if num > 1:
    num = num+1
    list = []
    for j in range (2,num,1):
        flag = 0
        for i in range (2,int(j/2)+1,1):
            if(j%i)== 0:
                flag = 1
                break
        if flag==0:
            list.append(j)
    print(list)  
else:
    print("Enter Number Greater Than 1")

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