GO Program to find factors of a number

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to find factors of a number

The simple method to find the factors of a given number is

  1. Find all the numbers less than or equal to the given number.
  2. Divide the given number by all the numbers
  3. The numbers as divisors that give a reminder of 0 are the factors of the given number

How to find factors of a number in the Go Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing how to find factors of a number in the Go language. Here variables num holding the number whose factors have to be found, and variable i as the indexing variable in the for-loop. The factors of the number are calculated as (num%i == 0) in a for-loop. Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable num, i 

STEP 4: Read the number num using fmt.Scanln()

STEP 5: Use for loop for find the factors as num%i == 0 

STEP 6: The loop iterated from i=0 to i<=num

STEP 7: Print the factors using fmt.Println()

 

GO Source Code

                                          package main
import "fmt"

func main() {

    var num, i int
    fmt.Print("Enter any number to find factors = ")
    fmt.Scanln(& num)
    fmt.Println("The factors of the ", num, " are = ")
    for i = 1; i <= num; i++ {
        if num%i == 0 {
            fmt.Println(i)
        }
    }
}
                                      

OUTPUT

Enter any number to find factors = 76
The factors of the  76  are = 
1
2
4
19
38
76