following code judge with C++ got WA,why?
Code:
#include <iostream>
using namespace std;
long int GCD(long int x,long int y){
if(0==y)return x;
else if(0==x)return y;
if(x<y)GCD(x,y%x);
else GCD(y,x%y);
}
int main()
{
long int i=0,j=0,N=0;
long int GGG=0;
while(cin>>N){
if(0==N)break;
GGG=0;
for(i=1;i<N;i++)
for(j=i+1;j<=N;j++)
{
GGG+=GCD(i,j);
}
cout<<GGG<<endl;
}
return 0;
}
and I use same method to store the cout value to the array with VC 2005,
it works and got AC... it's impossible! how could this happen?
why this code get WA?
Ans:
your GCD function doesn't return if x!=0 && y!=0.
change
Code:
if(x<y)GCD(x,y%x);
else GCD(y,x%y);
to
Code:
if(x<y)return GCD(x,y%x);
else return GCD(y,x%y);
沒有留言:
張貼留言