/
SafeMathWithRequire.sol
63 lines (58 loc) · 1.84 KB
/
SafeMathWithRequire.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
//SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert
*/
library SafeMathWithRequire {
uint256 private constant DECIMALS_18 = 1000000000000000000;
uint256 private constant DECIMALS_12 = 1000000000000;
uint256 private constant DECIMALS_9 = 1000000000;
uint256 private constant DECIMALS_6 = 1000000;
function sqrt6(uint256 a) internal pure returns (uint256 c) {
a = a * DECIMALS_12;
uint256 tmp = (a + 1) / 2;
c = a;
// tmp cannot be zero unless a = 0 which skip the loop
while (tmp < c) {
c = tmp;
tmp = ((a / tmp) + tmp) / 2;
}
}
function sqrt3(uint256 a) internal pure returns (uint256 c) {
a = a * DECIMALS_6;
uint256 tmp = (a + 1) / 2;
c = a;
// tmp cannot be zero unless a = 0 which skip the loop
while (tmp < c) {
c = tmp;
tmp = ((a / tmp) + tmp) / 2;
}
}
function cbrt6(uint256 a) internal pure returns (uint256 c) {
a = a * DECIMALS_18;
uint256 tmp = (a + 2) / 3;
c = a;
// tmp cannot be zero unless a = 0 which skip the loop
while (tmp < c) {
c = tmp;
uint256 tmpSquare = tmp**2;
require(tmpSquare > tmp, "overflow");
tmp = ((a / tmpSquare) + (tmp * 2)) / 3;
}
return c;
}
function cbrt3(uint256 a) internal pure returns (uint256 c) {
a = a * DECIMALS_9;
uint256 tmp = (a + 2) / 3;
c = a;
// tmp cannot be zero unless a = 0 which skip the loop
while (tmp < c) {
c = tmp;
uint256 tmpSquare = tmp**2;
require(tmpSquare > tmp, "overflow");
tmp = ((a / tmpSquare) + (tmp * 2)) / 3;
}
return c;
}
}