/** * 递归算法 */ @Test public void recursion() { System.out.println(factorial(2)); } /** * 递归算法计算阶乘n! * * @param n * @return */ public static Integer factorial(Integer n) { if (n < 0) return 0; if (n == 1) return 1; return n * factorial(n - 1); }
2、递归计算1*2+2*3+3*4+...+n*(n+1)
/** * 递归算法 */ @Test public void recursion() { System.out.println(productSum(4)); } /** * 递归算法计算1*2+2*3+3*4+...+n*(n+1) * @param n * @return */ public static Integer productSum(Integer n) { if (n <= 0) return 0; if (n == 1) return 2; int result = productSum(n - 1) + n * (n + 1); return result; }
/** * 递归算法 */ @Test public void recursion() { System.out.println(productSum(4)); } /** * 递归算法计算1*2+2*3+3*4+...+n*(n+1) * @param n * @return */ public static Integer productSum(Integer n) { if (n <= 0) return 0; if (n == 1) return 2; int result = productSum(n - 1) + n * (n + 1); return result; }