下面的代码编译并运行得很好。但是,如果我更换线路
int d=xgcd(x,y,&m,&n);
cout<<d << " = "<<m<<" * "<<x<<" + "<<n<<" * "<<y<<endl;
和
cout<< xgcd(x,y,&m,&n) << " = "<<m<<" * "<<x<<" + "<<n<<" * "<<y<<endl;
然后,m
并且n
将是零,而不是他们应该是什么。所以我想知道这种行为差异背后的原因是什么。我错过了什么吗?
这是用 C++ 编写的代码,我使用的是带有标志 -O0 的 gcc 4.72。
测试XGCD.cpp:
#include"xgcd.h"
#include<iostream>
#include<cstdlib>
using namespace std;
int main(int argc, char** argv) {
// Read the command line parameter
int x=atoi(argv[1]), y=atoi(argv[2]);
int m=0,n=0;
int d=xgcd(x,y,&m,&n);
// Output the result;
cout<<d << " = "<<m<<" * "<<x<<" + "<<n<<" * "<<y<<endl;
}
xgcd.h:
#ifndef XGCD
#define XGCD
#include<vector>
// Perform the extended Euclidean Algorithm.
// Find (m,n) and return it. pp and qp are two pointers to store the
// coefficients of m and n so 1 = pm + qn.
const int xgcd(int m, int n, int* pp = 0, int* qp = 0) {
// The temp variable to store the remainder.
int temp;
// Create a container to store the quotients.
std::vector<int> quotients;
// Start the Euclidean algorithm.
while(!(m==0)) {
// store the quotient for the extended Euclidean algorithm.
quotients.push_back(n/m);
temp = m;
m = n%m;
n = temp;
}
// Before performing the magic pattern Bud Brown showed us in class,
// put base value 0 and 1 to the end.
quotients.back() = 1;
quotients.push_back(0);
// Create an iterator to traverse the quotients and do the trick.
typename std::vector<int>::reverse_iterator rip = quotients.rbegin();
rip+=2;
// Do the trick here!
while(rip!=quotients.rend()) {
*rip=*rip * *(rip-1) + *(rip-2);
rip++;
}
// If there are odd number of quotients, the last value should be
// it's negative. Otherwise, the second last value should be negative.
if(quotients.size() % 2) {
if(pp!=0)
*pp=-quotients[0];
if(qp!=0)
*qp=quotients[1];
}else{
if(pp!=0)
*pp=quotients[0];
if(qp!=0)
*qp=-quotients[1];
}
return temp;
}
#endif
我为 xgcd.h 使用了头文件而不是 c 文件,因为我修改了我的原始模板实现,并且不费心为我的作业问题创建另一个单独的实现文件。
有谁知道为什么会有这样的差异?