Golang Program to Generate all the Divisors of an Integer


Steps

  • Take the value of the integer and store it in a variable.
  • Use a for loop and an if statement to generate the divisors of the integer.
  • Print the divisors of the number.
Enter an integer:25
The divisors of the number are:
1
5
25
The divisors of the number are: 20
1
2
4
5
10
20

Explanation

  • User must first enter the value and store it in a variable.
  • Use a for loop to generate numbers from 1 to n.
  • Using an if statement, check if the number divided by i gives the remainder as 0 which is basically the divisor of the integer.
  • Print the divisors of the number.

Example

 Live Demo

package main
import "fmt"
func main(){
   var n int
   fmt.Print("Enter an integer:")
   fmt.Scanf("%d", &n)
   fmt.Println("The divisors of the number are:")
   for i:=1; i<=n; i++{
      if n%i==0 {
         fmt.Printf("%d\n", i)
      }
   }
}

Output

Enter an integer:20
The divisors of the number are:
1
2
4
5
10
20

Updated on: 31-Jul-2021

301 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements