Home>Article>Backend Development> How to implement a PHP class to calculate the factorial of an integer? (detailed code explanation)

How to implement a PHP class to calculate the factorial of an integer? (detailed code explanation)

藏色散人
藏色散人 Original
2018-11-12 10:21:05 4198browse

This article mainly introduces you to implement a PHP class to calculate the factorial of integers.

Recommended reference study: "PHP Tutorial"

First of all, let’s briefly understand whatfactorialis?

The factorial of a positive integer is the product of all positive integers less than and equal to the number, and the factorial of 0 is 1. The factorial of a natural number n is written n!.

To put it simply, for example, the factorial of 6 is 6!=1*2*3*4*5*6

So how do we implement the PHP class to calculate integers? of factorial?

The implementation code is as follows:

_n = $n; } public function result() { $factorial = 1; for ($i = 1; $i <= $this->_n; $i++) { $factorial *= $i; } return $factorial; } } $newfactorial = New factorial_of_a_number(5); echo $newfactorial->result(); ?>

The above code is to calculate the factorial of 5, and the output result is 120.

Related function introduction:

is_int() functionDetects whether the variable is an integer.

__construct() functionCreates a new SimpleXMLElement object. PHP 5 allows developers to define a method as a constructor in a class. Classes with a constructor will call this method every time a new object is created, so it is very suitable for doing some initialization work before using the object.

We can use a logic diagram to represent it:

How to implement a PHP class to calculate the factorial of an integer? (detailed code explanation)

This article introduces the method of implementing a PHP class to calculate integer factorials, which has a certain reference Value, I hope it will be helpful to friends in need!

The above is the detailed content of How to implement a PHP class to calculate the factorial of an integer? (detailed code explanation). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn