Generate a list of prime numbers up to a given limit using the Go programming language.
Introduction
Prime numbers are numbers greater than 1 that have no divisors other than 1 and themselves. In this article, we will learn how to write a simple program in Go that generates prime numbers up to a given limit. This program will help you understand basic loops, conditionals, and how to work with numbers in Go.
Objective
The goal of this program is to provide a list of prime numbers up to a specified limit. The user will input the limit, and the program will display all prime numbers between 1 and the given limit.
Prime Number Generator Code in Go
package main import "fmt" // Function to check if a number is prime func isPrime(n int) bool { if n <= 1 { return false } for i := 2; i*i <= n; i++ { if n%i == 0 { return false } } return true } // Function to generate primes up to a given limit func generatePrimes(limit int) []int { primes := []int{} for i := 2; i <= limit; i++ { if isPrime(i) { primes = append(primes, i) } } return primes } func main() { var limit int fmt.Print("Enter the limit: ") fmt.Scan(&limit) primes := generatePrimes(limit) fmt.Println("Prime numbers up to", limit, "are:", primes) }
Explanation of the Program Structure
The program is divided into several parts:
- isPrime function: This function checks if a given number is prime. It does this by checking if the number is divisible by any number from 2 up to the square root of the number. If it is divisible, it’s not a prime.
- generatePrimes function: This function takes the limit as input and generates a list of prime numbers by calling the
isPrime
function for each number from 2 up to the limit. - main function: In the main function, the user is prompted to enter the limit, and the program generates the prime numbers up to that limit using the
generatePrimes
function. Finally, the program prints the list of prime numbers.
How to Run the Program
Follow these steps to run the program:
- Install Go programming language from the official website (https://golang.org/dl/).
- Create a new file with a
.go
extension (e.g.,prime_number_generator.go
). - Copy and paste the code provided above into the file.
- Open your terminal or command prompt and navigate to the directory where the file is saved.
- Run the command:
go run prime_number_generator.go
- Enter the limit when prompted, and the program will display all prime numbers up to that limit.