Introduction
Prime factorization is a mathematical process where a number is expressed as a product of its prime factors.
This program demonstrates how to find the prime factors of a given number using Go, showcasing loops, conditionals, and number theory in action.
Objective
The objective of this project is to create a program that calculates and displays the prime factors of a user-provided number.
This helps learners understand number theory and how to implement mathematical concepts in Go programming.
Code
package main
import (
"fmt"
)
// Function to find and return the prime factors of a number
func primeFactors(n int) []int {
factors := []int{}
// Divide n by 2 until it is odd
for n%2 == 0 {
factors = append(factors, 2)
n /= 2
}
// Check for odd factors from 3 onwards
for i := 3; i*i <= n; i += 2 { for n%i == 0 { factors = append(factors, i) n /= i } } // If n is still greater than 2, it must be prime if n > 2 {
factors = append(factors, n)
}
return factors
}
func main() {
var num int
fmt.Println("Welcome to the Prime Factorization Program!")
fmt.Print("Enter a number to find its prime factors: ")
fmt.Scanln(&num)
if num <= 1 {
fmt.Println("Please enter a number greater than 1.")
return
}
factors := primeFactors(num)
fmt.Printf("The prime factors of %d are: %v\n", num, factors)
}
Explanation
The program structure is as follows:
- Prime Factorization Function: The
primeFactors
function calculates the prime factors by:- Dividing the number by 2 repeatedly to account for all factors of 2.
- Iterating through odd numbers from 3 onwards to find other factors.
- Appending the remaining number if it is greater than 2, as it is prime.
- Main Function: The main function takes user input for the number, validates it, and calls the prime factorization function.
The result is displayed to the user.
How to Run the Program
- Ensure you have Go installed on your system. You can download it from
Go’s official website. - Save the code in a file named
prime_factorization.go
. - Open a terminal and navigate to the directory containing the file.
- Run the program with the following command:
go run prime_factorization.go
- Enter a number greater than 1 when prompted to find its prime factors.
Copyright © Learn Programming. All rights reserved.