PHP-Factorial-program-using-GMP-Functions.md 1.48 KB
Newer Older
1 2 3 4 5 6 7 8 9
---
title: PHP Factorial program using GMP Functions
date: 2012-06-04 17:13:14
categories:
	- Codes
tags:
	- code-example
	- php
---
10 11
### Summary

12 13 14 15 16 17 18 19 20 21 22 23
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](http://www.php.net/manual/en/ref.gmp.php).

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.

24
### Code
25 26 27

```php
<?php
28 29 30
if (isset($_POST['submit']) and $_POST['submit'] == 'Generate') {
    if (isset($_POST['num']) and is_numeric($_POST['num'])) {
        $num = $_POST['num'];
31
        $fact = gmp_fact($num);
32
        echo 'Factorial of Number (' . $num . ') is' . $fact . '<br />';
33
    } else {
34
        echo 'Enter proper number<br />';
35 36 37
    }
}
?>
38 39 40
<form action="" method="post">
    Enter Number: <input type="text" name="num" /><br />
    <input type="submit" name="submit" value="Generate" />
41 42
</form>
```