Arithmetic operators in Kotlin - Time & Space Complexity
We want to see how the time to run arithmetic operations changes as we use more numbers.
How does the program's work grow when doing simple math on inputs?
Analyze the time complexity of the following code snippet.
fun sumArray(numbers: IntArray): Int {
var total = 0
for (num in numbers) {
total += num
}
return total
}
This code adds up all numbers in an array using arithmetic operators.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Addition inside the loop (total += num)
- How many times: Once for each number in the array
Each new number means one more addition operation.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to add numbers grows in a straight line as the list gets longer.
[X] Wrong: "Arithmetic operations like addition take more time as numbers get bigger."
[OK] Correct: In most programming languages, simple arithmetic operations take constant time regardless of the number size.
Understanding how loops with arithmetic operations scale helps you explain code efficiency clearly and confidently.
"What if we replaced the loop with a recursive function doing the same additions? How would the time complexity change?"