加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

递归/非递归的辗转相除法、辗转相减法求最大公约数

(2011-01-26 23:55:55)
标签:

辗转相除法

辗转相减法

最大公约数

最小公倍数

it

分类: 算法

辗转相除法,即欧几里德算法;

辗转相减法,即尼考曼彻斯法。

以下为Java代码:

public class exp
{
 static public int gcd1_1(int x,int y)   //非递归的辗转相除法
 {
  int temp;
  
  do{
  temp = x % y;
  x = y;
  y = temp;
  }while(temp != 0); 
  
  return x;
 }
 
 static public int gcd2_1(int x,int y)   //非递归的辗转相减法
 {
  int max,min;
  int temp;
  max = (x>y)?x:y;
  min = (x<y)?x:y;
  
  while (max != min)
  {
   temp = max - min;
   max = (temp>min)?temp:min;
   min = (temp<min)?temp:min;   
  }
  
  return max;
 }
 
 static public int gcd1_2(int x,int y)   //递归的辗转相除法
 {
  return (y==0)?x:gcd1_2(y,x%y);
 }
 
 static public int gcd2_2(int x,int y)   //递归的辗转相减法
 {
  if(x==y) return x;
  return (x>y)?gcd2_2(x-y,y):gcd2_2(x,y-x);
 }
 
 public static void main(String args[])
 {
  int a=28,b=48;
  int g = 0;
  g = gcd1_1(a,b);
  System.out.println(g);
  g = gcd1_2(a,b);
  System.out.println(g);
  g = gcd2_1(a,b);
  System.out.println(g);
  g = gcd2_2(a,b);
  System.out.println(g);
  System.out.println(a*b/g); // 最小公倍数
 }

 

运行结果:

4

4

4

4

336

 

另附记移位法:

 static public int gcd(int a,int b)
 {
     if(a==b) return a;
     if((a&1)==0)
     {
         if((b&1)==0)
             return gcd(a>>1,b>>1)<<1;
         else
             return gcd(a>>1,b);
     }
     else
     {
         if((b&1)==0)
             return gcd(a,b>>1);
         else
             return gcd(((a>b)?(a-b):(b-a))>>1,(a+b)>>1);
     }
  }

 

 

0

阅读 收藏 喜欢 打印举报/Report
前一篇:汉诺塔
后一篇:浮沉冒泡排序
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有