Multiplying two number arrays

这一生的挚爱 提交于 2019-12-13 03:24:20

问题


Can anyone please tell me how to multiply two number arrays in C? The number arrays are basically derived from two strings containing digits. eg: 123456 and 132465.

Edit: I had two string as S1 = "123456" and S2="132546". I then converted these two strings into array of ints i.e. int IS1[6] and IS2[6] so that

IS1[1] = 1, IS1[2] = 2......

and

IS2[1] = 1, IS2[2] = 3.....

Now I have to mulitply these two arrrays. Please help.


回答1:


It's not clear what exactly you want to multiply. If you need to multiply two null terminated strings in a char[], you can convert them to int values with atoi:

int result = atoi(str1) * atoi(str2);



回答2:


If you want to use the paper-and-pencil arithmetics and don't know how to do that, here is the illustration.




回答3:


I just code a simple program multiply two number stored in 2 line in file using algorithm long multiplication. It can multiply two number which have more than 1 billion number in each other

Example:

            23958233
            5830 ×
         ------------
            00000000  ( =      23,958,233 ×     0)
           71874699   ( =      23,958,233 ×    30)
          191665864   ( =      23,958,233 ×   800)
         119791165    ( =      23,958,233 × 5,000)

Source code:

Please review and give your comment http://code.google.com/p/juniormultiply/source/browse/#svn/trunk/src




回答4:


If your numbers are small enough, parse them into ints (atoi).

If they are too large to fit into ints:

  • use a library such as gmp

  • or use the pencil-and-paper algorithm, but you'll be reinventing the wheel.




回答5:


Well, if you want to generate an array containing the multiplications, you could use:

int *a, *b, *c; // pointers to arrays of size n
for (unsigned i=0;i<n;++i)
  c[i] = a[i] * b[i];

If you want the inner product, this is how you could do it:

int *a, *b; // pointers to arrays of size n
int res = 0;
for (unsigned i=0;i<n;++i)
  res += a[i] * b[i];

If, like previous answers suggest, what you wanted was to treat the two arrays as numbers you could use the atoi() function as mentioned.




回答6:


If it is for a real project, do the conversion.

If this is an exercise of algorithm, do the multiple loop according to the pencil and paper approach.



来源:https://stackoverflow.com/questions/1869245/multiplying-two-number-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!