You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
1.2 KiB

  1. package prime
  2. import "math/rand"
  3. const (
  4. // MaxPrime is to get a prime value below this number
  5. MaxPrime = 2000
  6. // MinPrime is to get a prime value above this number
  7. MinPrime = 500
  8. )
  9. // RandInt returns a random integer between two values
  10. func RandInt(min int, max int) int {
  11. r := rand.Intn(max-min) + min
  12. return r
  13. }
  14. // RandPrime returns a random prime number between two values
  15. func RandPrime(min int, max int) int {
  16. primes := SieveOfEratosthenes(max)
  17. randN := rand.Intn(len(primes)-0) + 0
  18. return primes[randN]
  19. }
  20. // SieveOfEratosthenes returns a list of primes less than N
  21. func SieveOfEratosthenes(N int) (primes []int) {
  22. b := make([]bool, N)
  23. for i := 2; i < N; i++ {
  24. if b[i] == true {
  25. continue
  26. }
  27. primes = append(primes, i)
  28. for k := i * i; k < N; k += i {
  29. b[k] = true
  30. }
  31. }
  32. return
  33. }
  34. // Gcd returns the greatest common divisor
  35. func Gcd(a, b int) int {
  36. var bgcd func(a, b, res int) int
  37. bgcd = func(a, b, res int) int {
  38. switch {
  39. case a == b:
  40. return res * a
  41. case a%2 == 0 && b%2 == 0:
  42. return bgcd(a/2, b/2, 2*res)
  43. case a%2 == 0:
  44. return bgcd(a/2, b, res)
  45. case b%2 == 0:
  46. return bgcd(a, b/2, res)
  47. case a > b:
  48. return bgcd(a-b, b, res)
  49. default:
  50. return bgcd(a, b-a, res)
  51. }
  52. }
  53. return bgcd(a, b, 1)
  54. }