Leetcode. 263. Ugly Number

Edgar
2 min readSep 7, 2024

--

private val primes = List(2, 3, 5)

def isUgly(n: Int): Boolean =
var result = n
for (prime <- primes)
while (result > 1 && result % prime == 0)
result /= prime
result == 1

The Scala code snippet defines a function `isUgly` which classifies a number as an “ugly number.” Ugly numbers are special in that they are positive integers whose only prime factors are 2, 3, and 5. This concept is rooted in number theory and is particularly useful in problems involving sequence generation and optimization where simplicity in factors leads to fewer complications in calculations.

Here’s a breakdown of the code’s mechanism:

1. Prime List Initialization: It starts with defining a list `primes` containing the integers 2, 3, and 5. These primes are the only factors that define an ugly number.

2. Function Setup: The function `isUgly` takes an integer `n` and uses a mutable variable `result` to manipulate and evaluate the number.

3. Iterative Factor Reduction: Through a combination of a `for` loop and a nested `while` loop, the code iteratively divides `result` by each prime in the `primes` list. The division continues as long as `result` is divisible by the current prime, effectively stripping away these prime factors.

4. Final Evaluation: After the loops conclude, the number’s “ugliness” is determined by whether `result` has been reduced to 1. If so, `n` consisted solely of the primes 2, 3, and 5, qualifying it as an ugly number.

5. Return Statement: The function returns `true` if `n` is an ugly number, indicating that it contains no prime factors other than 2, 3, and 5, and `false` otherwise.

This elegant solution showcases the power of Scala’s collections and looping constructs to solve an interesting problem from theoretical computer science and mathematics, highlighting the importance of factorization in computational theory. The function is concise yet powerful, illustrating the utility of focusing on specific factors to classify integers in a specific subset.

--

--

Edgar

Software engineer building composable and then reliable systems