Python Program to Find Prime Factors of a Number

1. Introduction

Determining the prime factors of a number is a common operation in mathematics and programming. It involves breaking down the number into its constituent prime factors, which are the prime numbers that multiply together to give the original number.

Prime factors of a number are the set of prime numbers that can be multiplied together to result in the original number. For instance, the prime factors of 28 are 2 and 7, because 2 x 2 x 7 equals 28.

2. Program Steps

1. Start with the smallest prime number, which is 2.

2. Divide the number by this prime number if possible.

3. Increment the prime number when the number is no longer divisible by it.

4. Repeat the process until the number is reduced to 1.

5. The prime numbers used in the division process are the prime factors.

3. Code Program

# Function to print prime factors of a number
def print_prime_factors(number):
    # Start with the smallest prime factor
    divisor = 2
    # Continue until the number is reduced to 1
    while number > 1:
        # If the number is divisible by the divisor, it is a prime factor
        while number % divisor == 0:
            print(divisor, end=' ')
            number //= divisor
        # Increment the divisor
        divisor += 1
    # Add a new line at the end
    print()

# Number to find the prime factors of
num_to_factor = 28
# Print the prime factors
print_prime_factors(num_to_factor)

Output:

2 2 7

Explanation:

1. The function print_prime_factors is defined to take an integer number and identify its prime factors.

2. It initializes divisor to 2, the smallest prime factor.

3. The outer while loop runs as long as number is greater than 1.

4. An inner while loop checks for divisibility of number by divisor using the modulus operation number % divisor.

5. If divisible, divisor is printed as a prime factor and number is divided by divisor using floor division.

6. Once number is not divisible by divisor, the divisor is incremented to check the next potential prime factor.

7. This process repeats, printing each prime factor multiple times if necessary (e.g., 2 is printed twice for the prime factors of 28).

8. The output shows the prime factors of 28 printed in ascending order: 2 2 7, which multiply together to give 28.

Comments