Integer and Float number types in Ruby - Time & Space Complexity
When working with numbers in Ruby, it is helpful to understand how operations on integers and floats affect the time it takes to run your program.
We want to see how the time needed changes as the numbers get bigger or more precise.
Analyze the time complexity of the following code snippet.
def sum_numbers(numbers)
total = 0
numbers.each do |num|
total += num
end
total
end
This code adds up all numbers in an array, which can include both integers and floats.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Adding each number to a total inside a loop.
- How many times: Once for every number in the list.
As the list of numbers grows, the time to add them all grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The time grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to add numbers grows in a straight line with how many numbers there are.
[X] Wrong: "Adding floats takes longer than adding integers, so time grows faster with floats."
[OK] Correct: While floats are a bit more complex inside the computer, the addition operation still happens once per number, so the overall time still grows linearly with the list size.
Understanding how simple operations like adding numbers scale helps you explain how your code will behave with bigger data, a skill that shows you think about efficiency clearly.
"What if we changed the code to multiply each number instead of adding? How would the time complexity change?"