简体   繁体   English

两个整数数组的成对乘法。 如果它们的长度不同,则较短的需要缠绕

[英]Pair-wise multiplication of two integer arrays. If they are of different lengths, the shorter one needs to wrap around

I have two integer arrays. 我有两个整数数组。

A[] = {3,4,5,6}
B[] = {1,2}

How can we multiply these two arrays in order to get a product of 3456*12 using long multiplication? 我们如何使用长乘法将这两个数组相乘以获得乘积3456*12

Very crude example in Python. Python中非常粗糙的示例。

a = [3,4,5,6]
b = [1,2]
result = []                        
for i in range(0, len(a)):
     result.append(a[i % len(a)]*b[i % len(b)])

print result

In Java 在Java中

 public static int mul(int[] a, int []b) {
      int res=0, i, j, mcol, mrow;
      for (mcol=1, i=a.length-1 ; i>=0 ; i--, mcol*=10) {
            for (mrow=1, j=b.length-1 ; j>=0 ; j--, mrow*=10) {
                 res += a[i] * b[j] * mcol * mrow;
            }
      }
      return res;
 }

Principle is the same as school multiplication 原理与学校乘法相同

3 4 5 6
x   1 2

=          2x6 + 2x5x10 + 2x4x100 +2x3x1000
   + 10 x (1x6 + 1x5x10 + 1x4x100 +1x3x1000)

Starting from 6 , multiply by 2 , then 2 x 5 in 2 nd position, so you have to *10 it, and add it to the result, and so on... 6开始,乘以2 ,然后在第二个位置乘以2 x 5 ,所以您必须将其*10 ,并将其添加到结果中,依此类推...

For the next digit, 1 , do the same operation, but multiply each time this result again by 10 since 1 is the next digit in the lower row. 对于下一个数字1 ,请执行相同的操作,但是每次将此结果再次乘以10因为1是下一行的下一个数字。


You can also consider the multiplication from the left side of the arrays. 您也可以考虑从数组的左侧进行乘法。

 public static int mul(int[] a, int []b) {
      int res=0, resrow, i, j;
      for (i=0 ; i<a.length ; i++) {
            for (resrow=j=0 ; j<b.length ; j++) {
                 resrow = resrow * 10 + a[i] * b[j];
            }
            res = res * 10 + resrow;
      }
      return res;
 }

the function is slightly different 功能略有不同

  public static int mul(int[] a, int []b) { int res=0, resrow, i, j; for (i=0 ; i<a.length ; i++) { for (resrow=j=0 ; j<b.length ; j++) { resrow = resrow * 10 + a[i] * b[j]; } res = res * 10 + resrow; } return res; } 


Call like this 像这样打电话

  public static void main(String[] args) { int a[] = {3,4,5,6}; int b[] = {1,2}; int r = mul(a,b); out.println(r); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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