-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
63 lines (57 loc) · 1.46 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Print("** GoPrime **\nPlease type an integer: ")
var number int
fmt.Scanln(&number)
fmt.Printf("Performing prime factorization on number %v...\n\n", number)
factors := performPrimeFactorization(number)
factorsString := prettyFactors(number, factors)
fmt.Println()
fmt.Println(factorsString)
}
// prettyFactors returns a string with the format "number = factor1 * factor2 ..."
func prettyFactors(number int, factors []int) string {
factorsString := strconv.Itoa(number) + " = "
for i, v := range factors {
factorsString += strconv.Itoa(v)
if i != len(factors)-1 {
factorsString += " * "
}
}
return factorsString
}
// performPrimeFactorization factors an integer using trial division
func performPrimeFactorization(number int) []int {
currentNumber := number
factors := []int{}
fmt.Print(currentNumber)
for i := 2; i <= number; i++ {
if !isPrimeNumber(i) {
continue
}
for isNumberDivisible(currentNumber, i) {
fmt.Println("\t|", i)
factors = append(factors, i)
currentNumber /= i
fmt.Print(currentNumber)
}
}
fmt.Println() // Empty line on purpose
return factors
}
func isNumberDivisible(number1, number2 int) bool {
return number1%number2 == 0
}
func isPrimeNumber(number int) bool {
// Prime numbers only have two divisors in the Natural range: 1 and the number itself
for i := 2; i < number; i++ {
if isNumberDivisible(number, i) {
return false
}
}
return true
}