python vs cpp表现不同

时间:2019-02-11 19:55:14

标签: python c++ numbers theory

两个程序都求两个数字的公因数。

输入:a = 100000 b = 100000

  

python 36(正确)

     

cpp 35(错误)

首先我找到两个数的gcd,然后找到gcd的因数以获得公因数。 我从here找到了python程序 并且我试图将其转换为cpp,但是我得到了错误的答案。

python:

$cb = intersection( 0, 163, 123, 256, 0, 133, 93, 256 );

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))

1 个答案:

答案 0 :(得分:1)

在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--;
    }
}
相关问题