-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
57 lines (47 loc) · 1.16 KB
/
main.go
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
// An implementation of https://en.wikipedia.org/wiki/Shamir%27s_Secret_Sharing
// This video explains it: https://www.youtube.com/watch?v=kkMps3X_tEE
package main
import (
"fmt"
"math"
)
type Point struct {
x float64
y float64
}
func interpolate(f []Point, p float64) float64 {
// Since we will loop over all the points in the vector, capture n.
// Also, convert n to usize because we will be using th iterator
// associated types as indices.
n := len(f)
result := 0.0
// Each point in the vector of "known" points will be interpolated
// to calculate the point at f(0).
for i := 0; i < n; i++ {
term := f[i].y
// A good old nested for loop :)
for j := 0; j < n; j++ {
if i != j {
// X's should be unique
//assert!(f[i].x - f[j].x != 0.0);
denominator := f[i].x - f[j].x
numerator := -f[j].x
term = term * (numerator / denominator)
}
}
result += term
result = math.Mod(result, p)
}
return result
}
func main() {
f := make([]Point, 3)
f[0] = Point{x: 4.0, y: 1.0}
f[1] = Point{x: 3.0, y: 2.0}
f[2] = Point{x: 5.0, y: 2.0}
p := 11.0
result := interpolate(f, p)
fmt.Println("f(0) =", result)
}
// Output:
// f(0) = 6