Solved problem 27

This commit is contained in:
Ben Shiller 2021-06-05 15:48:09 -05:00
parent 28d65ed7c0
commit 53a5b94525
No known key found for this signature in database
GPG Key ID: DC46F01400846797
3 changed files with 136 additions and 63 deletions

View File

@ -5,7 +5,6 @@ import (
"strconv"
)
func max(arr []int) int {
result := 0
for v := range arr {
@ -24,7 +23,7 @@ func get_next_digit(numerator, denominator int) int {
}
func calc_digit_repeat(i int, c chan int) {
digit_length := map[int]int {
digit_length := map[int]int{
0: 0, 1: 0, 2: 0, 3: 0, 4: 0,
5: 0, 6: 0, 7: 0, 8: 0, 9: 0,
}
@ -53,7 +52,7 @@ func calc_digit_repeat(i int, c chan int) {
}
}
func start_calc_digit_repeat(i int) (chan int) {
func start_calc_digit_repeat(i int) chan int {
c := make(chan int)
go calc_digit_repeat(i, c)

69
pe27/pe27.go Normal file
View File

@ -0,0 +1,69 @@
package pe27
import (
"fmt"
"math"
)
type Params struct {
A int
B int
N int
}
func is_prime(x int) bool {
if x < 0 {
x = -x
}
if x == 0 || x == 1 {
return false
}
if x == 2 {
return true
}
for i := 2; float64(i) <= math.Sqrt(float64(x)); i++ {
if x%i == 0 {
return false
}
}
return true
}
func count_primes(a, b int, c chan Params) {
num_primes := 0
for n := 0; ; n++ {
ans := n*n + a*n + b
if !is_prime(ans) {
break
} else {
num_primes++
}
}
c <- Params{a, b, num_primes}
}
func Solve(_ []string) {
c := make(chan Params, 3999999)
var a, b int
for a = -999; a < 1000; a++ {
for b = -1000; b < 1001; b++ {
go count_primes(a, b, c)
}
}
max_a, max_b, max := 0, 0, 0
for i := 0; i < 3999999; i++ {
arr := <-c
if arr.N > max {
max_a = arr.A
max_b = arr.B
max = arr.N
}
}
fmt.Println("A:", max_a, "B:", max_b, "Num Primes:", max, "A * B:", max_a*max_b)
/*
for i := 0; i < 100; i++ {
fmt.Println("i:", i, "is prime:", is_prime(i))
}
*/
}

View File

@ -4,21 +4,26 @@ import (
"fmt"
"os"
"shillerben.com/gitlab/shillerben/projecteuler/pe26"
"shillerben.com/gitlab/shillerben/projecteuler-go/pe26"
"shillerben.com/gitlab/shillerben/projecteuler-go/pe27"
)
var solve_funcs = map[string]func([]string){
"26": pe26.Solve,
"27": pe27.Solve,
}
func main() {
if len(os.Args) < 3 {
if len(os.Args) < 2 {
fmt.Println("usage: projecteuler <problem number> <problem args>")
return
}
problem_number := os.Args[1]
problem_args := os.Args[2:]
var problem_args []string
if len(os.Args) > 2 {
problem_args = os.Args[2:]
}
solve_funcs[problem_number](problem_args)
}