From 39a6ae56df8f416c5ae4e149bfde70648050915f Mon Sep 17 00:00:00 2001 From: VicRen Date: Tue, 24 Nov 2020 10:45:43 +0800 Subject: [PATCH] 50: consecutive prime sum --- 50_consecutive_prime_sum/main.go | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 50_consecutive_prime_sum/main.go diff --git a/50_consecutive_prime_sum/main.go b/50_consecutive_prime_sum/main.go new file mode 100644 index 0000000..de5441a --- /dev/null +++ b/50_consecutive_prime_sum/main.go @@ -0,0 +1,41 @@ +package main + +import "fmt" + +func main() { + solution() +} + +func solution() { + limit := 1000000 + notPrime := make([]int, limit) + var primes []int + notPrime[0] = 1 + notPrime[1] = 1 + + for i := 2; i < limit; i++ { + if notPrime[i] == 0 { + primes = append(primes, i) + for j := i * i; j < limit; j += i { + notPrime[j] = 1 + } + } + } + + maxSum := 0 + maxRun := -1 + for i := 0; i < len(primes); i++ { + sum := 0 + for j := i; j < len(primes); j++ { + sum += primes[j] + if sum >= limit { + break + } + if notPrime[sum] == 0 && sum > maxSum && j-i > maxRun { + maxRun = j - i + maxSum = sum + } + } + } + fmt.Println("max sum:", maxSum) +}