博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Binary GCD algorithm
阅读量:6186 次
发布时间:2019-06-21

本文共 1925 字,大约阅读时间需要 6 分钟。

基于二进制计算最大公约数的算法。

程序来自维基百科。

#include 
// Recursive version in Cunsigned int gcd(unsigned int u, unsigned int v){ // simple cases (termination) if (u == v) return u; if (u == 0) return v; if (v == 0) return u; // look for factors of 2 if (~u & 1) // u is even { if (v & 1) // v is odd return gcd(u >> 1, v); else // both u and v are even return gcd(u >> 1, v >> 1) << 1; } if (~v & 1) // u is odd, v is even return gcd(u, v >> 1); // reduce larger argument if (u > v) return gcd((u - v) >> 1, v); return gcd((v - u) >> 1, u);}// Iterative version in Cunsigned int gcd2(unsigned int u, unsigned int v){ int shift; /* GCD(0,v) == v; GCD(u,0) == u, GCD(0,0) == 0 */ if (u == 0) return v; if (v == 0) return u; /* Let shift := lg K, where K is the greatest power of 2 dividing both u and v. */ for (shift = 0; ((u | v) & 1) == 0; ++shift) { u >>= 1; v >>= 1; } while ((u & 1) == 0) u >>= 1; /* From here on, u is always odd. */ do { /* remove all factors of 2 in v -- they are not common */ /* note: v is not zero, so while will terminate */ while ((v & 1) == 0) /* Loop X */ v >>= 1; /* Now u and v are both odd. Swap if necessary so u <= v, then set v = v - u (which is even). For bignums, the swapping is just pointer movement, and the subtraction can be done in-place. */ if (u > v) { unsigned int t = v; v = u; u = t;} // Swap u and v. v = v - u; // Here v >= u. } while (v != 0); /* restore common factors of 2 */ return u << shift;}int main(void){ unsigned m = 140, n = 42; printf("gcd1: %u %u result=%u\n", m, n, gcd(m, n)); printf("gcd2: %u %u result=%u\n", m, n, gcd2(m, n)); return 0;}

转载于:https://www.cnblogs.com/tigerisland/p/7564914.html

你可能感兴趣的文章
C++知识点
查看>>
死锁、进程通信
查看>>
centos 7扩展磁盘分区容量
查看>>
github 新建一个分支
查看>>
[MEF] 学习之一 入门级的简单Demo
查看>>
2017全国卷1文科第9题高考真题的解法
查看>>
坐标系与参数方程习题01【中级高阶辅导】
查看>>
Java 可视化垃圾回收
查看>>
【10-25】intelliji ide 学习笔记
查看>>
JavaScript常用方法
查看>>
让普通用户可以控制树莓派的GPIO(Archlinuxarm)
查看>>
洛谷P2485 [SDOI2011]计算器(exgcd+BSGS)
查看>>
Apache和Tomcat的区别
查看>>
Katalon Recorder初探
查看>>
20160929001 Guid生成
查看>>
Java知多少(109)数据库更新
查看>>
HNUSTOJ-1437 无题
查看>>
WKWebView使用
查看>>
2017CCPC秦皇岛 C题Crusaders Quest&&ZOJ3983【模拟+STL】
查看>>
JSOI2015 R3 退队滚粗了
查看>>