PHP program to find the first natural number whose factorial can be divided by a number 'x'

To find the first natural number whose factorial can be divided by a number 'x', we need to calculate factorials incrementally and check divisibility until we find a match.

Example

The following PHP program finds the first natural number whose factorial is divisible by a given number ?

<?php
function factorial_num($x_val)
{
    $i = 1;
    $fact_num = 1;
    
    while (true) {
        $fact_num = $fact_num * $i;
        
        if ($fact_num % $x_val == 0) {
            return $i;
        }
        $i++;
    }
}

$x_val = 16;
echo "The first natural number whose factorial can be divided by " . $x_val . " is ";
echo factorial_num($x_val);
?>

Output

The first natural number whose factorial can be divided by 16 is 4

How It Works

The function factorial_num() starts with $fact_num = 1 and multiplies it by consecutive natural numbers (1, 2, 3, ...). At each step, it checks if the current factorial is divisible by the target number $x_val. When divisibility is found, it returns the current natural number.

For example, with x = 16:

  • 1! = 1 (not divisible by 16)
  • 2! = 2 (not divisible by 16)
  • 3! = 6 (not divisible by 16)
  • 4! = 24 (divisible by 16) ?

Conclusion

This algorithm efficiently finds the first natural number whose factorial is divisible by a given number by computing factorials incrementally and checking divisibility at each step.

Updated on: 2026-03-15T09:07:02+05:30

267 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements