一:递归调用构造方法求1到100的和
/**
* 递归调用构造方法求1到100的和
* @author Administrator
*
*/
public class sumExceptionConstructor {
public static int n;
public static int[] array;
public sumExceptionConstructor(int i) {
try {
array[i] = array[i-1] + i;
new sumExceptionConstructor(i+1);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println(array[n]);
return;
}
}
}
二:递归调用sumExceptionMethod方法求1到100的和
/**
* 递归调用sumExceptionMethod方法求1到100的和
* @author Administrator
*
*/
public class sumExceptionMethod {
private int n;
private int[] array;
public sumExceptionMethod(int n) {
super();
this.n = n;
array = new int[n+1];
}
public int sumMethod(int i){
try {
array[i] = array[i-1] + i;
int k = sumMethod(i+1);
return k;
} catch (ArrayIndexOutOfBoundsException e) {
return array[n];
}
}
}
三:递归、非递归、以及等差数列
int total = 0;
public int addtion_0(int n) {
for (int i = 0; i <= n; i++) {
total += i;
}
return total;
}
public int addtion(int n) {
if (n == 1)
return 1;
else {
return total = total + n + addtion(n - 1);
}
}
public int addtion02(int n) {
return n * (1 + n) / 2;
}