AI Forever
3 subscribers
1 link
🌱 Beginner β†’ οΏ½ Intermediate β†’ πŸš€ Advanced β†’ πŸ† Mastery
Download Telegram
πŸ”· Problem 3: A Square of Squares πŸ”·

πŸ‘· You love building blocksβ€”especially square ones! But can you tell if the total number of blocks you have can form a perfect square?

🎯 Task:
Given an integer n, determine whether it's a *perfect square* (i.e., the square of an integer).

🧠 Examples:
-1 => False  
0 => True
3 => False
4 => True
25 => True
26 => False


---

πŸ§ͺ My Initial Solution (Not Efficient for Large Numbers)

def is_square(n): 
def find_factors(n):
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
return factors
factors = find_factors(n)

for i in factors:
if i * i == n:
return True
if n == 0:
return True
return False


⚠️ *Why this fails on Codewars:*
While logically correct, it’s too slow for large values of n, because it checks all factors up to n.

---

⚑️ AI/Optimal Solution (Codewars Accepted βœ…)

import math

def is_square(n):
if n < 0:
return False
sqrt_n = math.isqrt(n) # Efficient integer square root
return sqrt_n * sqrt_n == n


πŸ“Œ Key Notes:
- math.isqrt(n) returns the integer square root efficiently (no floating point issues).
- Checking sqrt_n * sqrt_n == n is both fast and accurate.
- Negative numbers can't be perfect squares, so return False early.

βœ… Best Practice: Use mathematical functions when available. They are optimized and make your code cleaner and faster.

---

πŸ’‘ *Follow for more real-world coding challenges and clean solutions!*

#Python #Codewars #Math #PerfectSquare #LearnToCode #ProgrammingTips