简体   繁体   中英

How to convert this Python to C++ without overflow?

I have the following Python snippet

v=(2*(a/2)+1)**2
U=int(((4*N+v)**.5-1)/4)

N is on the order of 10^12, and the variable "a" takes on many values but is also of 10^12 magnitude at its largest.

However I can't seem to write this in C++ without overflowing something somewhere and I am a little stuck.

edit: And yes, the 2*(a/2) is intentional because in Python, division is the same as floor division. Sometimes a is odd so I need to halve it, floor it, then remultiply it by 2, which is what that code does.

>>> a=10**12
>>> v=(2*(a/2)+1)**2
>>> log(v,2)
79.72627427729958

The value you're calculating needs 80 bits, and a long long is only 64. You'll need an extended arithmetic package to handle it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM