Math.sol 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. // SPDX-License-Identifier: MIT
  2. pragma solidity ^0.8.0;
  3. /**
  4. * @dev Standard math utilities missing in the Solidity language.
  5. */
  6. library Math {
  7. /**
  8. * @dev Returns the largest of two numbers.
  9. */
  10. function max(uint256 a, uint256 b) internal pure returns (uint256) {
  11. return a >= b ? a : b;
  12. }
  13. /**
  14. * @dev Returns the smallest of two numbers.
  15. */
  16. function min(uint256 a, uint256 b) internal pure returns (uint256) {
  17. return a < b ? a : b;
  18. }
  19. /**
  20. * @dev Returns the average of two numbers. The result is rounded towards
  21. * zero.
  22. */
  23. function average(uint256 a, uint256 b) internal pure returns (uint256) {
  24. // (a + b) / 2 can overflow, so we distribute.
  25. return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
  26. }
  27. /**
  28. * @dev Returns the ceiling of the division of two numbers.
  29. *
  30. * This differs from standard division with `/` in that it rounds up instead
  31. * of rounding down.
  32. */
  33. function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
  34. // (a + b - 1) / b can overflow on addition, so we distribute.
  35. return a / b + (a % b == 0 ? 0 : 1);
  36. }
  37. }