python cpp,python和cpp的行为不同

这两个程序都是求两个数的公约数。

输入: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<

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值