Calculate ab by the following iterations:
a1 = a1,
a2 = a2,
...
ai = ai,
...
ab = ab
You have ai+1 = ai×a. Calcluate each ai not exactly. The thing is that the relative error of ab is less than n times relative error of a.
You want to get final relative error less than 10-n. Thus relative error on each step may be . Remove last digits at each step.
For example, a=2, b=16, n=1. Final relative error is 10-n = 0.1. Relative error on each step is 0.1/16 > 0.001. Thus 3 digits is important on each step. If n = 2, you must save 4 digits. Common rule: save [n+log10 b] digits at each step.
2 (1), 4 (2), 8 (3), 16 (4), 32 (5), 64 (6), 128 (7), 256 (8), 512 (9), 1024 (10) → 102,
204 (11), 408 (12), 816 (13), 1632 (14) → 163, 326 (15), 652 (16).
Answer: 6.
This algorithm has a compexity of O(b). But it is easy to change it to get O(log b)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…