简体   繁体   English

查找小于或等于用户使用循环输入的数字的素数。 我怎么做?

[英]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.实际上,达到sqrt(num)就足够了。 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. range(2,some_num)给出一个迭代器,遍历从 2 到some_num-1所有数字,all() 函数检查该迭代器中的语句n%i是否为真,并返回一个布尔值。 If you can guarantee to never pass even numbers you can start the range from 3 (of course with the loss of generality).如果您可以保证永远不会通过偶数,您可以从 3 开始范围(当然会失去一般性)。 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.列表prime_lst将包含所有您寻求的素数。 I start the loop from 1 such that I can loop through only the odd numbers, even numbers are divisible by two.我从 1 开始循环,这样我只能循环遍历奇数,偶数可以被 2 整除。 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.不幸的是,这需要我检查数字本身是否可能是 2,这是一个质数。 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.您的代码仅检查输入的数字是否为素数,但您质疑是否要获得从 2 到 n 的素数(n = 用户输入的数字),为此您在标志位的帮助下运行下面的代码,这将有点容易你。 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试试这个我运行这个代码它肯定会帮助你找到你的答案它在python 3.0或更高版本中工作

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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查找小于或等于给定自然数的素数总数 - Find total of prime less than or equal to a given natural number 如何检查用户是否输入了号码? - How do I check if the user has entered a number? 质数小于或等于n - Prime numbers less than or equal to n 我如何在这个质数筛的 for 循环中花费更少的时间? - How do I spend less time in the for loop in this prime number sieve? 如何在django过滤器中做小于或等于和大于等于? - how to do less than or equal to and greater than equal to in django filter? 如何在 Python 中使用递归找到素数 - How do I find a prime number using recursion in Python 如何检查用户输入是否未输入任何内容? - How do I check if user input has entered nothing? 我如何添加所有这些素数? - How do I add all of these prime numbers? 我想编写一个代码,当一个数字等于某事时说些什么,但是当它大于或小于该数字时,做其他事情 - I want to make a code that says something when a number is equal to something, but when it is bigger than or less than that number do something else 我如何找到所有可能的方法,我可以将一个数组安装到 4 个插槽中,并且数组可能有更多/少于 4 个数字? - How do I find all possible ways I can fit an array to 4 slots with the possibility of the array having more/less than 4 numbers?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM