Ugly Number - Problem

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, otherwise return false.

Note: 1 is typically treated as an ugly number. Negative numbers and zero are not ugly numbers.

Input & Output

Example 1 — Basic Ugly Number
$ Input: n = 6
Output: true
💡 Note: 6 = 2 × 3, so it only has prime factors 2 and 3, making it ugly
Example 2 — Not Ugly Number
$ Input: n = 14
Output: false
💡 Note: 14 = 2 × 7, and 7 is a prime factor other than 2, 3, 5, so 14 is not ugly
Example 3 — Edge Case
$ Input: n = 1
Output: true
💡 Note: 1 has no prime factors, so by convention it is considered an ugly number

Constraints

  • -231 ≤ n ≤ 231 - 1

Visualization

Tap to expand
Ugly Number - Division Method INPUT n = 6 Allowed Prime Factors: 2 3 5 6 = 2 x 3 Is 6 an ugly number? (only factors 2, 3, 5?) ALGORITHM STEPS 1 Check Base Cases n <= 0 --> return false 6 > 0, continue 2 Divide by 2 While n % 2 == 0: 6 / 2 = 3 3 Divide by 3 While n % 3 == 0: 3 / 3 = 1 4 Divide by 5 While n % 5 == 0: 1 % 5 != 0, skip Check: n == 1? --> 1 == 1 OK 6 --> 3 --> 1 FINAL RESULT Output: true 6 IS an ugly number! Verification: 6 = 2 x 3 Only uses factors 2 and 3 Both are allowed! OK Counter-example: 14 = 2 x 7 (7 not allowed) 14 is NOT ugly Key Insight: The Division Method repeatedly divides n by 2, 3, and 5 until it can no longer be divided. If the final result is 1, all prime factors were 2, 3, or 5 --> ugly number. Time: O(log n) TutorialsPoint - Ugly Number | Division Method Approach
Asked in
Facebook 12 Google 8 Amazon 6
89.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen