[英]How to convert this Python code to C++
I have a working algorithm in Python which I want to convert to C++: 我在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
I'm having a problem with large input values as the multiple of N and M causes integer overflow and using long
to store its value doesn't seem to help, unless I'm doing something wrong. 我遇到了输入值较大的问题,因为N和M的倍数会导致整数溢出,并且使用
long
来存储其值似乎无济于事,除非我做错了事。
Here's my current code: 这是我当前的代码:
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;
}
To begin with, change: 首先,更改:
long m = N * M;
int lcm = m / g;
To: 至:
long long m = (long long)N * M;
int lcm = (int)(m / g);
In general, you might as well change every int
in your code to unsigned long long
... 通常,您最好将代码中的每个
int
更改为unsigned long long
...
But if you have some BigInt
class at hand, then you might want to use it instead. 但是,如果手头有一些
BigInt
类,则可能要改用它。
Here is one for free: http://planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=9735&lngWId=3 这是免费的一个: http : //planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=9735&lngWId=3
It stores a natural number of any conceivable size, and supports all arithmetic operators provided in C++. 它存储任何可能大小的自然数,并支持C ++中提供的所有算术运算符。
You are computing g=gcd(N,M)
, then m=N*M
, then lcm=m/g
, and finally returning lcm/M
. 您正在计算
g=gcd(N,M)
,然后是m=N*M
,然后是lcm=m/g
,最后返回lcm/M
That's the same as returning N/gcd(N,M)
. 这与返回
N/gcd(N,M)
。 You don't need those intermediate calculations. 您不需要这些中间计算。 Get rid of them.
摆脱它们。 Now there's no problem with overflow (unless M=0, that is, which you aren't protecting against).
现在,溢出没有问题(除非M = 0,也就是说,您无法避免)。
int solution(int N, int M) {
if (M == 0) {
handle_error();
}
else {
return N / gcd(N,M);
}
}
The problem is in long m = N*M.
问题出在
long m = N*M.
The multiplication takes place as 32 bit integers only. 乘法仅作为32位整数发生。 Since both are of
int
type, overflow occurs. 由于两者均为
int
类型,因此会发生溢出。
Correction is long long m = (long long)N*M
校正
long long m = (long long)N*M
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.