Content deleted Content added
→Ancient Indian algorithm for multiplying numbers close to a round number: Because who cares if it's Indian or ancient |
changed the pseudocode in Long multiplication to be is similar format. Also removed unnessesary section heading that was for pseudocode |
||
Line 53:
———————————————
139676498390 ( = 139,676,498,390 )
Below pseudocode describes the process of above multiplication. It keeps only one row to maintain sum which finally becomes the result. Note that
▲Below pseudocode describes the process of above multiplication. It keeps only one row to maintain sum which finally becomes the result. Note that we use '+=' operator to denote sum to existing value and store operation (akin to languages such as Java and C) for compactness.
<source lang="pascal">
multiply(a[1..p], b[1..q], base) // Operands containing rightmost digits at index 1
for b_i = 1 to q // for all digits in b
carry = 0
for
carry =
return
</source>
Line 82 ⟶ 80:
A simple inductive argument shows that the carry can never exceed ''n'' and the total sum for ''r''<sub>''i''</sub> can never exceed ''D'' * ''n'': the carry into the first column is zero, and for all other columns, there are at most ''n'' digits in the column, and a carry of at most ''n'' from the previous column (by the induction hypothesis). The sum is at most ''D'' * ''n'', and the carry to the next column is at most ''D'' * ''n'' / ''D'', or ''n''. Thus both these values can be stored in O(log ''n'') digits.
In pseudocode, the log-space algorithm is:<syntaxhighlight lang="pascal">
▲ '''multiply'''(a[1..p], b[1..q], base) // Operands containing rightmost digits at index 1
for ri = 1 to p + q - 1 //For each digit of result
▲ sum ← 0
tot
product[ri] = tot mod base
tot
product[p+q] = tot mod base //Last digit of the result comes from last carry
return product
▲ result[p+q] ← sum mod base //Last digit of the result comes from last carry
</syntaxhighlight>
===Electronic usage===
|