Go Language - Program to Check Whether a Number is Prime or Not
- Prime numbers are natural numbers that are only divisible by 1 and the number itself.
- A prime number cannot be divided by any other numbers without leaving a remainder.
- An example of a prime number is 17. It can only be divided by 1 and 17, which has only two factors 1 and 5.
- Let's take another example of the number 6, which has more than two factors, i.e 1, 2, 3, and 6. This means 6 is not a prime number.
Example 1. Go Program to check whether the given number is Prime or not
package main
import ( "fmt")
func main() { CheckPrimeNumber(11) CheckPrimeNumber(1) CheckPrimeNumber(23) CheckPrimeNumber(20) CheckPrimeNumber(-9)}
func CheckPrimeNumber(number int) {
isPrime := true
if number < 0 { fmt.Println("Number must be greater than 0") } else if number == 0 || number == 1 { fmt.Println(number, "is not a prime number") } else { for i := 2; i <= number/2; i++ { if number%i == 0 { fmt.Println(number, " is not a prime number") isPrime = false break } } if isPrime == true { fmt.Println(number, "is a prime number") } }}
Output:
Example 2. Go Program to check whether the number from standard input is Prime or not
package main
import ( "fmt")
func main() { var number int fmt.Println("Enter an integer value : ")
_, err := fmt.Scanf("%d", &number)
if err != nil { fmt.Println(err) }
CheckPrimeNumber(number)}
func CheckPrimeNumber(number int) {
isPrime := true
if number < 0 { fmt.Println("Number must be greater than 0") } else if number == 0 || number == 1 { fmt.Println(number, "is not a prime number") } else { for i := 2; i <= number/2; i++ { if number%i == 0 { fmt.Println(number, " is not a prime number") isPrime = false break } } if isPrime == true { fmt.Println(number, "is a prime number") } }}