执行速度(从快->慢):__gcd()algorithm库函数>gcd更相减损术与移位结合>gcd1更相减损术>gcd2辗转相除法
#include <iostream> #include <cstdio> #include <climits> #include <algorithm> using namespace std; //gcd更相减损术与移位结合 int gcd(int a, int b) { if(a < b) return gcd(b, a); if(b == 0) return a; if(!a & 1){ //a为b均为偶数 if(!b & 1) return gcd(a >> 1, b >> 1) << 1; //a为偶数,b为奇数 else return gcd(a >> 1, b); } else{ //a为奇数,b为偶数 if(!b & 1) return gcd(a, b >> 1); //a为奇数,b为奇数 else return gcd(a - b, b); } } //gcd1更相减损术 int gcd1(int a, int b){ if(a < b) return gcd1(b, a); if(b == 0) return a; else return gcd1(a - b, b); } //gcd2辗转相除法 int gcd2(int a, int b){ if(b == 0) return a; return gcd2(b, a % b); } int main(){ int n; while(~scanf("%d", &n)){ int maxn, minn; scanf("%d", &minn); maxn = minn; for(int i = 1; i < n; i++){ int x; scanf("%d", &x); maxn = max(maxn, x); minn = min(minn, x); } //printf("%d %d %d\n", minn, maxn, __gcd(minn, maxn));//使用algorithm库函数 printf("%d %d %d\n", minn, maxn, gcd(minn, maxn));//gcd更相减损术与移位结合 //printf("%d %d %d\n", minn, maxn, gcd1(minn, maxn));//gcd1更相减损术 //printf("%d %d %d\n", minn, maxn, gcd2(minn, maxn));//gcd2辗转相除法 } return 0; }