GO Program to check prime number

How to check prime number

Here we are explaining how to check prime numbers in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

 

How to check prime numbers in the GO Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to check the prime numbers in the Go language. Here variables num holding the number for the prime check, and other variables are count, i. Check the num%i=0 in an for loop also increment the count variable. The loop iterate from 2 to num/2.Check the count=0 and num not equal to 1 then, it is a prime, otherwise not a prime number. Given below are the steps which are used in the Go program. 

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

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 = ")
    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