1.辗转相除法:
gcd(m,n)=gcd(n,m%n)
2.中学时计算gcd( m , n ),分别m,n所有的质因数,然后相同的质因数积值就是最大公约数
public class Euclid {
static int[] primeArray={2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,
151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229};//50
public static void main(String[] args) {
// Scanner scanner=new Scanner(System.in);
gcdClass m=new gcdClass(24,60);
//method1
// System.out.println(m.calculate());
// System.out.println(m.getFrequency());
//method2
System.out.println(m.calculate_primeArray());
Prime();//生成prime数
}
static class gcdClass{
int a,b;//a>b
int frequency;
public gcdClass(int a,int b) {
if(a<b) {
int temp=a;a=b;b=temp;
}
this.a=a;
this.b=b;
this.frequency=1;
}
public int calculate(){
while(a%b!=0){
int t=a;
a=b;
b=t%b;
frequency++;
}
return b;
}
public int getFrequency(){
return frequency;
}
public int calculate_primeArray(){
ArrayList<Integer> aArray=new ArrayList<>();
ArrayList<Integer> bArray=new ArrayList<>();
while(a!=1){
for(int i=0;i<primeArray.length && primeArray[i]<=a;i++){
if(a%primeArray[i]==0){
aArray.add(primeArray[i]);
System.out.print(primeArray[i]+" ");
a/=primeArray[i];
break;
}
}
}
while(b!=1){
for(int i=0;i<primeArray.length && primeArray[i]<=b;i++){
if(b%primeArray[i]==0){
bArray.add(primeArray[i]);
System.out.print(primeArray[i]+" ");
b/=primeArray[i];
break;
}
}
}
return findCommonProduct(aArray,bArray);
}
}
public static int findCommonProduct(ArrayList<Integer>A ,ArrayList<Integer>B){//辅助method2
int P=1;
int i=0,j=0;
System.out.println(A.get(1));
while(i<A.size() && j< B.size()){
if(A.get(i)==B.get(j)) {
P *= A.get(i);
i++;
j++;
}
else if(A.get(i)>B.get(j)) j++;
else if(A.get(i)<B.get(j)) i++;
}
return P;
}
public static void Prime(){//默认生成50个质数 //辅助method2
int cnt=0;
int i=2;
boolean flag;
while(cnt<50){
flag=true;
for(int j=2;j*j<i;j++){
if(i%j==0) {
flag = false;
break;
}
}
if(flag){
// System.out.println(flag+" "+i);
System.out.print(i+", ");
cnt++;
}
i++;
}
}
}