Checking if prime number then printing factors

4166 views python
7

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.

answered question

1 Answer

9

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

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories