简体   繁体   English

检查素数是否打印因子

[英]Checking if prime number then printing factors

The question asks to check if a number is a prime number.这个问题要求检查一个数字是否是素数。 If it isn't, then you have to make a separate function that prints the list of factors of the prime numbers.如果不是,那么您必须创建一个单独的函数来打印质数的因子列表。 The exact question is:确切的问题是:

Write two functions (isPrime and primeFactors).编写两个函数(isPrime 和 primeFactors)。 The function isPrime will return True if its argument is a prime number, False otherwise.如果参数是素数,函数 isPrime 将返回 True,否则返回 False。 The function primeFactors will return a list of prime factors of a number.函数 primeFactors 将返回一个数字的素因数列表。

So far I have:到目前为止,我有:

def isPrime(x):
if x==1:
    return False
elif x==2:
    return True
else:
    for i in range(2,x):
        if (x % i==0):  
            return False

This first function checks if the number is prime or not.第一个函数检查数字是否为素数。 However, I am not sure how to make the primeFactors function then only work when the result is not a prime number.但是,我不确定如何使 primeFactors 函数仅在结果不是素数时才起作用。

Since you already have your function for determining if a number is prime, the function of finding the prime factors of a number would be as follows:由于您已经有了确定一个数是否为素数的函数,因此找到一个数的素数因子的函数如下:

def findPrimeFactors(number):
    primeFactors = []

    for i in range(2, number + 1):
        if number % i == 0 and isPrime(i):
            primeFactors.append(i)

    return primeFactors

If you want to find all the prime factors including duplicates ie@Omari Celestine's answer will only return [2] for the findPrimeFactors(8) rather than [2, 2, 2] etc.如果您想找到包括重复项在内的所有主要因素,即@Omari Celestine 的答案只会为findPrimeFactors(8)返回[2]而不是[2, 2, 2]等。

You could do something like this, notice how I am only checking up to the square root of n in each function:你可以做这样的事情,注意我是如何只检查每个函数中n平方根的:

def is_prime(n):
  if n < 2:
    return False
  else:
    i = 2
    while i * i <= n:
      if n % i == 0:
        return False
      i += 1
    return True

def prime_factors(n):
  primes = []
  i = 2
  while i * i <= n:
    if not is_prime(n):
      n = n // i
      primes.append(i)
    else:
      i += 1
  if n > 1:
    primes.append(n)
  return primes

print(is_prime(9)) # False
print(prime_factors(8)) # [2, 2, 2]
print(prime_factors(37)) # [37]
print(prime_factors(56)) # [2, 2, 2, 7]
print(prime_factors(23424)) # [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 11]

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

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