Factorial Using PHP

The factorial of a number n is defined by the product of all the digits from 1 to n (including 1 and n).

For example,

  1. 4! = 4*3*2*1 = 24
  2. 6! = 6*5*4*3*2*1 = 720

Note:

  • It is denoted by n! and is calculated only for positive integers.
  • Factorial of 0 is always 1.

The simplest way to find the factorial of a number is by using a loop.

There are two ways to find factorial in PHP:

  • Using loop
  • Using recursive method

Logic:

  • Take a number.
  • Take the descending positive integers.
  • Multiply them.

 

Factorial using Form in PHP

Below program shows a form through which you can calculate factorial of any number.

 

<html>

<head>

<title>Factorial Program using loop in PHP</title>

</head>

<body>

<form method=“post”>

Enter the Number:<br>

<input type=“number” name=“number” id=“number”>

<input type=“submit” name=“submit” value=“Submit” />

</form>

<?php

if($_POST){

$fact = 1;

//getting value from input text box ‘number’

$number = $_POST[‘number’];

echo “Factorial of $number:<br><br>”;

//start loop

for ($i = 1; $i <= $number$i++){

$fact = $fact * $i;

}

echo $fact . “<br>”;

}

?>

</body>

</html>

2 thoughts on “Factorial Using PHP

  1. Hi there! I know this is somewhat off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

    Like

Leave a comment