NeetCode #910LC-263EasyMath & Geometry
← Back to All Problems#910 · #263 · Ugly Number(丑数)
📌 Problem Statement & Constraints
An ugly number is a positive integer whose prime factors are limited to
2, 3 and 5. Given an integer n, return true if it is ugly, otherwise false. Constraints: -2^31 <= n <= 2^31 - 1.💡 Core Algorithmic Approaches
- Divide out every factor of
2, then every factor of3, then every factor of5. - If the remaining value is
1, all prime factors were among those three, sonis ugly. - Non-positive inputs are not ugly by definition and must be rejected up front.
- The number of divisions is bounded by the number of prime factors, which is O(log n).
💻 Benchmark Python3 Implementation
class Solution:
def isUgly(self, n: int) -> bool:
if n <= 0:
return False
for p in (2, 3, 5):
while n % p == 0:
n //= p
return n == 1⚡ Complexity Deep Dive
⏱️ Time Complexity
O(log n): each division reduces n by at least a factor of two.
💾 Space Complexity
O(1).
⚠️ Interview Pitfalls & Follow-ups
- Forgetting the
n <= 0guard:0would loop forever because0 % p == 0is always true. - Testing divisibility without dividing: the value must actually be reduced, otherwise the inner loop never terminates.
- Returning
n > 0instead ofn == 1: after removing all allowed factors the remainder must be exactly1. - Assuming
1is not ugly:1has no prime factors at all, so it is ugly by definition.