Optimizing Perfect Number Solution in Java with √n Approach

Day 21 of My DSA Journey Solved “Perfect Number” using Java. Problem Summary A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). Example: 28 → divisors are 1, 2, 4, 7, 14 → sum = 28 Approach Initially, I checked all divisors up to n/2. This works but is inefficient for larger numbers. Then I optimized the solution by iterating only up to √n. For every divisor i, there exists a corresponding pair (n / i). So instead of checking all numbers, we only check till √n and add both divisors. Important points: • Start sum = 1 (since 1 is always a divisor) • Avoid counting the square root twice when i == n / i • Exclude the number itself from the sum Optimization Insight Divisors always occur in pairs. Using this property significantly reduces the number of iterations. Complexity Time Complexity: O(√n) Space Complexity: O(1) Key Learning A brute-force solution may work, but understanding mathematical properties helps in optimizing it. Thinking in terms of patterns and divisor behavior leads to better solutions. #DSA #LeetCode #Java #ProblemSolving #CodingJourney #100DaysOfCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories