## DEV Community is a community of 725,972 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# How to write a php class that calculates the factorial of an integer?

Let's understand the two key terms used above;

• FACTORIAL - the product of an integer and all the integers below it; e.g. factorial four ( 4! ) is equal to 24.(4 X 3 X 2 X 1)

• INTEGER - Integer is a number which is not a fraction, you could also say that an integer is a whole number

COOL!

Now let's solve the problem, the class we are asked to write has two main requirements

1) It should filter out the integers
2) It should return the factorial of that filtered number/integer

To meet 1) above we can use the function is_int() in php , so using the if condition with this function, we could say "if (!is_int(n)) { Do not run the program or perhaps throw an error}"

To return a factorial of a number we can Loop through all the numbers that are less than or equal to the integer that was passed in-while storing the product of all the numbers in a variable that can be returned when the loop is over.

Here's a way of doing this,

``````<?php

public function myFactorial()
{

\$factorial = 1;

for(\$i= 1; \$i<=\$this->number; \$i++)
{
\$factorial = \$factorial*\$i;
}

return \$factorial;

}
?>

``````

Why are we doing;

\$factorial = \$factorial*\$i

And whats the meaning of it ?

\$i in the above line is changing each time we loop (ie. it starts at 1 and increments till it reaches the value of the integer that was passed in)

Left hand side \$factorial is assigned the product of right hand side \$factorial and \$i in each iteration.

Let's say we wanted to find the factorial of 3. (then \$this->number would be 3)

First iteration - we will have the following values

\$i = 2 , Right hand side \$factorial = 1; (although \$i starts with one it will be incremented by one during the first iteration as we have \$i++ in the for loop)

Therefore Left hand side \$factorial = 1 multiplied by 2 .(ie. 2)

Second iteration

\$i = 3 , Right hand side \$factorial = 2;

Therefore Left hand side \$factorial = 2 multiplied by 3 . (ie. 6)

Ok will there be a third iteration? "NO" WHY?

Next iteration , \$i = 4 and we have a condition in the for loop that says 'Continue the loop as long as \$i is less than or equal to 3'.

Here's the complete solution;

``````<?php

Class find_my_factorial
{

protected \$integer;

public function __construct(\$passedInt)
{
if(!is_int(\$passedInt))
{
throw new InvalidArgumentException('Not a valid integer');
}

\$this->integer = \$passedInt;

public function myFactorial()
{
\$factorial = 1;
for(\$i = 1; \$i<= \$this->integer; \$i++)
{
\$factorial = \$factorial *\$i;
}
return \$factorial;
}
}

//Instantiating the above class,

\$Twofact = New find_my_factorial(2);

echo \$Twofact->myFactorial();

?>
``````