mirror of
https://github.com/cubixle/codekata-golang.git
synced 2026-04-30 20:28:45 +01:00
summation of primes
TODO: better algorithm
This commit is contained in:
@@ -0,0 +1,40 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "fmt"
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
sum := 0
|
||||||
|
from := 2
|
||||||
|
count := 0
|
||||||
|
for {
|
||||||
|
if from == 2000000 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
if IsPrime(from) {
|
||||||
|
fmt.Println("prime:", from)
|
||||||
|
sum += from
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
from++
|
||||||
|
}
|
||||||
|
fmt.Println("sum:", sum, count)
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsPrime(n int) bool {
|
||||||
|
if n < 2 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if n == 2 {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
squareRoot := 1
|
||||||
|
for squareRoot*squareRoot < n {
|
||||||
|
squareRoot++
|
||||||
|
}
|
||||||
|
for i := 2; i <= squareRoot; i++ {
|
||||||
|
if n%i == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestIsPrime(t *testing.T) {
|
||||||
|
tt := []struct {
|
||||||
|
name string
|
||||||
|
input int
|
||||||
|
want bool
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
"1",
|
||||||
|
1,
|
||||||
|
false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"2",
|
||||||
|
2,
|
||||||
|
true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"10",
|
||||||
|
10,
|
||||||
|
false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"17",
|
||||||
|
17,
|
||||||
|
true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"97",
|
||||||
|
97,
|
||||||
|
true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tc := range tt {
|
||||||
|
t.Run(tc.name, func(t *testing.T) {
|
||||||
|
got := IsPrime(tc.input)
|
||||||
|
if got != tc.want {
|
||||||
|
t.Errorf("IsPrime(%d)=%v, want %v", tc.input, got, tc.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user