The problem
A whole number is given as a list of its decimal digits, most significant first: [1, 3, 2, 1] is 1321. Multiply two such numbers and return the product in the same form, with no leading zeros (zero itself is [0]).
multiply([1, 3, 2, 1], [2, 2, 1, 3]) # [2, 9, 2, 3, 3, 7, 3]
multiply([9, 9], [0]) # [0]
This problem is about writing Karatsuba’s method yourself, so work on the digits. Do not turn the lists into Python ints: Python’s own multiplication already uses Karatsuba’s method in C (lesson 5), so that would skip the exercise. The tests cannot check this; it is up to you.
Limits
- Up to 12,000 digits in each number. The schoolbook method, O(n²), is too slow for the largest test; aim for O(n¹·⁵⁸⁵).
- The inputs have no leading zeros, except the number 0 itself.
Builds on DVCQ-5 Karatsuba multiplication.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | Times zero | Not run | |
| 3 | One digit each | Not run | |
| 4 | Different lengths | Not run | |
| 5 | Many carries | Not run | |
| 6 | Powers of ten | Not run | |
| 7 | 100 digits by 3 digits | Not run | |
| 8 | 300 digits each | Not run | |
| 9 | 4,000 digits each | Not run | |
| 10 | 12,000 digits each | Not run |