SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Programming Excercises
Question:18 | ISBN:978013274719 | Edition: 6

Question

(Find the factors of an integer) Write a program that reads an integer and displays all its smallest factors, also known as prime factors. For example, if the input integer is 120, the output should be as follows: 2, 2, 2, 3, 5

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Find the factors of an integer Program code:

# Function to find and display the prime factors of an integer
def displayPrimeFactors(number):
    factors = []  # List to store the prime factors

    # Find and append the smallest prime factor repeatedly
    while number > 1:
        for factor in range(2, number + 1):
            if number % factor == 0:
                factors.append(factor)
                number //= factor
                break

    # Display the prime factors
    for index, factor in enumerate(factors):
        if index != len(factors) - 1:
            print(factor, end=", ")  # Print the factor with a comma and space
        else:
            print(factor)  # Print the last factor without a comma

# Example usage:
num = int(input("Enter an integer: "))
displayPrimeFactors(num)

 

Exeucted Output 1:

Enter an integer: 120

2, 2, 2, 3, 5

Executed output 2:

Enter an integer: 1500

2, 2, 3, 5, 5, 5

 

0 0

Discussions

Post the discussion to improve the above solution.