Created
August 18, 2023 15:11
-
-
Save dimitrilw/619b7f1852c3dfa03c33953ee638c727 to your computer and use it in GitHub Desktop.
Go (golang) prime factors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func PrimeFactors(n int) (res []int) { | |
// keep dividing by 2 until we arrive at n is odd | |
for n%2 == 0 { | |
res = append(res, 2) | |
n = n / 2 | |
} | |
// n is now odd & cannot be even | |
for i := 3; i*i <= n; i = i + 2 { | |
for n%i == 0 { | |
res = append(res, i) | |
n = n / i | |
} | |
} | |
// add final n if it is not a 1 | |
if n > 2 { | |
res = append(res, n) | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment