Learn how to check if a number is prime and generate a list of prime numbers in Golang.
A prime number is a number greater than 1 that has no divisors other than 1 and itself.
We will write a function isPrime(n int) bool
that checks if a number is prime.
package main
import "math"
// isPrime checks if a number is prime
func isPrime(n int) bool {
if n < 2 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
return false
}
}
return true
}
This code checks whether a given number is prime using an optimized approach.
package main
Every Go program starts with a package declaration. The main
package indicates that this is an executable program.
math
Packageimport "math"
We import the math package to use the Sqrt()
function (square root).
isPrime(n int) bool
FunctionThis function takes an integer n
and returns true
if it is prime, otherwise false
.
if n < 2 { return false }
If n
is less than 2, it is not prime, so we return false
.
βn
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
We check divisibility only up to the square root of n
to improve efficiency.
if n % i == 0 { return false }
If n
is divisible by any number i
, then it is not prime.
true
if No Divisors Are Foundreturn true
If no divisors are found, it means n
is a prime number.
We now create a function generatePrimes(limit int) []int
that finds all prime numbers up to a given limit.
// generatePrimes generates a list of prime numbers up to a given limit
func generatePrimes(limit int) []int {
var primes []int
for i := 2; i <= limit; i++ {
if isPrime(i) {
primes = append(primes, i)
}
}
return primes
}
Here is the complete Go program to check if a number is prime and generate prime numbers:
package main
import (
"fmt"
"math"
)
// Check if a number is prime
func isPrime(n int) bool {
if n < 2 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
return false
}
}
return true
}
// Generate a list of prime numbers
func generatePrimes(limit int) []int {
var primes []int
for i := 2; i <= limit; i++ {
if isPrime(i) {
primes = append(primes, i)
}
}
return primes
}
func main() {
var num int
fmt.Print("Enter a number to check if it's prime: ")
fmt.Scan(&num)
if isPrime(num) {
fmt.Printf("%d is a prime number.\n", num)
} else {
fmt.Printf("%d is NOT a prime number.\n", num)
}
var limit int
fmt.Print("Enter a limit to generate prime numbers: ")
fmt.Scan(&limit)
primes := generatePrimes(limit)
fmt.Println("Prime numbers up to", limit, ":", primes)
}
Example of user interaction with the program:
Enter a number to check if it's prime: 11
11 is a prime number.
Enter a limit to generate prime numbers: 20
Prime numbers up to 20: [2 3 5 7 11 13 17 19]
math.Sqrt()
incorrectlyπ΄ Problem: Trying to pass an int
directly into math.Sqrt()
causes an error.
β
Solution: Convert int
to float64
before using math.Sqrt()
:
for i := 2; i <= int(math.Sqrt(float64(n))); i++ { ... }
primes
π΄ Problem: Using append(primes, i)
without declaring primes
causes an error.
β Solution: Always initialize it like this:
var primes []int
n
instead of βn
π΄ Problem: Using a full loop from 2 to n
instead of 2 to βn
makes the program much slower.
β
Solution: Optimize by looping up to math.Sqrt(n)
.
π΄ Problem: Negative numbers should never be considered prime, but the function might allow them.
β
Solution: Add a condition at the start of isPrime()
:
if n < 2 { return false }
π΄ Problem: Using var primes int
instead of []int
for a slice.
β Solution: Make sure you're using the correct types for lists:
var primes []int
π΄ Problem: If you store prime numbers globally, they may accumulate across runs.
β
Solution: Make sure the prime list is reset for each call of generatePrimes()
.
1 : Can this program handle very large numbers?
It works for reasonable values, but for very large numbers, consider using optimized prime algorithms like the Sieve of Eratosthenes.
2 : Why do we use math.Sqrt(n)
?
To optimize performance. A number is composite if it has a factor β€ βn.
3 : Why does 1 return false in this program?
By definition, 1 is not a prime number because it has only one divisor (itself). A prime number needs exactly two divisors: 1 and itself.
4 : How can I modify this program to check multiple numbers in one run?
You can wrap the fmt.Scan
input inside a loop to allow multiple checks without restarting the program.
5 : How do I print only the first N prime numbers instead of up to a limit?
Modify generatePrimes
to stop after finding N
primes instead of checking up to a number limit.
π Thank you for reading these articles! If you find this content valuable and want to support my work, a coffee would be greatly appreciated! βπ
π» I am a freelance web developer, and I personally create and maintain this website. Any support would help me improve and expand it further! π