-
-
Notifications
You must be signed in to change notification settings - Fork 95
/
lucasSeries.sol
76 lines (65 loc) · 2.04 KB
/
lucasSeries.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title This is a Solidity implementation to Lucas sequence problem.
* @author [Wenceslas Sanchez](https://github.com/wenceslas-sanchez)
* @dev Related to Fibonacci sequence number.
*/
contract LucasSeries {
/**
* @notice Computes the n-th (0-indexed) Lucas number using recursion.
* @dev This method use a lot of gas to run. Recursive methods are not good ideas.
* For instance with RemixIDE, its hard to go further 10th term.
*/
function lucasRecursiveTerm(uint256 _n)
public
pure
returns (uint256 result)
{
if (_n == 0) {
result = 2;
} else if (_n == 1) {
result = 1;
} else {
result = lucasRecursiveTerm(_n - 1) + lucasRecursiveTerm(_n - 2);
}
return result;
}
/**
* @notice Computes the first n (0-indexed) Lucas numbers using recursion
* @dev It is based on lucasRecursiveTerm => consume a lot of gas
* for large _n.
*/
function lucasRecursive(uint256 _n) public pure returns (uint256[] memory) {
uint256[] memory result = new uint256[](_n + 1);
for (uint256 i = 0; i < _n + 1; i++) {
result[i] = lucasRecursiveTerm(i);
}
return result;
}
/**
* @notice Computes the n_th (0-indexed) Lucas numbers.
*/
function lucasDynamicTerm(uint256 _n) public pure returns (uint256) {
uint256 a = 2;
uint256 b = 1;
uint256 c;
for (uint256 i = 0; i < _n; i++) {
c = b;
b = a + b;
a = c;
}
return a;
}
/**
* @notice Computes the first n (0-indexed) Lucas numbers
* @dev No 'limitation' in term of gas consumption.
*/
function lucasDynamic(uint256 _n) public pure returns (uint256[] memory) {
uint256[] memory result = new uint256[](_n + 1);
for (uint256 i = 0; i < _n + 1; i++) {
result[i] = lucasDynamicTerm(i);
}
return result;
}
}