我如何检查数字是否为半素数

时间:2018-04-25 21:31:37

标签: python if-statement range

def is_prime(num):

    if num > 1:

        for i in range(2,num):
如果(num%i)== 0:,则

返回False
            if (num % i) == 0:
                return False

如果为素数

则返回True
        else:
            return True

如果不是素数

则返回False
    else:
        return False

def is_semiprime():
        n = int(input("Enter a number to find out if its semiprime or not\n>>> "))
        for d1 in range(2, int(n**.5)):
            if n % d1 == 0:
                d2 = int(n / d1)

is_prime(d1)和is_prime(d2)通过并且不告诉我真或假他们只是发送空行。

               return is_prime(d1) and is_prime(d2)
            return False

is_semiprime()

当它返回is_prime(d1)和is_prime(d2)时如果它们都是True则返回True

3 个答案:

答案 0 :(得分:2)

半素数是一个数字,它是两个素数的乘积。所以算法很简单:

  1. 找到该号码的一个除数,称之为d1
  2. 将数字除以d1以获得第二个除数d2
  3. 测试d1d2是否为素数。如果是,那么原始数字是半素数。
  4. 代码:

    def is_semiprime(n):
        for d1 in range(2, int(n**.5)+1):
            if n % d1 == 0:
                d2 = n / d1
                return is_prime(d1) and is_prime(d2)
        return False
    
    def is_prime(n):
      if n == 2 or n == 3: return True
      if n < 2 or n%2 == 0: return False
      if n < 9: return True
      if n%3 == 0: return False
      r = int(n**0.5)
      f = 5
      while f <= r:
        if n%f == 0: return False
        if n%(f+2) == 0: return False
        f +=6
      return True    
    
    def ask_semiprime():
        num = int(input("What number would you like to check?"))
        if is_semiprime(num):
            print(num, " is semiprime")
        else:
            print(num, " is not semiprime")
    
    ask_semiprime()
    

    我从isPrime Function for Python Language

    复制了is_prime功能

答案 1 :(得分:0)

number = int(input())

s =数字

x = []

对于范围为(2,number + 1)的i:

if s%i==0:

    x.append(i)

    s=s//I

    if s==i or (i>s and s!=1):

        x.append(s)

如果len(x)== 2:

print(f"{number} is a semiprime number because it is the product of Tow primes: ",end="")

其他:

print(f"{number} is not a semiprime number because it is the product of {len(x)} primes: ",end="")

对于x中的i:

if i==x[-1]:

    print(i)

else:

    print(str(i)+"*",end="")

答案 2 :(得分:0)

def check_prime(n): #for checking wheather prime or not
    if n > 1:
        if n == 2: return True
        for i in range(2,n):
            if n % i == 0:
                return False
                break
        return True
    return False
def primeproduct(m): #for checking wheather prime product or not 
    if m >= 0:
      for i in range(1,m):
        if m%i == 0 and check_prime(i) and check_prime(m//i):
            return True
            break
    return False
  

这可能有帮助