求最大公约数的方法

                   求最大公约数

辗转相除法(欧几里德法):
1.大数放在a中,小数放在b中,a/b的余数放在temp中,若temp等于0,则最大公约数为b;
2.如若不等于0,则a=b,b=temp进行循环直到temp=0,则b为最大公约数
例如15和9 15/9=1……6,9/6=1……3,6/3=0则最大公约数等于3
循环:

public class Java {
    public static void main(String[] args) {
   int a=9;
   int b=15;
   int m=a;
   int n=b;
   int temp=0;
   if(a%b==0){
       System.out.println(b);
   }
   if(a<b){
       temp=a;
       a=b;
       b=temp;
   }
    temp=a%b;
   while(temp!=0){
       a=b;
       b=temp;
       temp=a%b;
   }
      System.out.println(b);  
}
}

最小公倍数=两个数的乘积/最大公约数;
循环函数

public class JavaApplication29 {
    public static void main(String[] args) {
   int a=15;
   int b=9;
       System.out.println(gcd(15,9));
   
    }
   public static int gcd(int a,int b){
       int temp=a%b;
   while(temp!=0){
       a=b;
       b=temp;
       temp=a%b;
   }
   return b;
   }
}

递归:

public class  Java {
    public static void main(String[] args) {
   int a=9;
   int b=15;
       System.out.println(gcd(15,9));
   
    }
   public static int gcd(int a,int b){
       int temp=a%b;
   if(temp==0){
      return b;
   }
   else{
       return gcd(b,a%b);
   }
   }
}

相减法(更相减损法)
1.如果a>b a=a-b;
2.如果 b>a b=b-a;
3.如果a=b,则a或b是最大公约数
4.如果 a!=b,则从1开始执行
5.循环判断的条件a!=b,直到a=b结束

public class Java{
    public static void main(String[] args) {
   int a=9;
   int b=15;
       System.out.println(gcd(15,9));
   
    }
   public static int gcd(int a,int b){
     while(a!=b){
      if(a>b){
          a=a-b;
   }
      else{
          b=b-a;
      }
     
   }
     return a;
   }
}

穷举法:
1.定义temp,把a.b中小的值给temp;
2.只要找到一个数能同时被,a.b整除则退出循环,否则temp–;

public class Java {
    public static void main(String[] args) {
   int a=9;
   int b=15;
       System.out.println(gcd(15,9));
   
    }
   public static int gcd(int a,int b){
     int temp;
     temp=(a>b)? b : a;
     while(temp>0){
         if(a%temp==0&&b%temp==0){
             break;
         }
         else{
             temp--;
         }
     }
     return temp;
   }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值