π· 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
π§ Examples:
---
π§ͺ My Initial Solution (Not Efficient for Large Numbers)
β οΈ *Why this fails on Codewars:*
While logically correct, itβs too slow for large values of
---
β‘οΈ AI/Optimal Solution (Codewars Accepted β )
π Key Notes:
-
- Checking
- Negative numbers can't be perfect squares, so return
β 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
π· 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