forked from TheAlgorithms/Solidity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactorial.sol
38 lines (32 loc) · 858 Bytes
/
factorial.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title This is a Solidity implementation to factorial.
* @author [Wenceslas Sanchez](https://github.com/wenceslas-sanchez)
*/
contract Factorial {
/**
* @notice Compute the factorial of a number iteratively.
*
*/
function factoIterative(uint256 _n) public pure returns (uint256) {
uint256 result = 1;
for (uint256 i = 2; i <= _n; ++i) {
result *= i;
}
return result;
}
/**
* @notice Compute the factorial of a number recursively.
*
*/
function factoRecursive(uint256 _n) public pure returns (uint256) {
uint256 result;
if (_n == 1 || _n == 0) {
result = 1;
} else {
result = _n * factoRecursive(_n - 1);
}
return result;
}
}