Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

c++ - first n digits of an exponentiation

How do i determine the first n digits of an exponentiation (ab).

eg: for a = 12, b = 13 & n = 4, the first 4 digits are 1069.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 forumula. 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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...