forked from Synthetixio/synthetix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMath.sol
30 lines (26 loc) · 928 Bytes
/
Math.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
pragma solidity ^0.5.16;
// Libraries
import "./SafeDecimalMath.sol";
// https://docs.synthetix.io/contracts/source/libraries/math
library Math {
using SafeMath for uint;
using SafeDecimalMath for uint;
/**
* @dev Uses "exponentiation by squaring" algorithm where cost is 0(logN)
* vs 0(N) for naive repeated multiplication.
* Calculates x^n with x as fixed-point and n as regular unsigned int.
* Calculates to 18 digits of precision with SafeDecimalMath.unit()
*/
function powDecimal(uint x, uint n) internal pure returns (uint) {
// https://mpark.github.io/programming/2014/08/18/exponentiation-by-squaring/
uint result = SafeDecimalMath.unit();
while (n > 0) {
if (n % 2 != 0) {
result = result.multiplyDecimal(x);
}
x = x.multiplyDecimal(x);
n /= 2;
}
return result;
}
}