forked from Synthetixio/synthetix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMath.sol
34 lines (28 loc) · 882 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
31
32
33
34
pragma solidity 0.4.25;
import "./SafeDecimalMath.sol";
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;
}
}