Advertisement
Guest User

Untitled

a guest
Sep 16th, 2014
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.94 KB | None | 0 0
  1. /**
  2.  * This class includes a silmple method to compute the greatest common divisor of
  3.  * two possitive integers using Euclid's algorithm.
  4.  * Time complexity is O(log n), being n the greatest number
  5.  */
  6.  
  7. /**
  8.  * @author adrian
  9.  *
  10.  */
  11. public class Gcd {
  12.    
  13.     // computes the greatest common divisor of two possitive integers using Euclid's algorithm
  14.     public int gcd(int a, int b) {
  15.         if (a < 0 || b < 0) {
  16.             throw new java.lang.IllegalArgumentException("Numbers must be non-negative");
  17.         }
  18.         if (b == 0) {
  19.             return a;
  20.         }
  21.         return gcd(b, a%b);
  22.     }
  23.  
  24.     /**
  25.      * @param args
  26.      */
  27.     public static void main(String[] args) {
  28.         Gcd solver = new Gcd();
  29.        
  30.         // set input numbers
  31.         int a = 30;
  32.         int b = 12;
  33.         if (a == 0 || b == 0) {
  34.             throw new java.lang.IllegalArgumentException("Numbers must be non-zero integers");
  35.         }
  36.         System.out.println("Greatest common divisor for " + a + " and " + b
  37.                 + " is: " + solver.gcd(a, b));
  38.  
  39.     }
  40.  
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement