phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - Number: Calculating Factorials

Tag: number, calculation, factorial   Category: PHP Basic
post: 16 Mar 2008 read: 208


PHP Number Tips - Part 12: In order to find the factorial number, you can use a loop to count down and multiply the number by all the numbers between itself and 1 such as:

<?php
//define number
$num = 5;

//initialize variable
$factorial = 1;

//calculate factorial
//by multiplying the number by all the
//numbers between itself and 1
//result: "Factorial of 5 is 120"
for ($x=$num; $x>=1; $x--) {
  $factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>

A factorial of a number n is the product of all the numbers between n and 1. The easiest way to calculate it is with a for( ) loop which one that starts at n and counts down to 1. Each time the loop runs, the previously calculated product is multiplied by the current value of the loop counter and the result is the factorial of the number n.




| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Chart: How to Build Cool Animation Real Time Chart
Joomla: Fast Road to Understand Component Programming
Email: Send Attachement Mail
mod_rewrite - Part 1: create your "fantasy" URL

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


615
posting