PHP-Factorial-program-using-GMP-Functions.md 1.5 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
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.

Rohan Rajan Sangita Sakhale's avatar
Rohan Rajan Sangita Sakhale committed
16
<!-- more -->
17 18 19 20 21 22 23 24
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.

25
### Code
26 27 28

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