Skip to main content
Back to problems
#263
Easy Algorithms

Ugly number

Math
43.2% acceptance
Jan 12, 2026
3818
1791
An ugly number is a positive integer which does not have a prime factor other than 2, 3, and 5. Given an integer n, return true if n is an ugly number.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn is_ugly(n: i32) -> bool {
    if n <= 0 {
      return false;
    }
    
    let mut n = n;
    for factor in [2, 3, 5] {
      while n % factor == 0 {
        n /= factor;
      }
    }
    
    n == 1
  }
}