Checking Abundant Numbers: Brute Force vs Optimized Approach

Day 23 of my #50DaysOfCode challenge is done ✅ 📌 Problem Solved Check if a Number is an Abundant Number We were given an integer n. We had to check if it is an abundant number. An abundant number means: The sum of its proper divisors is greater than the number itself. Example: 12 → divisors: 1, 2, 3, 4, 6 Sum = 16 Since 16 > 12, it is an abundant number. 💻 Brute Force Approach 🔹️Traverse from 1 to n. 🔹️Check if i divides n. 🔹️If yes, add it to sum. 🔹️After traversal, compare sum with n. 🔹️If sum > n → abundant number. Time Complexity: O(n) Space Complexity: O(1) Works. But unnecessary checks happen. 💻 Optimized Approach 🔹️Traverse from 1 to √n. 🔹️If i divides n, add i to sum. 🔹️Also add n / i as paired divisor. 🔹️Avoid adding duplicates when i = n/i. 🔹️Finally compare sum with n. Time Complexity: O(√n) Space Complexity: O(1) Much fewer iterations. 📚 What I learned today: ▫️Divisors always appear in pairs. ▫️Checking till √n is enough for divisor problems. ▫️Avoid counting duplicate divisors for perfect squares. ▫️Small observations can reduce complexity a lot. Day 23 completed. #50DaysOfCode #CodingChallenge #Consistency #LearningInPublic

To view or add a comment, sign in

Explore content categories