Optimized gas costs in ceilDiv (#4553)
This commit is contained in:
@ -110,8 +110,14 @@ library Math {
|
||||
return a / b;
|
||||
}
|
||||
|
||||
// (a + b - 1) / b can overflow on addition, so we distribute.
|
||||
return a == 0 ? 0 : (a - 1) / b + 1;
|
||||
// The following calculation ensures accurate ceiling division without overflow.
|
||||
// Since a is non-zero, (a - 1) / b will not overflow.
|
||||
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
|
||||
// but the largest value we can obtain is type(uint256).max - 1, which happens
|
||||
// when a = type(uint256).max and b = 1.
|
||||
unchecked {
|
||||
return a == 0 ? 0 : (a - 1) / b + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user