解答
1 根据书上的理解,有三种方式:辗转相除法,辗转相减法,综合解决法。
2 辗转相除法的缺点:用模,大数运算量大;
辗转相减法的缺点:一个数大,一个数小;
3 综合解决法的办法,是利用模2和答案的关系来处理。
代码
public static int method1(int number1 ,int number2){
//辗转相除法
return (number2==0)?
number1:method1(number2,number1%number2);
}
public static int method2(int number1, int number2){
if(number1<number2){
return method2(number2,number1);
}
if(number2 ==0){
return number1;
}
return method2(number2,number1-number2);
}
public static int method3(int number1,int number2){
if(number1<number2){
return method3(number2,number1);
}
if(number2 ==0){
return number1;
}
else {
if(IsEven(number1)){
if(IsEven(number2)){
return (method3(number1>>1, number2>>1)<<1);
}
else
{
return method3(number1>>1, number2);
}
}
else{
if(IsEven(number2)){
return method3(number1, number2>>1);
}
else
{
return method3(number2, number1-number2);
}
}
}
}
private static boolean IsEven(int number1) {
return (number1&0x00000001)==0?true:false;
}