LeetCode 1952 Three Divisors in Python | Easy Coding Tutorial for Beginners

preview_player
Показать описание
Solve LeetCode 1952 "Three Divisors" in Python with this beginner-friendly coding tutorial! This problem asks you to determine if a given integer `n` has exactly three divisors (e.g., n = 4 returns true because 4 has divisors 1, 2, 4). We’ll count the divisors of `n` by checking all numbers from 1 to `n`, and return true if the count is exactly 3. We’ll also discuss an optimized approach using the square root. Perfect for Python learners, coding beginners, or anyone prepping for coding interviews!

🔍 **What You'll Learn:**
- Understanding LeetCode 1952’s requirements
- Counting divisors of a number in Python
- Optimizing divisor counting using the square root
- Testing with example cases

💻 **Code Used in This Video:**
class Solution(object):
def isThree(self, n):
"""
:type n: int
:rtype: bool
"""
divisors = [d for d in range(1, n + 1) if n % d == 0]
return len(divisors) == 3

# Test cases
solution = Solution()

# Test case 1: Number with exactly 3 divisors
# Divisors of 4: 1, 2, 4 (exactly 3)

# Test case 2: Number with more than 3 divisors
# Divisors of 6: 1, 2, 3, 6 (4 divisors)

# Test case 3: Number with less than 3 divisors
# Divisors of 1: 1 (1 divisor)

# Test case 4: Another number with 3 divisors
# Divisors of 9: 1, 3, 9 (exactly 3)

# Optimized solution
class SolutionOptimized(object):
def isThree(self, n):
"""
:type n: int
:rtype: bool
"""
# A number has exactly 3 divisors if it is a square of a prime number
# Check divisors up to sqrt(n)
count = 0
for d in range(1, int(n ** 0.5) + 1):
if n % d == 0:
count += 1 # d is a divisor
if n // d != d: # If d is not sqrt(n), count the pair (n/d)
count += 1
return count == 3

solution_opt = SolutionOptimized()
print("\nOptimized solution:")

🌟 **Why Solve LeetCode 1952?**
This problem is a great introduction to number theory in Python, a common topic in coding interviews! We’ll show how to count divisors and optimize the process using the square root of `n`. The original solution has a time complexity of O(n), but the optimized version is O(√n), with O(1) space complexity for both. Note: Numbers with exactly 3 divisors are squares of prime numbers (e.g., 4 = 2², 9 = 3²). Master this, and you’ll be ready for more advanced LeetCode challenges!

📚 **Who’s This For?**
- Python beginners learning coding
- Coding enthusiasts tackling LeetCode problems
- Developers prepping for technical interviews

👍 Like, subscribe, and comment: What LeetCode problem should we solve next? Next up: More LeetCode number theory problems—stay tuned!

#LeetCodeTutorial #ThreeDivisors #PythonCoding #LearnCoding #InterviewPrep
Рекомендации по теме