python - 如何将此 Python 代码转换为 C++

标签 python c++ integer overflow

我在 Python 中有一个工作算法,我想将其转换为 C++:

def gcd(a, b):    
    if (a % b == 0):
        return b
    else:
        return gcd(b, a % b)

def solution(N, M):
    lcm = N * M / gcd(N, M)
    return lcm / M

我遇到大输入值的问题,因为 N 和 M 的倍数导致整数溢出,使用 long 来存储它的值似乎没有帮助,除非我正在做某事错了。

这是我当前的代码:

int gcd(int a, int b)
{
    if (a % b == 0)
        return b;
    else
        return gcd(b, a % b);
}

int solution(int N, int M) {

    // Calculate greatest common divisor
    int g = gcd(N, M);

    // Calculate the least common multiple
    long m = N * M;
    int lcm = m / g;

    return lcm / M;
}

最佳答案

您正在计算 g=gcd(N,M),然后是 m=N*M,然后是 lcm=m/g,最后返回 lcm/M。这与返回 N/gcd(N,M) 相同。您不需要那些中间计算。摆脱他们。现在溢出没有问题(除非 M=0,也就是说,您没有防止溢出)。

int solution(int N, int M) {
   if (M == 0) {
      handle_error();
   }
   else {
      return N / gcd(N,M);
   }
}

关于python - 如何将此 Python 代码转换为 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21960860/

相关文章:

java - TODO-FIXME : In Java 8's Integer class?

c++ - 如果输入是一个字符然后在 C++ 中存储在一个整数中,为什么 cin 会得到奇怪的值?

python - 关于在 gensim 中如何实现 tf-idf 模型的一些困惑

python - Heroku Procfile 不进入目录?

python - 如何用时区解析时间戳?

c++ - 安卓NDK : unable to open database file using sqlite3_open

c++ - 是否可以在调用 .str() 之前知道 std::wostringstream 的长度?

python - Gmpy sqrt精度

C++ 对象实例化和作用域

c中二维数组中整数的连续间隔输入