问题
There are 2 large integers, x and y such that z=x*y overflows. I would like to compute the first digit of x. Directly doing so isn't possible as the result overflows.
I was wondering if there was a certain technique for this.
Example: 10000000000000000000000000000000000 * 20579725928294522859735727575, here the first digit is 2 as I can see it directly, however, besides this special case, is there a way?
#include <iostream>
using namespace std;
int main() {
long long int x,y,z;
cin>>x>>y;
z=x*y;
while(z>9)
{
z/=10;
}
cout<<z;
return 0;
}
Above is a code that fails to work. For x=10000000000000000000000000000000000 y=20579725928294522859735727575
It gives output 5 as z overflows, and thus z=5240626126797720724 which is clearly wrong. I am looking to find a way out of this.
回答1:
You can do the multiplication with strings, like I learned in school many years ago
123456789987654321 * 998877665544332211 123456789987654321 * 998877665544332211 -------------------------------------- 123456789987654321 123456789987654321 246913579975308642 246913579975308642 370370369962962963 370370369962962963 493827159950617284 493827159950617284 617283949938271605 617283949938271605 740740739925925926 740740739925925926 864197529913580247 864197529913580247 987654319901234568 987654319901234568 1111111109888888889 + 1111111109888888889 -------------------------------------- 123318230178465034444583004253633731
回答2:
In general; the most significant digit of the result depends on all the other digits, so you can't determine the most significant digit without determining all the other digits too.
For example, consider 3333334 * 3, where the carry would ripple all the way from the least significant digit all the way to the most significant digit.
Note that this is really:
4 * 3 * 1
+ 3 * 3 * 10
+ 3 * 3 * 100
+ 3 * 3 * 1000
+ 3 * 3 * 10000
+ 3 * 3 * 100000
+ 3 * 3 * 1000000
..where the problem is that each addition can cause carries.
For multiple digits it gets worse. For example, 3333334 * 31 becomes:
+ 4 * 1 * 1
+ 3 * 1 * 10
+ 3 * 1 * 100
+ 3 * 1 * 1000
+ 3 * 1 * 10000
+ 3 * 1 * 100000
+ 3 * 1 * 1000000
+ 4 * 3 * 10
+ 3 * 3 * 100
+ 3 * 3 * 1000
+ 3 * 3 * 10000
+ 3 * 3 * 100000
+ 3 * 3 * 1000000
+ 3 * 3 * 10000000
回答3:
you can use Boost's Multiprecision Library to create big enough integers that would not overflow. But as to figuring out what the first digit is, you can turn your integer into string and then turn the first character of the string into integer. Having said that I fail to see why you would need such thing. If you are working with such big numbers that computation on them causes overflow, you should use something other than integer (Like BCD or boost) instead of regular int.
Sam
来源:https://stackoverflow.com/questions/37682728/first-digit-of-the-product-of-two-very-large-numbers