Skip to content

Commit 34c3214

Browse files
Create primalityTest.go (#179)
* Create the prime_check.go * Added test file
1 parent d9069e9 commit 34c3214

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

math/prime_check/prime_check.go

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//A primality test is an algorithm for determining whether an input number is prime.Among other fields of mathematics, it is used for cryptography.
2+
//Unlike integer factorization, primality tests do not generally give prime factors, only stating whether the input number is prime or not.
3+
//Source - Wikipedia https://en.wikipedia.org/wiki/Primality_test
4+
package main
5+
6+
func NaiveApproach(n int) bool {
7+
if n < 2 {
8+
return false
9+
}
10+
for i := 2; i < n; i++ {
11+
12+
if n%i == 0 {
13+
return false
14+
}
15+
}
16+
return true
17+
}
18+
19+
func PairApproach(n int) bool {
20+
if n < 2 {
21+
return false
22+
}
23+
for i := 2; i*i <= n; i++ {
24+
if n%i == 0 {
25+
return false
26+
}
27+
}
28+
return true
29+
}
30+
31+
//goos: windows
32+
//goarch: amd64
33+
//BenchmarkNaiveApproach-12 660980034 1.81 ns/op
34+
//BenchmarkPairApproach-12 664641356 1.82 ns/op

math/prime_check/prime_check_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package main
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestTableNaiveApproach(t *testing.T) {
8+
var tests = []struct {
9+
input int
10+
expected bool
11+
}{
12+
{2, true},
13+
{3, true},
14+
{1, false},
15+
{10, false},
16+
{23, true},
17+
}
18+
19+
for _, test := range tests {
20+
if output := NaiveApproach(test.input); output != test.expected {
21+
t.Error("Test Failed: {} inputted, {} expected, recieved: {}", test.input, test.expected, output)
22+
}
23+
}
24+
25+
}
26+
func TestTablePairApproach(t *testing.T) {
27+
var tests = []struct {
28+
input int
29+
expected bool
30+
}{
31+
{2, true},
32+
{3, true},
33+
{1, false},
34+
{10, false},
35+
{23, true},
36+
}
37+
38+
for _, test := range tests {
39+
if output := PairApproach(test.input); output != test.expected {
40+
t.Error("Test Failed: {} inputted, {} expected, recieved: {}", test.input, test.expected, output)
41+
}
42+
}
43+
44+
}

0 commit comments

Comments
 (0)