Check Whether a Given Number is Ugly Number or Not in PHP
Last Updated :
10 Jul, 2024
Given an integer N, the task is to find out whether the given number is an Ugly number or not.
Ugly numbers are numbers whose only prime factors are 2, 3 or 5.
Examples:
Input: N = 14
Output: No
Explanation:
14 is not ugly since it includes another prime factor 7.
Input: N = 6
Output: Yes
Explanation:
6 is a ugly since it includes 2 and 3.
Below are the approaches to check whether a given number is ugly number or not in PHP:
Using a Queue
In this approach, we are using a queue to generate ugly numbers by multiplying the smallest current ugly number by 2, 3, and 5, and adding the results back to the list if they are not already present. By continuously expanding the list and checking if the given number is within it, we determine if the number is an ugly number.
Example: This example shows the implementation of the above-explained approach.
JavaScript
<?php
$number = 14;
$ugly_numbers = [1];
$index = 0;
while (count($ugly_numbers) < $number) {
$next_ugly = $ugly_numbers[$index];
$index++;
$new_ugly1 = $next_ugly * 2;
$new_ugly2 = $next_ugly * 3;
$new_ugly3 = $next_ugly * 5;
if (!in_array($new_ugly1, $ugly_numbers)) {
$ugly_numbers[] = $new_ugly1;
}
if (!in_array($new_ugly2, $ugly_numbers)) {
$ugly_numbers[] = $new_ugly2;
}
if (!in_array($new_ugly3, $ugly_numbers)) {
$ugly_numbers[] = $new_ugly3;
}
sort($ugly_numbers);
}
if (in_array($number, $ugly_numbers)) {
echo "YES";
} else {
echo "NO";
}
?>
Output
NO
Using Recursive Division
In this approach, we are using recursive division to repeatedly divide the given number by 2, 3, or 5. If the number reduces to 1, it is an ugly number; otherwise, it is not. The function recursively checks divisibility until it confirms or rejects the number's status as an ugly number.
Example: This example shows the implementation of the above-explained approach.
PHP
<?php
$number = 6;
function isUgly($num) {
if ($num <= 0) return false;
if ($num == 1) return true;
if ($num % 2 == 0) return isUgly($num / 2);
if ($num % 3 == 0) return isUgly($num / 3);
if ($num % 5 == 0) return isUgly($num / 5);
return false;
}
if (isUgly($number)) {
echo "YES";
} else {
echo "NO";
}
?>
Output
YES
Using Iterative Division
In this approach, we are using iterative division to repeatedly divide the given number by 2, 3, or 5. By continuously dividing the number by these prime factors, if the number reduces to 1, it is an ugly number; otherwise, it is not.
Example: This example shows the implementation of the above-explained approach.
PHP
<?php
$number = 14;
function isUgly($num) {
if ($num <= 0) return false;
foreach ([2, 3, 5] as $prime) {
while ($num % $prime == 0) {
$num /= $prime;
}
}
return $num == 1;
}
if (isUgly($number)) {
echo "YES";
} else {
echo "NO";
}
?>