繁体   English   中英

在 python 中找到素数

[英]find prime numbers in python

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

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

使用筛子可以达到目的:

例:

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

您可以将每个数字的除数存储在列表中,然后使用", ".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)

编辑:愚蠢的语法错误

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

一个更优雅的解决方案是制作一个单独的函数isPrime或在内部for循环中使用break和else。 两种方式都将使质数不必要。

您只能一一除以它本身,因此至少是该定义,它是质数。

> # 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

这是输出的简单程序

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()函数将检查数字是否可整除。

这段代码从用户那里接收一个数字并判断它是否是质数。 我可以说它是最快的,因为在数学中,要找出一个数字是否是素数,只需检查该数字的平方根就足够了。

import math
prime = int(input("Enter your number: "))
count = 0
sqr = int(math.sqrt(prime))
for i in range(2, sqr+1):
    if prime % i == 0:
        print("your number is not prime")
        count += 1
        break
if count == 0:
    print("your number is prime")

暂无
暂无

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

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