![]() |
VOOZH | about |
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 = 72Input: n = 15
Output: 24
Explanation: Divisors sum 1 + 3 + 5 + 15 = 24
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:
Final Answer = 24
72
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, 18Consider 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.
72