Java/PHP/GitLab Fan, Passionate Developer and Loves Teaching

0%

PHP Factorial Program Using GMP Functions

Summary

Regular working with arbitrary number is usually a tough job, normally for generating factorial number using the regular looping methods you can generate only upto 170, and it doesn’t work for huge numbers.

GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers.

GMP functions allow you to work with arbitrary-length integers using the GNU MP library.

You may need to do the initializations of GMP onto the server side if it don’t work directly, read on php.net for it.

For complete reference on GMP functions visit here.

The following code accepts a number from user and on the server side it is checked if numeric and passed onto the gmp_fact() method which returns the factorial of it and output is displayed on the screen.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
if (isset($_POST['submit']) and $_POST['submit'] == 'Generate') {
if (isset($_POST['num']) and is_numeric($_POST['num'])) {
$num = $_POST['num'];
$fact = gmp_fact($num);
echo 'Factorial of Number (' . $num . ') is' . $fact . '<br />';
} else {
echo 'Enter proper number<br />';
}
}
?>
<form action="" method="post">
Enter Number: <input type="text" name="num" /><br />
<input type="submit" name="submit" value="Generate" />
</form>