Skip to content

Instantly share code, notes, and snippets.

@theodesp
Last active September 17, 2019 14:31
Show Gist options
  • Save theodesp/305d2bea8f2a55bc6149a47bd5f2bcd8 to your computer and use it in GitHub Desktop.
Save theodesp/305d2bea8f2a55bc6149a47bd5f2bcd8 to your computer and use it in GitHub Desktop.
Find all the Prime Numbers until N #go
/*
Observation: A prime number N cannot be factored. So to find all the prime numbers til N
then for each n <= N we try to find if any number factors the n. If yes we abort as we know that n is not a prime.
*/
func GetPrimeNumbers(to int) []int {
result := []int{}
for i := 1; i <= to; i+=1 {
isFactored := false
for j := 2; j <= i/2; j+=1 {
if i % j == 0 {
isFactored = true
break
}
}
if !isFactored && i != 1 {
result = append(result, i)
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment