/** Functions from second Recursion lecture */ public class MoreRecursion { /** Yields: s, with commas every 3 digits. * Precondition: s represents an integer n >= 0. * e.g. commafy("5341267") = �5,341,267� */ public static String commafy(String s) { if (s.length() <= 3) { return s; } // String has more than 3 digits return commafy(s.substring(0,s.length()-3)) + "," + s.substring(s.length()-3); } /** Yields: n, with commas every 3 digits. * Precondition: n >= 0. * e.g. commafy(5341267) = �5,341,267� */ public static String commafy(int n) { //return commafy(""+n); if (n < 1000) { return "" + n; } // n >= 1000 return commafy(n/1000) + "," + to3(n%1000); } /** Yields: p with at least 3 chars * Adds leading 0's if necessary */ public static String to3(int p) { if (p < 10) { return "00" + p; } if (p < 100) { return "0" + p; } return "" + p; } // Number of frames used in exp recursive calls public static int countFrames = 0; /** Yields: b^c. Precondition: c � 0 * Property: b^c = b * b^(c-1)*/ public static double expSlow(double b, int c) { if (c == 0) { return 1; } // Used to count the number of frames countFrames = countFrames+1; // c > 0 return b * expSlow(b, c-1); } /** Yields: b^c. Precondition: c � 0 * Property: b^c = b^^(c/2) * b^(c-c/2)*/ public static double expAlternate(double b, int c) { if (c == 0) { return 1; } // Used to count the number of frames countFrames = countFrames+1; // c > 0 return expAlternate(b, c/2)*expAlternate(b,c-c/2); } /** Yields: b^c. Precondition: c � 0 * Property. b^c = b * b^(c-1) * Property. b^c = (b*b)^(c/2) for even c*/ public static double expFast(double b, int c) { if (c == 0) { return 1; } // Used to count the number of frames countFrames = countFrames+1; // c > 0 if (c % 2 == 0) { return expFast(b*b, c/2); } return b * expFast(b, c-1); } }