Solving Ugly Number III with Binary Search and Math

✳️Day 40 of #100DaysOfCode✳️ 🚀 Cracking the Code: Solving "Ugly Number III" with Math & Binary Search 1️⃣ The Power of Binary Search Instead of counting up from 1, we treat the answer as a range. By using Binary Search on the search space (up to 2 \times 10^9), we can efficiently narrow down the n^{th} number. We check a candidate middle value to see if there are at least n ugly numbers below it. 2️⃣ Inclusion-Exclusion Principle (The Math Secret) To count how many numbers up to M are divisible by a, b, or c, we can't just add them up—that would double-count the multiples they share. I used the Inclusion-Exclusion Principle to get an accurate count: Add counts of numbers divisible by a, b, and c individually. Subtract the counts of numbers divisible by their pairs: lcm(a, b), lcm(b, c), and lcm(a, c). Add back the count of numbers divisible by all three: lcm(a, b, c). 3️⃣ Least Common Multiple (LCM) & GCD To find the LCM accurately, I implemented a helper function using the Greatest Common Divisor (GCD). This ensures that we correctly identify the overlapping multiples without overflow issues. Key Takeaway: Sometimes the most efficient way to "search" isn't to look at every item, but to use mathematical properties to "jump" to the right answer. #LeetCode #Java #Algorithms #CompetitiveProgramming #SoftwareEngineering #BinarySearch #MathInCode

  • text

To view or add a comment, sign in

Explore content categories