RootOfNumber
Last updated
Was this helpful?
Last updated
Was this helpful?
Many times, we need to re-implement basic functions without using any standard library functions already implemented. For example, when designing a chip that requires very little memory space.
In this question we’ll implement a functionroot
that calculates then’th
root of a number. The function takes a nonnegative numberx
and a positive integern
, and returns the positiven’th
root ofx
within an error of0.001
(i.e. suppose the real root isy
, then the error is:|y-root(x,n)|
and must satisfy|y-root(x,n)| < 0.001
).
Don’t be intimidated by the question. While there are many algorithms to calculate roots that require prior knowledge in numerical analysis (some of them are mentioned ), there is also an elementary method which doesn’t require more than guessing-and-checking. Try to think more in terms of the latter.
Make sure your algorithm is efficient, and analyze its time and space complexities.
Examples:
Constraints:
[time limit] 5000ms
[input] floatx
0 ≤ x
[input] integern
0 < n
[output] float
这题就是改了一下。那题开平方,这题能开n方。做法还是二分。这里还学了个优雅点的写法。