简体   繁体   中英

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). The function isPrime will return True if its argument is a prime number, False otherwise. The function primeFactors will return a list of prime factors of a number.

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.

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.

You could do something like this, notice how I am only checking up to the square root of n in each function:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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