-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrootNumber.java
More file actions
67 lines (44 loc) · 1.68 KB
/
rootNumber.java
File metadata and controls
67 lines (44 loc) · 1.68 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Root of Number
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 function root that calculates the n’th root of a number. The function takes a nonnegative number x and a positive integer n, and returns the positive n’th root of x within an error of 0.001 (i.e. suppose the real root is y, 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 here), 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:
input: x = 7, n = 3
output: 1.913
input: x = 9, n = 2
output: 3
Constraints:
[time limit] 5000ms
[input] float x
0 ≤ x
[input] integer n
0 < n
[output] float
*/
import java.io.*;
import java.util.*;
class Solution {
static double root(double x, int n) {
if (x == 0) {
return 0;
}
double low = 0;
double high = Math.max(1,x);
double approxRoot = (low + high)/2;
while (approxRoot - low >= 0.001) {
if (Math.pow(approxRoot, n) > x) {
high = approxRoot;
} else if (Math.pow(approxRoot, n) < x) {
low = approxRoot;
} else {
break;
}
approxRoot = (low + high)/2;
}
return approxRoot;
}
public static void main(String[] args) {
}
}