VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sum-factors-number/

⇱ Sum of Factors of a Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sum of Factors of a Number

Last Updated : 5 Apr, 2026

Given a number n, find the sum of all the factors.

Examples :

Input: n = 30
Output: 72
Explanation: Divisors sum 1 + 2 + 3 + 5 + 6 + 10 + 15 + 30 = 72

Input: n = 15
Output: 24
Explanation: Divisors sum 1 + 3 + 5 + 15 = 24

Iterative Method - O(√n) Time and O(1) Space

Traverse from 2 to √n because factors always occur in pairs (i, n / i), so we can find all divisors till √n. Initialize the res with 1 (already including factor 1). For every divisor found, add both i and (n / i), handling the perfect square case where both are equal. Finally, add n to get the total sum.

For n = 15:

  • Initialize res = 1 (including factor 1)
  • √15 ≈ 3, so loop runs from i = 2 to 3
  • i = 2, 15 is not divisible by 2, so skip
  • i = 3, 15 is divisible by 3, so factors are 3 and 5, res becomes 1 + 3 + 5 = 9
  • Add n itself, res becomes 9 + 15 = 24

Final Answer = 24


Output
72

Keep Dividing n with Prime Factors

Use the prime factorization of n and apply the geometric progression formula to compute the sum of divisors efficiently. Each prime factor contributes a series (1 + p + p2 + ... + pa), and multiplying all such series gives the final sum.

If, n = p1a1 x p2a2 x ... x pkak

Then, Sum of factors = (1 + p1 + p12 + ... + p1a1) x (1 + p2 + p22 + ... + p2a2) x ... x (1 + pk + pk2 + ... + pkak)

We can notice that individual terms of the above formula are Geometric Progressions (GP). So, we can rewrite it as:

Consider the number n = 18

18 = 2¹ × 3²
Factors = 1, 2, 3, 6, 9, 18

Consider each prime Factor and add all its powers divisible by n
Sum = (2⁰ + 2¹) × (3⁰ + 3¹ + 3²)
= (1 + 2) × (1 + 3 + 9)
= (1 + p₁) × (1 + p₂ + p₂²)

So the problem reduces to finding the prime factors of n along with their powers.


Output
72
Comment