forked from alianse777/solidity-standard-library
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMath.sol
More file actions
75 lines (67 loc) · 1.95 KB
/
Math.sol
File metadata and controls
75 lines (67 loc) · 1.95 KB
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
pragma solidity ^0.4.0;
/*
# Copyright (C) 2017 alianse777
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
contract Math{
/**
* @dev Compute square root of x
* @param x
* @return sqrt(x)
*/
function sqrt(uint x) internal pure returns (uint){
uint n = x / 2;
uint lstX = 0;
while (n != lstX){
lstX = n;
n = (n + x/n) / 2;
}
return uint(n);
}
/**
* @dev Compute modular exponential (x ** k) % m
* @param x k m
* @return uint
*/
function mexp(uint x, uint k, uint m) internal pure returns (uint r) {
r = 1;
for (uint s = 1; s <= k; s *= 2) {
if (k & s != 0) r = mulmod(r, x, m);
x = mulmod(x, x, m);
}
}
function abs(int x) internal pure returns (uint) {
if(x < 0) {
return uint(-x);
}
return uint(x);
}
function u_pow(uint x, uint p) internal pure returns (uint) {
if(p == 0) return 1;
if(p % 2 == 1) {
return u_pow(x, p-1)*x;
}
else
{
return u_pow(x, p / 2)*u_pow(x, p / 2);
}
}
function pow(int x, uint p) internal pure returns (int) {
int r = int(u_pow(abs(x), p));
if(p % 2 == 1) {
return -1*r;
}
return r;
}
}