Skip to content

Instantly share code, notes, and snippets.

@soltrinox
Created December 18, 2014 15:56
Show Gist options
  • Save soltrinox/4f98365b1a5fb6554a3f to your computer and use it in GitHub Desktop.
Save soltrinox/4f98365b1a5fb6554a3f to your computer and use it in GitHub Desktop.
GCD / LCD
public static int GCD(int a, int b){ //method signature. Takes two values and returns the GCD.
int temp;
if(a==b){ //Euclidean algorithm implementation. Recursion stopping case.
return(a);
}
if(a<b){ //Recursion. if a<b; switch to make a>b
temp=a;
a=b;
b=temp;
}
return(GCD(a-b,b)); //euclidean algorithm: GCD(a,b)=GCD(a-b,b)
}
public static int LCM(int a, int b){ //LCM method signature. two values; returns LCM
return(a*b/(GCD(a,b))); //by definition, a*b=GCD(a,b)*LCM(a,b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment