Created
February 17, 2021 18:22
-
-
Save ythosa/bb8e972bf1541fb3be341bab9c697f66 to your computer and use it in GitHub Desktop.
The Number Of Sophie Germain
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type eratosthenesSieve struct { | |
sieve []bool | |
maxN int | |
} | |
func newEratosthenesSieve(maxN int) *eratosthenesSieve { | |
var sieve eratosthenesSieve | |
sieve.sieve = append(sieve.sieve, false) | |
sieve.sieve = append(sieve.sieve, false) | |
for i := 2; i < maxN; i++ { | |
sieve.sieve = append(sieve.sieve, true) | |
} | |
sieve.maxN = maxN | |
return &sieve | |
} | |
func (s *eratosthenesSieve) fill() { | |
for i := 2; i*i < s.maxN; i++ { | |
if s.sieve[i] { | |
for j := i * i; j < s.maxN; j += i { | |
s.sieve[j] = false | |
} | |
} | |
} | |
} | |
func (s *eratosthenesSieve) String() string { | |
result := "" | |
for i, isPrime := range s.sieve { | |
if isPrime { | |
result += fmt.Sprintf("%d ", i) | |
} | |
} | |
return result | |
} | |
type sophieGermainNumbers struct { | |
primeNumbers []bool | |
filtered []int | |
} | |
func newSofiZhemenNumbers(primeNumbers []bool) *sophieGermainNumbers { | |
var model sophieGermainNumbers | |
model.primeNumbers = primeNumbers | |
return &model | |
} | |
func (s *sophieGermainNumbers) filterPrimeNumbers() { | |
for i := 2; i < len(s.primeNumbers); i++ { | |
nextPos := 2*i + 1 | |
if nextPos >= len(s.primeNumbers) { | |
return | |
} | |
if s.primeNumbers[i] && s.primeNumbers[nextPos] { | |
s.filtered = append(s.filtered, i) | |
} | |
} | |
} | |
func (s *sophieGermainNumbers) String() string { | |
result := "" | |
for _, n := range s.filtered { | |
result += fmt.Sprintf("%d ", n) | |
} | |
return result | |
} | |
func main() { | |
const maxNumber = 10000 | |
erSieve := newEratosthenesSieve(maxNumber) | |
erSieve.fill() | |
sofiZhemenNums := newSofiZhemenNumbers(erSieve.sieve) | |
sofiZhemenNums.filterPrimeNumbers() | |
fmt.Println(sofiZhemenNums) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment