Horje
PHP Program to Check for Lucky Numbers

We have given an input number, and our task is to check if it is a lucky number or not in PHP based on the criteria that all digits in the number must be different.

Examples:

Input: n = 7
Output: 7 is a lucky numberInput: n = 9
Output: 9 is not a lucky number

Below are the approaches to check for lucky numbers in PHP:

Table of Content

Using for Loop

In this approach, we are using a for loop to iterate through numbers from 2 to n−1 to check if n has any divisors other than 1 and itself. If any such divisor is found, the count variable is incremented. Finally, if the count is greater than 0, the number n is deemed not lucky; otherwise, it is considered a lucky number.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php
$n = 9; 
$count = 0;
for ($i = 2; $i < $n; $i++) {
    if ($n % $i == 0) {
        $count++;
    }
}
if ($count > 0) {
    echo "$n is not a lucky number";
} else {
    echo "$n is a lucky number";
}
?>

Output
9 is not a lucky number

Using Array

In this approach, we are using an array to track removed elements, initializing it with false values representing numbers that are not yet removed. The code iteratively marks multiples of each prime number as removed, finally determining if the input number is lucky based on its presence in the array.

Example: This example shows the implementation of the above-explained approach.

PHP
<?php
$n = 9;

$removed = array_fill(0, $n + 1, false);
$i = 2;

while ($i <= $n) {
    if (!$removed[$i]) {
        $j = $i + $i;
        while ($j <= $n) {
            $removed[$j] = true;
            $j += $i;
        }
    }
    $i++;
}

if ($removed[$n]) {
    echo "$n is not a lucky number";
} else {
    echo "$n is a lucky number";
}
?>

Output
9 is not a lucky number



Reffered: https://www.geeksforgeeks.org


PHP

Related
How to Sort Numeric Array in PHP? How to Sort Numeric Array in PHP?
How to get the Difference Between Two Arrays in PHP? How to get the Difference Between Two Arrays in PHP?
Merge Two Arrays &amp; Remove Duplicate Items in PHP Merge Two Arrays &amp; Remove Duplicate Items in PHP
How to Remove Multiple Elements from an Array in PHP? How to Remove Multiple Elements from an Array in PHP?
How to Compare Two Arrays in PHP? How to Compare Two Arrays in PHP?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18