Introduction
A prime number is a number greater than 1 that has no positive divisors other than 1 and itself.
In other words, a prime number cannot be divided exactly by any other numbers except for 1 and itself.
For example, 2, 3, 5, 7, 11, and 13 are prime numbers, while 4, 6, 8, 9, and 10 are not.
The objective of this program is to check if a given number is a prime number using the Go programming language.
The program will take an integer input from the user and determine if it is prime or not by applying the basic properties of prime numbers.
Code Implementation
package main
import (
"fmt"
"math"
)
// Function to check if a number is prime
func isPrime(n int) bool {
if n <= 1 {
return false
}
for i := 2; i <= int(math.Sqrt(float64(n))); i++ {
if n%i == 0 {
return false
}
}
return true
}
func main() {
var number int
// Ask the user for input
fmt.Print("Enter a number: ")
fmt.Scan(&number)
// Check if the number is prime
if isPrime(number) {
fmt.Println(number, "is a prime number.")
} else {
fmt.Println(number, "is not a prime number.")
}
}
Explanation of the Program
The program is divided into several sections:
- isPrime function: This function takes an integer
n
as input and returnstrue
if the number is prime andfalse
otherwise.
The function first checks ifn
is less than or equal to 1. If so, it immediately returnsfalse
. Then, it iterates from 2 to the square root ofn
and checks ifn
is divisible by any number in that range. If it finds a divisor, it returnsfalse
. If no divisors are found, the number is prime, and the function returnstrue
. - main function: In the main function, the program asks the user to input an integer, then calls the
isPrime
function to check if the number is prime.
Based on the result, it prints whether the number is prime or not.
How to Run the Program
Follow the steps below to run the program:
- Ensure you have Go installed on your system. You can download it from Go Downloads.
- Create a new file named
prime_checker.go
and paste the above code into the file. - Open a terminal and navigate to the directory where the file is saved.
- Run the program using the command:
go run prime_checker.go
- The program will prompt you to enter a number. Enter any integer to check if it is prime.
After running the program, it will display whether the entered number is prime or not based on the logic implemented in the code.