这两个程序都是求两个数的公约数。
输入:A=100000 B=100000
python 36(正确)
CPP 35(错误)
首先求两个数的gcd,然后求gcd的因子,得到公约数。
我从中找到python程序
here
我试图把它转换成cpp,但我得到了错误的答案。
蟒蛇:
def ngcd(x, y):
i=1
while(i<=x and i<=y):
if(x%i==0 and y%i == 0):
gcd=i;
i+=1
return gcd;
def num_comm_div(x, y):
n = ngcd(x, y)
result = 0
z = int(n**0.5)
i = 1
while( i <= z ):
if(n % i == 0):
result += 2
if(i == n/i):
print("I am executed at ",i) # never executed
result-=1
i+=1
return result
print("Number of common divisors: ",num_comm_div(2, 4))
print("Number of common divisors: ",num_comm_div(2, 8))
print("Number of common divisors: ",num_comm_div(100000, 100000))
CPP:
#include
#include
using namespace std;
int gcd(int a,int b){
if(b==0)
return a;
return gcd(b,a%b);
}
int main(){
int t;
cin>>t;
while(t--){
int a,b;
cin>>a>>b;
int n = gcd(a,b);
cout<
int ans=0;
for(int i=1;i<=(int)sqrt(n);i++){
if(n%i==0){
ans+=2;
}
if(i==n/i)
{
printf("I am executed at %d \n",i);//executed at i=316
ans--;
}
}
cout<
}
}