FermatsLittleTheorm.groovy 946 B

1234567891011121314151617181920212223242526272829303132333435
  1. package com.garypaduana.groovytools.algorithm
  2. class FermatsLittleTheorm{
  3. /**
  4. * Implementation of Fermat's Little Theorm to determine if a
  5. * number is probably prime.
  6. */
  7. static def probablyPrime(def p){
  8. for(int i = 0; i < 30; i++){
  9. def a = randomBetween(2, p)
  10. if(!congruentModulo(a.pow(p.intValue() - 1), 1, p)){
  11. return false
  12. }
  13. }
  14. return true
  15. }
  16. /**
  17. * Returns a number between the two arguments inclusive to
  18. * the first argument and exclusive of the second. Ordering
  19. * does not matter.
  20. */
  21. static def randomBetween(def a, def b){
  22. Random r = new Random()
  23. return BigInteger.valueOf((long) r.nextDouble() * (b - a) + a)
  24. }
  25. /**
  26. * Determines if arguments a and b are congruent modulo to n.
  27. */
  28. static def congruentModulo(def a, def b, def n){
  29. return (a - b) % n == 0
  30. }
  31. }