output example of prime factors of an integer number

Python program to find the prime factors of an integer number

There are many examples of problems that can help you practice with loops. One of them is to find the prime factors of an integer number.

In this post, I’ll show you a python program that will calculate the prime factors of an integer.

What are the prime factors of an integer number?

The prime factors of a number are prime numbers that can be multiplied to obtain the original number.

Examples:

  • 26 = 2 x 13
  • 48 = 24 x 3
  • 63 = 32 x 7

As you can see from the example above, all the factors (2, 3, 7, and 13) are prime numbers. In this link, you can find a python program to find if a number is prime or not and to print the prime numbers in a given range.

The process of finding the prime factors of an integer number is called prime factorization.

There are several prime factorization algorithms.

Prime factorization is a “hard” computational problem. In this case, we just want to practice loops so I’m going to use the easiest (and most inefficient) algorithm: direct search factorization.

The algorithm consists of a sequential search for divisors.

Python program to find the prime factors of an integer number

Find below the python code for a function that returns the prime factors of a given number.

def prime_factors(n):
    result = str(n) + '='
    factor = 2
    while(n > 1):
        if(n % factor == 0):
            result = result + str(factor) + '*'
            n = n / factor
        else:
            factor = factor + 1
    return  result[:-1]

You can test the function below with the following main program, a.k.a. console application.

if __name__=='__main__':
    n = 63
    print (prime_factors(n))

H@ppy coding!

Related posts: