| 1 | package br.org.agilcoop.cursos.testes.unidade; |
| 2 | |
| 3 | public class MathHelper { |
| 4 | |
| 5 | public static long mdcAlgoritmoSuperLento(long a, long b) { |
| 6 | long maior = Math.max(a, b); |
| 7 | long menor = Math.min(a, b); |
| 8 | if(maior < 0 || menor < 0) throw new IllegalArgumentException("must be positive"); |
| 9 | if(maior == 0 || menor == 0) return 0; |
| 10 | // 10 e 5 = 5 |
| 11 | long mdc = 1; |
| 12 | for(long i = 2; i <= menor; i++) { |
| 13 | if(maior % i == 0 && menor % i == 0) |
| 14 | mdc = i; |
| 15 | } |
| 16 | return mdc; |
| 17 | } |
| 18 | |
| 19 | // Algoritmo de Euclides: mdc(a, b) = mdc(b, r) onde r: a = q * b + r |
| 20 | public static long mdcAlgoritmoEuclides(long a, long b) { |
| 21 | long valor = Math.max(a, b); |
| 22 | long divisor = Math.min(a, b); |
| 23 | if(valor < 0 || divisor < 0) throw new IllegalArgumentException("must be positive"); |
| 24 | if(valor == 0 || divisor == 0) return 0; |
| 25 | long resto = valor % divisor; |
| 26 | while(resto != 0) { |
| 27 | valor = divisor; |
| 28 | divisor = resto; |
| 29 | resto = valor % divisor; |
| 30 | } |
| 31 | return divisor; |
| 32 | } |
| 33 | |
| 34 | // Dois números naturais sempre têm divisores comuns. |
| 35 | public static long mdc(long a, long b) { |
| 36 | return mdcAlgoritmoEuclides(a, b); |
| 37 | } |
| 38 | |
| 39 | // calcula (num^exp) mod n |
| 40 | //http://en.wikipedia.org/wiki/Modular exponentiation |
| 41 | public static long potenciaModulo(long num, long exp, long n) { |
| 42 | long result = 1; |
| 43 | while (exp > 0) { |
| 44 | if ((exp & 1) > 0) result = (result * num) % n; |
| 45 | exp >>= 1; |
| 46 | num = (num * num) % n; |
| 47 | } |
| 48 | return result; |
| 49 | } |
| 50 | |
| 51 | } |