这两种方案都找两个数字的公约数的数目。
INPUT:A = 100000 B = 10万
蟒36(正确的)
CPP 35(错误的)
首先我觉得gcd上述两个数字,然后找到最大公约数的因素获得的公约数。我找到here Python程序,我试图将其转换成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<bits/stdc++.h>
#include<cmath>
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<<n<<endl;
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<<ans<<endl;
}
}
请注意,这if
在Python:
if(n % i == 0):
result += 2
if(i == n/i):
print("I am executed at ",i) # never executed
result-=1
第二届if
包含在第一主体。在C ++中你对应的块应该是:
if(n%i==0){
ans+=2;
if(i==n/i)
{
printf("I am executed at %d \n",i);//executed at i=316
ans--;
}
}