fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static int gcd(int a, int b)
  11. {
  12. return b != 0 ? gcd(b, a % b) : a;
  13. }
  14. public static int gcd_binary(int u, int v) throws Exception
  15. {
  16. if(u < 0 || v < 0)
  17. {
  18. throw new IOException("Invalid Input Value, params couldn't be less than zero");
  19. }
  20. if(u == v)
  21. return v;
  22.  
  23. if(u == 0)
  24. return v;
  25.  
  26. if(v == 0)
  27. return u;
  28.  
  29. if((~u & 1) == 1) {
  30. if((v & 1) == 1) {
  31. return gcd(u >> 1, v);
  32. }
  33. else
  34. return gcd(u >> 1, v >> 1) << 1;
  35. }
  36. if( (~v & 1) == 1)
  37. return gcd(u, v >> 1);
  38.  
  39. if(u > v)
  40. return gcd((u - v) >> 1, v);
  41.  
  42. return gcd((v - u) >> 1, u);
  43. }
  44. public static void main (String[] args) throws java.lang.Exception
  45. {
  46. // your code goes here
  47. PrintWriter out = new PrintWriter(System.out);
  48. out.println(gcd_binary(16, 52));
  49. out.flush();
  50. }
  51. }
Success #stdin #stdout 0.06s 711168KB
stdin
Standard input is empty
stdout
4