itiswhatitis
itiswhatitis

Reputation: 27

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.

Upvotes: 2

Views: 557

Answers (2)

Sash Sinha
Sash Sinha

Reputation: 22360

If you want to find all the prime factors including duplicates i.e. @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]

Upvotes: 0

Omari Celestine
Omari Celestine

Reputation: 1435

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

Upvotes: 1

Related Questions