【问题标题】:find prime numbers in python在python中找到素数
【发布时间】:2015-06-08 23:31:11
【问题描述】:

我需要编写一个代码来查找一系列数字中的所有素数,然后按顺序列出它们,说明哪些是素数,哪些不是,如果它们不是素数,请显示它们可以被哪些数字整除.它应该看起来像这样:

>>> Prime(1,10)
1 is not a prime number 
2 is a prime number
3 is a prime number
4 is divisible by 2
5 is a prime number
6 is divisible by 2, 3
7 is a prime number
8 is divisible by 2, 4
9 is divisible by 3

到目前为止,我有这个只会识别哪些数字是素数并将它们打印在列表中。我不知道如何做非素数并打印出它可以被哪些数字整除。我也知道 1 是一个素数。

def primeNum(num1, num2):
   for num in range(num1,num2):
    prime = True
    for i in range(2,num):
        if (num%i==0):
            prime = False
    if prime:
       print (num,'is a prime number')

【问题讨论】:

标签: python string primes


【解决方案1】:

使用筛子就可以解决问题:

示例:

from __future__ import print_function


def primes():
    """Prime Number Generator

    Generator an infinite sequence of primes

    http://stackoverflow.com/questions/567222/simple-prime-generator-in-python
    """

    # Maps composites to primes witnessing their compositeness.
    # This is memory efficient, as the sieve is not "run forward"
    # indefinitely, but only as long as required by the current
    # number being tested.
    #
    D = {}  

    # The running integer that's checked for primeness
    q = 2  

    while True:
        if q not in D:
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations
            # 
            yield q        
            D[q * q] = [q]
        else:
            # q is composite. D[q] is the list of primes that
            # divide it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next 
            # multiples of its witnesses to prepare for larger
            # numbers
            # 
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]

        q += 1


def factors(n):
    yield 1
    i = 2
    limit = n**0.5
    while i <= limit:
        if n % i == 0:
            yield i
            n = n / i
            limit = n**0.5
        else:
            i += 1
    if n > 1:
        yield n


def primerange(start, stop):
    pg = primes()
    p = next(pg)

    for i in xrange(start, stop):
        while p < i:
            p = next(pg)

        if p == i:
            print("{0} is prime".format(i))
        else:
            print("{0} is not prime and has factors: {1}".format(i, ", ".join(map(str, set(factors(i))))))

输出:

>>> primerange(1, 10)
1 is not prime and has factors: 1
2 is prime
3 is prime
4 is not prime and has factors: 1, 2
5 is prime
6 is not prime and has factors: 1, 2, 3
7 is prime
8 is not prime and has factors: 1, 2
9 is not prime and has factors: 1, 3

【讨论】:

    【解决方案2】:

    只需在将 prime 设置为 false 的位置添加打印和中断。

    更优雅的解决方案是创建一个单独的函数 isPrime 或在内部 for 循环中使用 break 和 else。无论哪种方式都会使素数变得不必要。

    你只能将它自己除以一个,所以它是一个素数,至少按照这个定义。

    【讨论】:

      【解决方案3】:

      您可以将每个数字的除数存储在一个列表中,然后使用", ".join(yourList) 打印它

      即:

      def primeNum(num1, num2):
         for num in range(num1,num2):
             divisors = []
             for i in range(2,num):
                 if (num%i == 0):
                     divisors.append(str(i))
             if divisors:
                 print ('%d is divisible by ' %num + ', '.join(divisors))
             else:
                 print ('%d is a prime number' %num)
      

      编辑:愚蠢的语法错误

      【讨论】:

      • 不是真的,1 和数字本身都没有被解析,所以它们永远不会在列表中
      【解决方案4】:
      > # Check a number whether prime or not
      a = int(input("Please your number (>1): "))
      y = 2
      import math
      b = math.floor(math.sqrt(a)) + 1
      x = True
      while x:
        if a == 2:
          print(f'{a} is prime')
          x = False
        else:
          x = True
          if a %y == 0:
            print(f' {a} is not prime')
            x = False
          else:
            y = y + 1
            if y >= b:
              print(f'{a} is prime')
              x = False
            else:
              x = True
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      【解决方案5】:

      这是输出的简单程序

      def isPrime(lower,upper):
          for num in range(lower,upper+1):
              if num > 1:
                  for i in range(2,num):
                      if (num % 1) == 0:
                          break
                  else:
                      print(num," is a prime number")
      
      def isDivisible(lower,upper):
           for num in range(lower,upper+1):
              if num > 1:
                  for i in range(2,num):
                      if (num % i) == 0:
                          print(num," is divisible by ", i)
                      else:
                          pass
                  else:
                      pass
       
      Lower = int(input("Enter your Lower limit"))
      Upper = int(input("Enter Your Upper Limit"))          
      isPrime(Lower,Upper)
      isDivisible(Lower,Upper)
      
      
      
      
      **This is the output to code:**
      2  is a prime number
      4  is divisible by  2
      6  is divisible by  2
      6  is divisible by  3
      8  is divisible by  2
      8  is divisible by  4
      9  is divisible by  3
      10  is divisible by  2
      10  is divisible by  5
      
      
      
      
       
      
      1. isPrime() 函数将检查数字是否为素数
      2. isDivisible() 函数将检查数字是否可整。

      【讨论】:

      • 如果你可以仔细检查你的两个函数,那么你会发现分支和循环是相同的,结果略有变化,因此你可以在合并时在单个函数中获得两个目标,让我知道你的想法 - 干得好,继续前进。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      相关资源
      最近更新 更多