Numeric values (int and float behavior) in Python - Time & Space Complexity
When working with numbers in Python, it helps to know how the time to do math grows as numbers get bigger.
We want to see how long it takes to add or multiply numbers as their size changes.
Analyze the time complexity of the following code snippet.
num1 = 12345678901234567890
num2 = 98765432109876543210
result = num1 * num2
print(result)
This code multiplies two very large integers and prints the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Multiplying digits of large numbers internally.
- How many times: The multiplication process repeats roughly proportional to the number of digits in the numbers.
As the numbers get more digits, the time to multiply grows more than just adding more digits.
| Input Size (digits) | Approx. Operations |
|---|---|
| 10 | About 100 steps |
| 100 | About 10,000 steps |
| 1000 | About 1,000,000 steps |
Pattern observation: Doubling digits roughly squares the work needed for multiplication.
Time Complexity: O(n^2)
This means multiplying two numbers takes time roughly proportional to the square of their digit count.
[X] Wrong: "Multiplying numbers always takes the same time no matter how big they are."
[OK] Correct: Bigger numbers have more digits, so the computer must do more steps to multiply them.
Understanding how number size affects calculation time helps you explain efficiency clearly and shows you know what happens behind the scenes.
"What if we used floating-point numbers instead of integers? How would the time complexity change?"