java用继承的方法求最大公倍数和最大公因数时,为什么最小公倍数a*b/m中的b会被吃掉?

public class SA {

    public int f(int a,int b) {
        int c;
        c=a%b;
        if(c==0) 
        return b;
        else return f(b,c);
    }
}

public class SB extends SA{
public int f(int a,int b) {
    int m;
    m=super.f(a,b);
    return a*b/m;
}
}

public class STest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SB q = new SB();
        System.out.println("最小公倍数为:"+q.f(9,6));
        SA w =new SA();
        System.out.println("最大公约数为:"+w.f(9,6));
    }
}

最小公倍数结果为什么不是18而是9(多次尝试后发现b/m是没有计算的)。


class SA {
    public int f(int a,int b) {
        int c = a>b?b:a;
        for(int i = c;i>=1;i--) {
        	if( a%i== 0 && b % i ==0) {
        		return i;
        	}
        }
        return c;
    }
}

class SB extends SA{
public int f(int a,int b) {
    int m;
    m=super.f(a,b);
    return a*b/m;
}
}

public class STest {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        SB q = new SB();
        System.out.println("最小公倍数为:"+q.f(9,6));
        SA w =new SA();
        System.out.println("最大公约数为:"+w.f(9,6));
    }
}

 

SA的f方法有问题吧,有点奇怪,b的值改为3 了

你用debug模式,跟一下代码看看

因为你这样设计,导致调用  m=super.f(a,b); 时,又会调用回 SB.f() 方法,因为你在 SA 里面写的是 f(b,c)。如果是这样的话,其实调用又变成了 SB.f()。

 

public class SA {
   public int f(int a,int b){
		if(a < b){  // 保证a为最大值
			int temp = a;
			a = b;
			b = temp;
		}
		
		while(b > 0){ // 求最大公约数
			if(a == b){
				return a;
			}else{
				int temp = a%b;
				a = b;
				b = temp;
			}
		}
		return a;
	}
}

你的问题在于没有保证第一个数为最大数。

class SA {
  public int f(int a,int b) {
    int c;
    c=a%b;
    if(c==0) {
      return b;
    } else {
      // 强行调用 SA 的 f
      return new SA().f(b,c);
    }
  }
}

这是我唯一想到的方法了。

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632