Sum of Prime Factors

Calculate sum of prime factors.

AdvancedPhase 6 - Category 3: Loop & Conditional MixExample 7 of 10
sum-of-prime-factors.py
1# Helper function
2def is_prime(n):
3 if n < 2:
4 return False
5 for i in range(2, int(n ** 0.5) + 1):
6 if n % i == 0:
7 return False
8 return True
9
10# Take number
11num = int(input("Enter a number: "))
12
13# Find and sum prime factors
14total = 0
15for i in range(2, num + 1):
16 if num % i == 0 and is_prime(i):
17 total += i
18
19print(f"Sum of prime factors: {total}")

Output

Enter a number: 60
Sum of prime factors: 10

What's going on

Find prime factors and sum them.

Key Concepts:

Find prime factors
Sum all prime factors
Return total