checking for prime numbers using golang
package main
import (
"fmt"
)
func isPrime(num int) bool {
if num <= 1 {
return false
}
for i := 2; i*i <= num; i++ {
if num%i == 0 {
return false
}
}
return true
}
func main() {
fmt.Println("Prime numbers between 1 and 20:")
for i := 1; i <= 20; i++ {
if isPrime(i) {
fmt.Println(i)
}
}
}
Explanation:
package main
: Declares that this file is part of the main package in Go.import "fmt"
: Imports the "fmt" package, which provides functions for formatting input and output.func isPrime(num int) bool
: Defines a function namedisPrime
that takes an integernum
as input and returns a boolean value (true
if the number is prime,false
otherwise).if num <= 1 { return false }
: Checks if the input number is less than or equal to 1. If so, returnsfalse
as prime numbers are greater than 1.for i := 2; i*i <= num; i++
: Iterates from 2 to the square root of the input number (num
) using the variablei
. This loop checks divisibility only up to the square root ofnum
to optimize the algorithm.if num%i == 0 { return false }
: Checks if the input number (num
) is divisible by the current value ofi
. If it is divisible, returnsfalse
as it indicates that the number is not prime.return true
: If no divisors are found in the loop, the number is prime, so the function returnstrue
.func main()
: Defines the main function where the execution of the program starts.fmt.Println("Prime numbers between 1 and 20:")
: Prints a message indicating the prime numbers will be displayed between 1 and 20.for i := 1; i <= 20; i++ { if isPrime(i) { fmt.Println(i) } }
: Iterates through numbers from 1 to 20. For each number, it checks if it is prime using theisPrime
function and prints the number if it's prime.