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.
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.
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
}
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,
findFactors
that takes one parameter n
of type int
.factors
to store the factors.for
loop to iterate from 1 to n
(inclusive).n
is divisible by the current number i
. If true, append i
to the slice of factors.findFactors
function with a sample number and print the result.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)
}
Factors of 12 are: [1 2 3 4 6 12]