Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum of Prime Factors

Add distinct prime divisors of an integer with Python. Students filter factor candidates and distinguish this sum from adding a repeated prime factorization.

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

In this one

  • Sum distinct prime divisors
  • Reuse a helper
  • Retain a neutral total

How it works

  1. 1

    Start total zero.

  2. 2

    Test each candidate for both factorhood and primality.

  3. 3

    Add accepted candidates once and print total.

Edge cases

Does a repeated factor contribute twice?

Does a repeated factor contribute twice?

No. This totals distinct prime divisors.

What is the result for a prime input seven?

What is the result for a prime input seven?

Seven, since it is its own prime divisor.

What's going on

The loop considers each possible divisor once. If it divides num and is prime, that divisor is added to total.

Twelve contributes two and three, totaling five rather than seven from 2 + 2 + 3. The candidate values are unique by construction. This direct scan assumes a positive input; one and nonpositive values produce no additions in the current range logic.

Does a repeated factor contribute twice? No. This totals distinct prime divisors.

What is the result for a prime input seven? Seven, since it is its own prime divisor.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is the total for twelve?

Pick an answer to check it.

Question 2

Does a repeated factor contribute twice?

Pick an answer to check it.

Questions people ask

Does a repeated factor contribute twice?

No. This totals distinct prime divisors.

What is the result for a prime input seven?

Seven, since it is its own prime divisor.

What is the total for twelve?

5.