Integer overflow and underflow in Blockchain / Solidity - Time & Space Complexity
When working with numbers in blockchain, it is important to understand how operations on integers behave as the input size changes.
We want to know how the time to check or handle integer overflow or underflow grows when numbers get bigger.
Analyze the time complexity of the following code snippet.
function safeAdd(uint256 a, uint256 b) public pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "Overflow detected");
return c;
}
This function adds two numbers and checks if the result caused an overflow by comparing it to the first number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: A single addition and comparison.
- How many times: Exactly once per function call, no loops or recursion.
The time to add two numbers and check for overflow stays the same no matter how large the numbers are.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 (add + compare) |
| 100 | 2 (add + compare) |
| 1000 | 2 (add + compare) |
Pattern observation: The number of operations does not increase with input size; it stays constant.
Time Complexity: O(1)
This means the time to check for overflow or underflow does not grow as the numbers get bigger; it takes the same amount of time every time.
[X] Wrong: "Adding bigger numbers takes more time because the numbers are larger."
[OK] Correct: Computers handle fixed-size numbers in constant time, so addition and comparison take the same time regardless of number size.
Understanding that integer operations run in constant time helps you explain how smart contracts handle numbers safely and efficiently.
"What if we changed from fixed-size integers to arbitrary large integers? How would the time complexity change?"