Documentation
¶
Overview ¶
A bunch of helper functions for dealing with small prime numbers that would fit in an unsigned integer.
This isn't a serious scientifically minded package, or heavily optimized, it's just a quick and dirty tool for grabbing prime numbers should you find yourself needing them.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func All ¶
All returns an iterator yielding all the prime numbers up to math.MaxUint in ascending order.
Example ¶
// Find first 5 pairs of twin primes
var prev uint
count := 0
for p := range All() {
if prev != 0 && p-prev == 2 {
fmt.Printf("(%d, %d) ", prev, p)
count++
if count == 5 {
break
}
}
prev = p
}
Output: (3, 5) (5, 7) (11, 13) (17, 19) (29, 31)
func Factorize ¶
Factorize returns an iterator that yields the prime factors of n and their exponents.
Example ¶
for prime, exponent := range Factorize(360) {
fmt.Printf("%d^%d ", prime, exponent)
}
Output: 2^3 3^2 5^1
func FirstN ¶
FirstN returns a slice containing the first n prime numbers in ascending order.
The returned slice should be considered read-only and must not be modified.
The returned slice might contain less than n elements if those numbers wouldn't fit in a uint.
Example ¶
fmt.Println(FirstN(10))
Output: [2 3 5 7 11 13 17 19 23 29]
func GCD ¶
GCD computes the greatest common divisor. This really doesn't have much to do with prime numbers other than the algorithm heavily relying on them.
Returns 0 if the list is empty or all of the numbers are 0.
Example ¶
fmt.Println(GCD(6, 0, 12, 9))
Output: 3
func LCM ¶
LCM computes the least common multiple. This really doesn't have much to do with prime numbers other than the algorithm heavily relying on them.
Returns 0 if the LCM would overflow, or one of the numbers is 0.
Example ¶
fmt.Println(LCM(6, 8, 12))
Output: 24
func Next ¶
Next returns the prime number at some relative offset to n, or 0 if there is no applicable number.
Next(n, 0) will return n if n is prime, otherwise 0. Next(n, -1) will return the next prime number before n, if one exists (i.e., n >= 3) Next(n, 1) will return the next prime number after n, if representable in a uint. Next(n, 100) will return the 100th prime number after n, if representable in a uint.
Example ¶
resetCache()
_ = upTo(100)
offsets := []int{-3, -2, -1, 0, 1, 2, 1000}
names := []string{"3rd prime before", "2nd prime before", "1st prime before", "prime at", "1st prime after", "2nd prime after", "thousandth prime after"}
for i, offset := range offsets {
const n = 4
if prime := Next(n, offset); prime != 0 {
fmt.Printf("%s %d is: %d\n", names[i], n, Next(n, offset))
} else {
fmt.Printf("no %s %d\n", names[i], n)
}
}
Output: no 3rd prime before 4 2nd prime before 4 is: 2 1st prime before 4 is: 3 no prime at 4 1st prime after 4 is: 5 2nd prime after 4 is: 7 thousandth prime after 4 is: 7933
Types ¶
This section is empty.
Source Files
¶
- prime.go