Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * This class includes a silmple method to compute the greatest common divisor of
- * two possitive integers using Euclid's algorithm.
- * Time complexity is O(log n), being n the greatest number
- */
- /**
- * @author adrian
- *
- */
- public class Gcd {
- // computes the greatest common divisor of two possitive integers using Euclid's algorithm
- public int gcd(int a, int b) {
- if (a < 0 || b < 0) {
- throw new java.lang.IllegalArgumentException("Numbers must be non-negative");
- }
- if (b == 0) {
- return a;
- }
- return gcd(b, a%b);
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- Gcd solver = new Gcd();
- // set input numbers
- int a = 30;
- int b = 12;
- if (a == 0 || b == 0) {
- throw new java.lang.IllegalArgumentException("Numbers must be non-zero integers");
- }
- System.out.println("Greatest common divisor for " + a + " and " + b
- + " is: " + solver.gcd(a, b));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement