-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem35.go
More file actions
73 lines (67 loc) · 2.04 KB
/
Copy pathproblem35.go
File metadata and controls
73 lines (67 loc) · 2.04 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
package projecteuler
import "math"
// given a slice of decimal digits (0-9)
// returns an integer formed by those digits
func numFromDigits(arr []int, base int) int {
sum := 0
for i := 0; i < len(arr); i++ {
sum = sum*base + arr[i]
}
return sum
}
// given a number, rotates that number by one digit place
// if 197 is given, after single digit rotation it'll be 971
// after that it'll be 719
func rotateNumber(num *[]int) {
if len(*num) == 1 {
return
}
tmp := make([]int, len(*num))
copy(tmp, *num)
for i := 1; i <= len(*num); i++ {
(*num)[i-1] = tmp[i%len(*num)]
}
}
// checks whether a given number is circular prime or not
func isCircularPrime(num int) (bool, []int) {
if !isPrime(num) { // first we check, whether given number is prime or not
return false, nil // if not, no need to check for its circular forms
}
splitted := splitDigits(num)
circulated := make([]int, int(math.Floor(math.Log10(float64(num))))+1)
circulated[0] = num
check := true
for i := 1; i < len(circulated); i++ {
rotateNumber(&splitted) // rotating number, for creating next value
circulated[i] = numFromDigits(splitted, 10) // putting rotated number into buffer
if !isPrime(circulated[i]) { // checking whether this form is prime or not, if not
check = false // we simply quit looping, to reduce CPU cycle usage
break
}
}
if !check {
return check, nil
}
return check, circulated // if circular prime, all circulated numbers generated to be returned
}
// copies content of slice into a given hash map,
// if that value is not present in hash map
func putIntoBuffer(items []int, buffer *map[int]int) {
for _, v := range items {
if _, ok := (*buffer)[v]; !ok {
(*buffer)[v] = 1
}
}
}
// CircularPrimes - Calculates number of circular primes under 10^6
func CircularPrimes() int {
primeBuffer := make(map[int]int)
for i := 2; i < 1000000; i++ {
if _, ok := primeBuffer[i]; !ok {
if check, extras := isCircularPrime(i); check {
putIntoBuffer(extras, &primeBuffer)
}
}
}
return len(primeBuffer)
}