Find the Factors of a Number in Go



In this tutorial, we will learn how to find the factors of a number in Go. We will cover the basic concept of factors and implement a function to perform the calculation.


What are Factors

Factors of a number are integers that can be multiplied together to produce the original number. For example, the factors of 12 are 1, 2, 3, 4, 6, and 12.


Syntax

The syntax to find the factors of a number in Go is:

func findFactors(n int) []int {
    var factors []int
    for i := 1; i <= n; i++ {
        if n % i == 0 {
            factors = append(factors, i)
        }
    }
    return factors
}


Example 1: Finding the factors of a number

We can create a function to find all factors of a given number by iterating through possible divisors and checking if they divide the number without a remainder.

For example,

  1. Define a function named findFactors that takes one parameter n of type int.
  2. Initialize an empty slice factors to store the factors.
  3. Use a for loop to iterate from 1 to n (inclusive).
  4. In each iteration, check if n is divisible by the current number i. If true, append i to the slice of factors.
  5. Return the slice of factors.
  6. In the main function, call the findFactors function with a sample number and print the result.

Go Program

package main

import (
    "fmt"
)

func findFactors(n int) []int {
    var factors []int
    for i := 1; i <= n; i++ {
        if n % i == 0 {
            factors = append(factors, i)
        }
    }
    return factors
}

func main() {
    // Find the factors of 12
    result := findFactors(12)

    // Print the result
    fmt.Printf("Factors of 12 are: %v\n", result)
}

Output

Factors of 12 are: [1 2 3 4 6 12]