Arithmetic operators in C Sharp (C#) - Time & Space Complexity
Arithmetic operators perform basic math on numbers in a program.
We want to see how the time to do these operations changes as input size grows.
Analyze the time complexity of the following code snippet.
int Add(int a, int b) {
return a + b;
}
int Multiply(int a, int b) {
return a * b;
}
int result = Add(5, 3);
int product = Multiply(4, 7);
This code adds and multiplies two numbers using arithmetic operators.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single arithmetic operations (addition and multiplication).
- How many times: Each operation runs exactly once.
Each arithmetic operation takes the same time no matter the input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 |
| 100 | 2 |
| 1000 | 2 |
Pattern observation: The number of operations stays the same even if numbers get bigger.
Time Complexity: O(1)
This means the time to do arithmetic does not grow with input size; it stays constant.
[X] Wrong: "Adding bigger numbers takes more time than smaller numbers."
[OK] Correct: Computers handle numbers in fixed steps, so addition or multiplication takes the same time regardless of number size.
Understanding that basic math operations run in constant time helps you reason about more complex code efficiently.
"What if we replaced single arithmetic operations with a loop that adds numbers repeatedly? How would the time complexity change?"