Ad Code

Write a Python program that prompts the user to enter a positive integer. Your program should display all the factors of the number. Additionally, calculate and display the sum of its factors. Sample output: Enter a positive integer: 45 Factors: 1 3 5 9 15 45 Sum of factors: 78

 Write a Python program that prompts the user to enter a positive integer. Your program should display all the factors of the number. Additionally, calculate and display the sum of its factors. Sample output: 

Enter a positive integer: 45 
Factors: 1 3 5 9 15 45 
Sum of factors: 78

Code:

def factors_and_sum(num):

    factors = []

    factor_sum = 0

    

    # Find factors and calculate their sum

    for i in range(1, num + 1):

        if num % i == 0:

            factors.append(i)

            factor_sum += i

            

    return factors, factor_sum


# Prompt the user to enter a positive integer

while True:

    try:

        num = int(input("Enter a positive integer: "))

        if num > 0:

            break

        else:

            print("Please enter a positive integer.")

    except ValueError:

        print("Invalid input! Please enter a valid integer.")


# Calculate factors and sum of factors

factors, factor_sum = factors_and_sum(num)


# Display factors

print("Factors:", ' '.join(map(str, factors)))


# Display sum of factors

print("Sum of factors:", factor_sum)












Reactions

Post a Comment

0 Comments