-
Notifications
You must be signed in to change notification settings - Fork 27
/
516.go
83 lines (74 loc) · 1.2 KB
/
516.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// UVa 516 - Prime Land
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
const max = 32767
func sieve() []bool {
p := make([]bool, max+1)
for i := 2; i*i <= max; i++ {
if !p[i] {
for j := 2 * i; j <= max; j += i {
p[j] = true
}
}
}
return p
}
func pow(b, e int) int {
num := 1
for ; e > 0; e-- {
num *= b
}
return num
}
func factorize(primes []bool, n int) [][2]int {
var factors [][2]int
f := n
for n > 1 {
if !primes[f] && n%f == 0 {
e := 0
for n > 1 && n%f == 0 {
n /= f
e++
}
factors = append(factors, [2]int{f, e})
f = n
} else {
f--
}
}
return factors
}
func main() {
in, _ := os.Open("516.in")
defer in.Close()
out, _ := os.Create("516.out")
defer out.Close()
s := bufio.NewScanner(in)
s.Split(bufio.ScanLines)
primes := sieve()
var b, e int
for s.Scan() {
if line := s.Text(); line != "0" {
num := 1
for r := strings.NewReader(line); ; {
if _, err := fmt.Fscanf(r, "%d%d", &b, &e); err != nil {
break
}
num *= pow(b, e)
}
factors := factorize(primes, num-1)
for i, v := range factors {
if i != 0 {
fmt.Fprint(out, " ")
}
fmt.Fprint(out, v[0], v[1])
}
fmt.Fprintln(out)
}
}
}