// ------------------------------------------------------- // StringMath // ------------------------------------------------------- public class StringMath { // ------------------------------------------------------- // add - Return (as a string) the result of // adding s1 and s2 // ------------------------------------------------------- public static String add(String s1, String s2) { while(s1.length() < s2.length()) s1 = "0" + s1; while(s2.length() < s1.length()) s2 = "0" + s2; int index = s1.length() - 1; String result = ""; int carry = 0; while(index >= 0) { char c1 = s1.charAt(index); char c2 = s2.charAt(index); int sum = carry + (c1 - '0') + (c2 - '0'); if(sum >= 10) { carry = 1; sum -= 10; } else carry = 0; result = (char)('0' + sum) + result; index--; } if(carry > 0) result = (char)('0' + carry) + result; return(result); } // ------------------------------------------------------- // multiply - Return (as a string) the result of // multiplying 's' by the supplied digit // ------------------------------------------------------- public static String multiply(String s, char digit) { String result = ""; int index = s.length() - 1; int carry = 0; while(index >= 0) { char c = s.charAt(index); int product = (digit - '0') * (c - '0') + carry; if(product >= 10) { carry = (product / 10); product %= 10; } else carry = 0; result = (char)('0' + product) + result; index--; } if(carry > 0) result = (char)('0' + carry) + result; return(result); } // ------------------------------------------------------- // multiply - Return (as a string) the result of // multiplying s1 and s2 // ------------------------------------------------------- public static String multiply(String s1, String s2) { String shorter = (s1.length() <= s2.length() ? s1 : s2); String longer = (s1.length() <= s2.length() ? s2 : s1); String result = ""; for(int i = shorter.length() - 1, j = 0; i >= 0; i--, j ++) { String product = multiply(longer, shorter.charAt(i)); for(int k = 0; k < j; k ++) product += "0"; result = add(result, product); } return(result); } // ------------------------------------------------------- // testAddition // ------------------------------------------------------- public static void testAddition() { final int MAX_POWER = 222; String value = "1"; for(int i = 0; i <= MAX_POWER; i ++, value = add(value, value)) System.out.printf("2^%d = %s\n", i, value); System.out.println(); } // ------------------------------------------------------- // testMultiplication // ------------------------------------------------------- public static void testMultiplication() { final int NUMBER = 1000; String value = "" + NUMBER; for(int i = NUMBER - 1; i > 1; i --) value = multiply(value, "" + i); System.out.printf("%d! = %s\n", NUMBER, value); } // ------------------------------------------------------- // main // ------------------------------------------------------- public static void main(String[] args) { testAddition(); testMultiplication(); } }