Int, Long, Float, Double number types in Kotlin - Time & Space Complexity
Let's see how the time it takes to work with different number types changes as we do more operations.
We want to know how the size of the input affects the time to process numbers like Int, Long, Float, and Double.
Analyze the time complexity of the following code snippet.
fun sumNumbers(numbers: List): Double {
var sum = 0.0
for (num in numbers) {
sum += num.toDouble()
}
return sum
}
This code adds up a list of numbers, converting each to Double before adding.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list once.
- How many times: Exactly once for each number in the input list.
As the list gets bigger, the time to add all numbers grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time grows directly with the number of items you add.
[X] Wrong: "Using Double or Float makes the code slower because they are more complex types than Int or Long."
[OK] Correct: The time to add numbers depends mostly on how many numbers you process, not the specific number type. The difference in speed between these types is usually very small and does not change the overall growth pattern.
Understanding how the size of data affects processing time is a key skill. It helps you write code that stays fast even as data grows.
"What if we changed the list to a nested list of numbers and summed all inner lists? How would the time complexity change?"