One of my favorite algorithms is the simple, elegant Euclidean algorithm for finding the greatest common denominator of two numbers. In ML or another functional language it really is beautiful:
1 2 | fun gcd(a, 0) = a | gcd(a, b) = gcd(b, a mod b); |
Of course, the same can be done in Java iteratively:
1 2 3 4 5 6 7 8 9 | public int gcd(int a, int b){ int c; while (b>0){ c = a; a = b; b = c%b; } return a; } |
Or recursively:
1 2 3 4 5 6 7 | public int gcd(int a, int b){ if(b==0){ return a; }else{ return gcd(b, a%b); } } |