Write a Golang program to search an element in an array

Go ProgrammingServer Side ProgrammingProgramming

Definition: A number is that is greater than 2 and divisible only by itself and 1.

Examples: Prime numbers are 2, 3, 5, 7, 11, 13, 113, 119, ..., etc.

Approach to solve this problem

  • Step 1: Find square root of the given number, sq_root = √num
  • Step 2: If the given number is divisible by a number that belongs to [2, sq_root], then print “Non Prime Number”
  • Step 3: If not divisible by any number, then print “Prime Number”

Program

Live Demo

package main
import (
   "fmt"
   "math"
)
func checkPrimeNumber(num int) {
   if num < 2 {
      fmt.Println("Number must be greater than 2.")
      return
   }
   sq_root := int(math.Sqrt(float64(num)))
   for i:=2; i<=sq_root; i++{
      if num % i == 0 {
         fmt.Println("Non Prime Number")
         return
      }
   }
   fmt.Println("Prime Number")
   return
}

func main(){
   checkPrimeNumber(0)
   checkPrimeNumber(2)
   checkPrimeNumber(13)
   checkPrimeNumber(152)
}

Output

Number must be greater than 2.
Prime Number
Prime Number
Non Prime Number
raja
Published on 04-Feb-2021 15:21:40
Advertisements