辗转相除法

来源:互联网 发布:网络肥皂是什么意思啊 编辑:程序博客网 时间:2024/06/05 03:59
//辗转相除法public class Solution4 {    public static int gcd(int a,int b){        while (b !=0){            int temp = a%b; // %取余数,比如10%3 结果为1; /除法,取整,比如10/3 结果为3。            System.out.println("temp's value:"+temp);            a = b;            b = temp;        }        return a;    }    public static int gcd2(int a, int b) //返回a,b的最大公因数,递归方法    {        if(b==0)            return a;        if(a<0)            return gcd2(-a, b);        if(b<0)            return gcd2(a, -b);        return gcd2(b, a%b);    }    public static void main(String args[]){        int a = gcd(26460,12375);        System.out.println("两个数的最大公约数:"+a);        int b = gcd(gcd(20,30),50);        System.out.println("三个数的最大公约数:"+a);        int c = gcd2(8,10);        System.out.println("递归求两个数的最大公约数:"+a);    }}//输出://        temp's value:1710//        temp's value:405//        temp's value:90//        temp's value:45//        temp's value:0//        两个数的最大公约数:45//        temp's value:20//        temp's value:10//        temp's value:0//        temp's value:10//        temp's value:0//        三个数的最大公约数:45//        递归求两个数的最大公约数:45
0 0
原创粉丝点击