首页 技术 正文
技术 2022年11月21日
0 收藏 546 点赞 2,176 浏览 1564 个字

二进制GCD算法基本原理是:
 先用移位的方式对两个数除2,直到两个数不同时为偶数。然后将剩下的偶数(如果有的话)做同样的操作,这样做的原因是如果u和v中u为偶数,v为奇数,则有gcd(u,v)=gcd(u/2,v)。到这时,两个数都是奇数,将两个数相减(因为gcd(u,v) = gcd(u-v,v)),得到的是偶数t,对t也移位直到t为奇数。每次将最大的数用t替换。

二进制GCD算法优点是只需用减法和二进制移位运算,不像Euclid’s算法需要用除法,这在某些嵌入式系统中可能排上用场。

本例实现参考了<<计算机编程的艺术>>第二卷中介绍的算法。

public class GCD_Binary {
/**
* solve gcd using binary method
* @param u
* @param v
* @return gcd(u,v)
*/
public static int gcdBinary(int u,int v){
u=(u<)?-u:u;
v=(v<)?-v:v; if(u==)
return v;
if(v==)
return u; int k=;
while((u & 0x01)== && (v & 0x01) == ){
u>>=; //divide by 2
v>>=;
k++;
}
//at this time, there is at least one number is odd between m and n
int t=-v; //set it negative for later comparison of (t>0)
if((v & 0x01)==){
//v is odd
t = u;
}
//process t as a possible even number
while(t != ){
while((t & 0x01)==){
//do until t is not even
t>>=;
}
if(t>) //u > v (the max is replaced by |t|)
u=t;
else //u<v (the max is replaced by |t|)
v=-t;
//now u and v are all odd, then u-v is even
t = u-v;
}
return u*(<<k);
} public static void print(int m,int n,int gcd){
m = (m<)?-m:m;
n = (n<)?-n:n;
System.out.format("gcd of %d and %d is: %d%n",m,n,gcd);
} public static void main(String[] args) {
int m = -;
int n= ;
print(m,n,gcdBinary(m,n)); //co-prime
m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); m = ;
n= ;
print(m,n,gcdBinary(m,n)); }
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,027
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,518
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,365
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,146
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,780
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,857