I wrote the following three functions. They're doing addition and multiplication "by hand". However, I can't get the third one to work properly, because I'm not sure how to go about adding the 0's for additional multiplications.
Code:
Any help would be appreciated.Code:public static int[] ppAdd (int[] a, int[] b) { // Store the length of the largest array: int iLen = (a.length > b.length) ? a.length : b.length; // Create the sum array (largest array length + 1): int[] sum = new int [iLen + 1]; int iRes = 0, iCarry = 0; for (int i = 0; i < iLen; i++) { int a_curr = (a.length - 1) - i; int b_curr = (b.length - 1) - i; if (a_curr < 0) { iRes = b[b_curr] + iCarry; } else if (b_curr < 0) { iRes = a[a_curr] + iCarry; } else { iRes = a[a_curr] + b[b_curr] + iCarry; } iCarry = 0; if (iRes > 9) { iCarry = 1; iRes = iRes - 10; } sum[iLen - i] = iRes; } return sum; } public static int[] ppMult (int[] mltp, int d) { int[] prod = new int[mltp.length + 1]; int iRes = 0, iCarry = 0; // Loop the mltp array backwards: for (int i = (mltp.length - 1); i >= 0; i--) { // Multiply the current index by d: iRes = mltp[i] * d + iCarry; // Grab the 1's spot: prod[i + 1] = iRes % 10; // Carry the 10's spot: iCarry = iRes / 10; } // Set the first value as the last carried value: prod[0] = iCarry; return prod; } public static int[] ppMultMM (int[] a, int[] b) { // If needed, we're going to switch a and b // so that the top is always the largest // number. This makes computation below much easier: if (b.length > a.length) { int[] tmp = a; a = b; b = tmp; } int[] prod = new int[a.length + b.length]; int[][] rows = new int[b.length][a.length + b.length]; for (int i = (b.length - 1); i >= 0; i--) { rows[i] = ppMult(a, b[i]); } // Loop the rows and add them together: for (int i = 0; i < rows.length; i++) { prod = ppAdd(rows[i], prod); } return prod; }




Reply With Quote