Python 与 CPP 的行为不同
python vs cpp behaving differently
这两个程序都是求两个数的公约数。
输入:a=100000b=100000
蟒蛇 36(正确(
CPP 35(错误(
首先,我找到两个数字的 gcd,然后找到 gcd 的因子以获得公约数。我从这里找到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;
}
}
注意 Python 中的if
:
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--;
}
}
相关文章:
- 如何运行位于boost/libs/python/example/tutorial目录中的hello.cpp和Jamfil
- 是否可以使用 libclang python 解析 cpp 文件中没有标头的函数原型
- 如何大致将 cpp 代码结构转换为 python
- 在 cpp 中嵌入 python:如何获取指向 python 函数(而不是 PyObject)的 C 指针?
- 在cpp中使用boost-python的python代码是否进行动态内存分配
- ROS CPP 相当于 Python subprocess.call() 和 shell=True
- Python vs CPP:为什么速度差异如此之大
- Or-Tools:CPP中琐碎的问题是不可行的,但在Python中起作用
- 从 Python 中以“.cpp”格式保存 LGBM 模型
- 使用python在非阳性组件中使用python与cpp中的特征库来计算特征值
- 编译 PythonService.cpp来自 win32 Python 扩展构建
- 如何在 Coverity Scan 中忽略生成的 cpp 文件(来自 swig/python)
- 从 python ctypes 调用 CPP 函数
- 将Python词典转换为CPP对象
- 将CPP EXE打印到Python脚本输入中
- Python 与 CPP 的行为不同
- 如何比较cpp和python输出
- Python 子进程.Popen 在 g++ 中编译,自动添加.cpp文件
- Swig C++ to python:编译一堆.cpp和.h文件
- Murmurhash3的Javascript实现,给出与Murmurhash3相同的结果.cpp Python的sklearn中可用的transform使用Murmurhash3