GO Program to check prime number

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

What is a prime number?

A prime number is a whole number that is only divisible by 1 and itself
Example: 2, 3, 5, 7 etc.

How to check prime number

The simplest way to check whether the given number is a prime number is find the factors of the given number. If the number displays more than two factors, then it is not a prime number. If the given number has only two factors that is 1 and the number itself then the number is a prime number. 

How to check prime numbers in the GO Program

2 is the only even prime number. Here we are using for loop that starts at 2 and ends at the number/2.
Syntax for for loop

for    initializer; condition;   incrementor {

Within the for loop we used the if statement to examine the number divisible by the iterator value. If the condition is true then increment the count value and exit the loop. After the for loop, we used the if else statement to check the count value is equal to 0 and the number not equal to 1.

syntax for if...else

if condition {
//do some instructions
}else {
//do some instructions

If the condition is true then it is a prime number otherwise not a prime.


STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable num, count

STEP 4: Read the number num using fmt.Scanfln()

STEP 5:Initialise integer count=0

STEP 6: Use for loop as (for i := 2; i < num/2; i++)

STEP 7: Check num%i == 0 and count++ in the loop

STEP8: Use If else statement (if count == 0 && num != 1) 

STEP9: If true, it is a Prime, otherwise not a Prime number.


GO Source Code

                                          package main
import "fmt"

func main() {
    var num, count int
    count = 0
    fmt.Print("Enter the number to find the prime number = ")

    for i := 2; i < num/2; i++ {
        if num%i == 0 {

    if count == 0 && num != 1 {
        fmt.Println(num, " is a Prime number")
    } else {
        fmt.Println(num, " is not a Prime number")


Enter the number to find the prime number = 3
3  is a Prime number

Enter the number to find the prime number = 25
25  is not a Prime number