Problem 263

Abstract / Summary

Check if a given number is only divisible by 2, 3, and 5.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0263.py

class Solution:
    def isUgly(self, n: int) -> bool:
        if n <= 0:
            return False

        while n % 2 == 0:
            n //= 2
        while n % 3 == 0:
            n //= 3
        while n % 5 == 0:
            n //= 5

        return n == 1
13 lines | 273 bytes | submitted August 19, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 44% (1+ million submissions).

Typical patterns to solve this problem:
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation defines a Solution class with a single method isUgly. The method determines whether a given integer n is an ugly number, i.e., a positive integer whose prime factors are limited to 2, 3, and 5. The algorithm follows a straightforward reduction approach: repeatedly strip away factors of 2, 3, and 5 from n and then check whether the residual value equals 1. If it does, the original number consisted solely of the allowed prime factors; otherwise, it contained at least one other prime factor and is not ugly.

Core Logic

The method begins with a guard clause that eliminates non-positive inputs:

if n <= 0:
    return False

This early return ensures that the subsequent factor-removal loops only operate on positive integers, which aligns with the mathematical definition of ugly numbers.

The next three code blocks each remove all occurrences of a specific prime factor from n. The loops are independent and execute sequentially:

while n % 2 == 0:
    n //= 2
while n % 3 == 0:
    n //= 3
while n % 5 == 0:
    n //= 5

Each loop checks divisibility using the modulo operator and, when true, divides n by the corresponding prime using integer division (//). The process repeats until n is no longer divisible by that prime, guaranteeing that all factors of 2, 3, and 5 are completely removed.

Finally, the method returns a boolean indicating whether the reduced number equals 1:

return n == 1

If n has been reduced to 1, the original number contained no prime factors other than 2, 3, or 5; otherwise, a residual factor remains, indicating the presence of a disallowed prime.

Edge-Case Handling

The guard clause (n <= 0) addresses inputs that are zero or negative. Zero is not considered ugly because it lacks a finite prime factorization, and negative numbers are excluded by definition. By returning False immediately, the method avoids unnecessary computation for these cases.

When n equals 1, the while loops are bypassed because 1 % 2, 1 % 3, and 1 % 5 are all non-zero. The final comparison n == 1 evaluates to True, correctly classifying 1 as an ugly number (the conventional base case).

Large integers that consist solely of the allowed prime factors are efficiently reduced to 1 through repeated division. Conversely, numbers that contain a prime factor outside the set {2, 3, 5} will retain that factor after the loops, causing the final comparison to fail.

Performance Optimizations

The implementation exhibits several implicit performance optimizations:

  • Early termination for invalid inputs - The guard clause prevents the algorithm from entering the factor-removal loops when the result is predetermined, saving cycles for non-positive values.

  • In-place reduction - The variable n is updated directly within each loop, eliminating the need for auxiliary storage or additional data structures. This keeps memory usage minimal.

  • Sequential factor stripping - By handling each prime factor in a separate loop, the code avoids repeated modulo checks for the same divisor within a single iteration. Once a factor is no longer present, the loop exits, and the next divisor is examined.

  • Integer division - Using the floor division operator (//) ensures that the division operation yields an integer result without invoking floating-point arithmetic, which is both faster and avoids rounding issues.

  • Minimal branching - The algorithm consists of a single conditional branch at the start and a final boolean expression. The three while loops contain only a simple modulo test and an assignment, leading to predictable execution flow and good branch prediction characteristics on modern CPUs.

Overall, the method delivers a concise and efficient solution for determining ugly numbers, leveraging direct arithmetic operations and early exits to keep both time and space overhead low.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a number is like a small toy you want to take apart. This set of instructions checks if a number can be broken down into only very simple building blocks, which are the numbers two, three, and five.

First, the instructions look at the number. If the number is zero or smaller, it does not count as one of these special numbers.

Then, the instructions go through a series of steps to see if the number has any pieces of two inside of it. If it does, those pieces are taken away one by one. After that, it does the exact same thing for the number three, and finally for the number five. Each time, it keeps dividing the number until there are no more of those pieces left to take out.

At the very end, there is one last check. If the number has become one, it means it was made entirely out of those special building blocks.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.31 | σ = 0.91

Complexity Analysis

Time: logarithmic
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java JS Go PHP
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JS
fartem Ruby
fengvyi C++
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, PHP, Python
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
DimitrisJim C
everthis JavaScript
fartem Ruby
fengvyi C++
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lennylxx C
linouk23 C++
lkwq007 Python
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
zfang399 C++
47 links | 32 authors | 11 languages

Videos

16 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

1 easy 7 medium 1 hard
10 solutions   August 19, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality