Golang Program to check prime number


March 4, 2022, Learn eTutorial
2154

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.

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, If the condition is true then it is a prime number otherwise not a prime.

ALGORITHM

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

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

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


This prime number program uses the below concepts of GO programming, please refer to these topics for a better understanding

Golang Source Code

                                          package main
import "fmt"

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

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

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

OUTPUT

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