Go Program to Check Prime Number

Any number can be a Prime number if it is not divisible by different numbers besides one and itself. Remember, 2 is the only even prime number. This Go program uses for loop (for i := 2; i < primNum/2; i++) that starts at two and ends at number/2, and If statement (if primNum%i == 0) examines the number divisible by the iterator value. If True, increment the count value, and the break statement will exit the GC from for loop. After the for loop, we used the If else statement (if primcount == 0 && primNum != 1) to check the count value equals zero and the number does not equal 1. If True, it is a prime number; otherwise, not a prime.

package main

import "fmt"

func main() {

    var primNum, primcount int
    primcount = 0

    fmt.Print("Enter the Number to find the Prime Numbers = ")
    fmt.Scanln(&primNum)

    for i := 2; i < primNum/2; i++ {
        if primNum%i == 0 {
            primcount++
            break
        }
    }

    if primcount == 0 && primNum != 1 {
        fmt.Println(primNum, " is a Prime Number")
    } else {
        fmt.Println(primNum, " is Not a Prime Number")
    }
}
SureshMac:GoExamples suresh$ go run prime1.go
Enter the Number to find the Prime Numbers = 2
2  is a Prime Number
SureshMac:GoExamples suresh$ go run prime1.go
Enter the Number to find the Prime Numbers = 35
35  is Not a Prime Number

Go Program to Find the Number is Prime using Functions

package main

import "fmt"

var primcount int = 0

func primeFunc(primNum int) int {
    for i := 2; i < primNum/2; i++ {
        if primNum%i == 0 {
            primcount++
        }
    }
    return primcount
}

func main() {

    var primNum int

    fmt.Print("Enter the Number to find the Prime Numbers = ")
    fmt.Scanln(&primNum)

    primcount = primeFunc(primNum)

    if primcount == 0 && primNum != 1 {
        fmt.Println(primNum, " is a Prime Number")
    } else {
        fmt.Println(primNum, " is Not a Prime Number")
    }
}
SureshMac:GoExamples suresh$ go run prime2.go
Enter the Number to find the Prime Numbers = 31
31  is a Prime Number
SureshMac:GoExamples suresh$ go run prime2.go
Enter the Number to find the Prime Numbers = 89
89  is Not a Prime Number

This Golang program prints the Prime numbers between the minimum and maximum limit or from 1 to N.

package main

import "fmt"

func main() {

    var primNum, primMin, primMax, primcount int

    fmt.Print("Enter the Minimum and Maximum Limit for Prime Numbers = ")
    fmt.Scanln(&primMin, &primMax)

    fmt.Println("Prime Numbers between ", primMin, " and ", primMax, " are ")
    for primNum = primMin; primNum <= primMax; primNum++ {
        primcount = 0
        for i := 2; i < primNum/2; i++ {
            if primNum%i == 0 {
                primcount++
                break
            }
        }
        if primcount == 0 && primNum != 1 {
            fmt.Print(primNum, "\t")
        }
    }
    fmt.Println()
}
Golang Program to Find Prime Number 3