-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem41.go
More file actions
65 lines (60 loc) · 1.22 KB
/
Copy pathproblem41.go
File metadata and controls
65 lines (60 loc) · 1.22 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
package projecteuler
import "sync"
// calculates first decimal number
// that requires `n` digits for representation
//
// i.e. first 2-digit number 10
func firstNDigitNumber(n int) int {
num := 1
for n > 1 {
num *= 10
n--
}
return num
}
// max decimal number that requires `n` digits
// for presentation
//
// i.e. 99 is max number that requires 2 digits
func lastNDigitNumber(n int) int {
return firstNDigitNumber(n+1) - 1
}
// finds maximum number that require `n` digits
// which is also pandigital ( from 1 to n) and prime
func largestNDigitPandigitalPrime(n int, channel chan int) {
prime := 0
end := firstNDigitNumber(n)
for i := lastNDigitNumber(n); i >= end; i -= 2 {
if isPandigital(splitDigits(i), 1, n) && isPrime(i) {
prime = i
break
}
}
channel <- prime
}
// PandigitalPrime - Computes maximum number that is pandigital and prime
func PandigitalPrime() int {
channel := make(chan int, 1)
maxPrime := 0
var wg sync.WaitGroup
wg.Add(1)
go func() {
c := 0
for i := range channel {
if i > maxPrime {
maxPrime = i
}
c++
if c == 8 {
break
}
}
close(channel)
wg.Done()
}()
for i := 9; i > 1; i-- {
go largestNDigitPandigitalPrime(i, channel)
}
wg.Wait()
return maxPrime
}