两个非常大的数的乘积的第一个数字 [英] First digit of the product of two very large numbers

查看:164
本文介绍了两个非常大的数的乘积的第一个数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有2个大整数,x和y使得z = x * y溢出。
我想计算x的第一个数字。直接这样做是不可能的,因为结果溢出。



我想知道是否有一个特定的技术。



例如:10000000000000000000000000000000000 * 20579725928294522859735727575,这里的第一个数字是2,我可以直接看到,但是,除了这个特殊情况,有没有办法?

  #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;
}

上面的代码无法正常工作。
对于
x = 10000000000000000000000000000000000
y = 20579725928294522859735727575



它将输出5作为z溢出,因此z = 5240626126797720724,这显然是错误的。

您可以用字符串 来执行乘法

,就像我多年前在学校学到的。

 
123456789987654321 * 998877665544332211

123456789987654321
* 998877665544332211
--------------------------------------
123456789987654321
123456789987654321
246913579975308642
246913579975308642
370370369962962963
370370369962962963
493827159950617284
493827159950617284
617283949938271605
617283949938271605
740740739925925926
740740739925925926
864197529913580247
864197529913580247
987654319901234568
987654319901234568
1111111109888888889
+ 1111111109888888889
-------------- ------------------------
123318230178465034444583004253633731


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.

解决方案

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

这篇关于两个非常大的数的乘积的第一个数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆