-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy path10140.go
More file actions
79 lines (70 loc) · 1.28 KB
/
10140.go
File metadata and controls
79 lines (70 loc) · 1.28 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
72
73
74
75
76
77
78
79
// UVa 10140 - Prime Distance
package main
import (
"fmt"
"math"
"os"
)
const max = 46340 // √(2^31-1)
var primes = sieve()
func sieve() []bool {
p := make([]bool, max+1)
p[0], p[1] = true, true
for i := 2; i*i <= max; i++ {
if !p[i] {
for j := 2 * i; j <= max; j += i {
p[j] = true
}
}
}
return p
}
func isPrime(n int) bool {
if n <= max {
return !primes[n]
}
for i := range primes {
if i*i > n {
break
}
if !primes[i] && n%i == 0 {
return false
}
}
return true
}
func solve(l, u int) (c1, c2, d1, d2 int) {
pre, min, max := -1, math.MaxInt32, math.MinInt32
for i := l; i <= u; i++ {
if isPrime(i) {
if pre != -1 {
distance := i - pre
if distance < min {
min, c1, c2 = distance, pre, i
}
if distance > max {
max, d1, d2 = distance, pre, i
}
}
pre = i
}
}
return
}
func main() {
in, _ := os.Open("10140.in")
defer in.Close()
out, _ := os.Create("10140.out")
defer out.Close()
var l, u int
for {
if _, err := fmt.Fscanf(in, "%d%d", &l, &u); err != nil {
break
}
if c1, c2, d1, d2 := solve(l, u); c1 == 0 && c2 == 0 && d1 == 0 && d2 == 0 {
fmt.Fprintln(out, "There are no adjacent primes.")
} else {
fmt.Fprintf(out, "%d,%d are closest, %d,%d are most distant.\n", c1, c2, d1, d2)
}
}
}