-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
71 lines (58 loc) · 2.8 KB
/
Copy pathMain.java
File metadata and controls
71 lines (58 loc) · 2.8 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
68
69
70
71
import java.math.BigInteger;
import java.util.*;
import java.nio.file.*; // for reading file
import java.io.*; // for IOException
public class ParseJsonManual {
public static void main(String[] args) throws IOException {
// ---- Step 1: Read JSON from file ----
String json = new String(Files.readAllBytes(Paths.get("input.json")));
// ---- Step 2: Parse n and k ----
int n = Integer.parseInt(json.split("\"n\":")[1].split(",")[0].trim());
int k = Integer.parseInt(json.split("\"k\":")[1].split("}")[0].trim());
System.out.println("n = " + n + ", k = " + k);
// ---- Step 3: Extract x, base, value ----
List<BigInteger> xs = new ArrayList<>();
List<BigInteger> ys = new ArrayList<>();
for (int i = 1; i <= n; i++) {
String key = "\"" + i + "\": {";
int idx = json.indexOf(key);
if (idx != -1) {
int start = idx + key.length();
int end = json.indexOf("}", start);
String content = json.substring(start, end);
String baseField = "\"base\": \"";
int baseIdx = content.indexOf(baseField) + baseField.length();
int baseEnd = content.indexOf("\"", baseIdx);
String base = content.substring(baseIdx, baseEnd);
String valueField = "\"value\": \"";
int valueIdx = content.indexOf(valueField) + valueField.length();
int valueEnd = content.indexOf("\"", valueIdx);
String value = content.substring(valueIdx, valueEnd);
BigInteger xi = BigInteger.valueOf(i); // x = key number
BigInteger yi = new BigInteger(value, Integer.parseInt(base)); // decode
xs.add(xi);
ys.add(yi);
System.out.println("Point (" + xi + "," + yi + ")");
}
}
// ---- Step 4: Interpolation at x=0 ----
BigInteger c = lagrangeInterpolation(xs, ys, k, BigInteger.ZERO);
System.out.println("Constant term c = " + c);
}
// Lagrange interpolation for first k points
public static BigInteger lagrangeInterpolation(List<BigInteger> x, List<BigInteger> y, int k, BigInteger xEval) {
BigInteger result = BigInteger.ZERO;
for (int i = 0; i < k; i++) {
BigInteger term = y.get(i);
for (int j = 0; j < k; j++) {
if (i != j) {
BigInteger num = xEval.subtract(x.get(j));
BigInteger den = x.get(i).subtract(x.get(j));
term = term.multiply(num).divide(den); // exact division
}
}
result = result.add(term);
}
return result;
}
}