![](/img/trans.png)
[英]Python subprocess.run timeout behaving differently on Windows vs Linux
[英]python vs cpp behaving differently
这两个程序都是求两个数的公约数。
输入:a=100000 b=100000
蟒蛇36(正确)
cpp 35(错误)
首先我找到两个数字的 gcd,然后找到 gcd 的因数以获得公约数。 我从这里找到了 python 程序,我试图将它转换为 cpp,但我得到了错误的答案。
Python:
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))
cp:
#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--;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.