Prime Number Checker in Go

Learn how to check if a number is prime and generate a list of prime numbers in Golang.

Understanding Prime Numbers

A prime number is a number greater than 1 that has no divisors other than 1 and itself.

Step 1: Writing the Prime Checker Function

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
    }

πŸ“Œ Explanation of the Go Code: Prime Number Checker

This code checks whether a given number is prime using an optimized approach.

1️⃣ Declaring the Package

package main

Every Go program starts with a package declaration. The main package indicates that this is an executable program.

2️⃣ Importing the math Package

import "math"

We import the math package to use the Sqrt() function (square root).

3️⃣ Defining the isPrime(n int) bool Function

This function takes an integer n and returns true if it is prime, otherwise false.

4️⃣ Checking Special Cases

if n < 2 { return false }

If n is less than 2, it is not prime, so we return false.

5️⃣ Checking Divisors up to √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.

6️⃣ Checking for Divisibility

if n % i == 0 { return false }

If n is divisible by any number i, then it is not prime.

7️⃣ Returning true if No Divisors Are Found

return true

If no divisors are found, it means n is a prime number.

Step 2: Generate a List of Prime Numbers

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
    }

Step 3: Running the Prime Checker

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)
    }

Expected Output

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]

Common Mistakes and How to Fix Them

FAQs

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! πŸ™Œ


β˜• Buy me a coffee