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

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete