使用陣列進行大資料運算

丶Pz發表於2018-01-22

這裡的大資料不是網際網路上的大資料,而是指 比 long.maxValue還要大的數,因為基本型別已經滿足不了大資料的計算。所以一般方法是採用陣列。

 

下面是我自己的實現程式碼:

   /**
     * 兩個陣列進行計算
     * */
    public static int[] calculate(int[] value1,int[] value2){

        //存放每次迴圈乘的結果
        int tempLength = value1.length * 2 -1;
        int[][] temp = new int[value1.length][tempLength];
        //第一步,迴圈遍歷第一個,依次乘以 value2的值,然後要留空位
        for (int i=value1.length -1;i>=0;i--){
            int[] tempValue = new int[tempLength];
            //預留幾個 0
            int zeroLength = value1.length-1-i;
            //賦值
            for (int j= value2.length-1;j>=0;j--){
                int index = tempLength - zeroLength - (value2.length-j);
                tempValue[index] = value1[i] * value2[j];
            }
            temp[i] = tempValue;
        }

        //陣列對應的每個值想加,行成一個新陣列
        int[] sumArr = new int[tempLength];
        for (int i=0;i<temp.length;i++){
            for (int j=0;j<temp[i].length;j++){
                sumArr[j]+= temp[i][j];
            }
        }

        for (int i=sumArr.length-1;i>0;i--){
            sumArr[i-1] += sumArr[i] / 10;
            sumArr[i] = sumArr[i] % 10;//取餘數
        }
        return sumArr;
    }

 

相關文章