Golang Program to Find the Smallest Divisor of an Integer


Consider that the integer is: 75

Divisor of that integer is: 3, 5, 15, ..., 75

The smallest divisor is: 3

Steps

  • Take an integer from the user.
  • Initialize a variable (res) with that number.
  • Use a for loop where the value of i ranges from 2 to the integer.
  • If the number is divisible by i, compare with res. If res > i, then update res with i.
  • Exit from the loop and print res.

Example

 Live Demo

package main
import "fmt"
func main(){
   var n int
   fmt.Print("Enter the number: ")
   fmt.Scanf("%d", &n)
   res := n
   for i:=2; i<=n; i++{
      if n%i == 0{
         if i<=res{
            res=i
         }
      }
   }
   fmt.Printf("The smallest divisor of the number is: %d", res)
}

Output

Enter the number: 75
The smallest divisor of the number is: 3

Updated on: 31-Jul-2021

282 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements