packagecom.luna.base;publicclassBirthRabbit{publicstaticvoidmain(String[] args){int i =1;for(i =1; i <=20; i++){System.out.println("兔子第"+ i +"个月的总数为:"+f(i));}}publicstaticintf(int x){if(x ==1|| x ==2){return1;}else{returnf(x -1)+f(x -2);}}}
packagecom.luna.base;publicclassPlus{publicintsum(int i){if(i ==1){return1;}return i +sum(i -1);}publicstaticvoidmain(String[] args){Plus plus =newPlus();System.out.println("计算结果:"+ plus.sum(100)+"!");}}
3.100的阶乘
packagecom.luna.base;importjava.math.BigInteger;publicclassLoopMutiply{publicBigIntegersum(int i){if(i ==1){returnBigInteger.ONE;}returnBigInteger.valueOf(i).multiply(sum(i -1));}publicstaticvoidmain(String[] args){LoopMutiply test =newLoopMutiply();try{System.out.println("计算结果:"+ test.sum(50)+"!");}catch(Exception e){
e.printStackTrace();}}}
4.有序数组a、b合并成一个新的有序数组
packagecom.luna.base;publicclassArraySort{publicstaticvoidmain(String[] args){int[] a ={1,3,4};int[] b ={2,3,5,6};int[] c =mergeArray(a, b);for(int n : c){System.out.print(n +" ");}}// 合并数组publicstaticint[]mergeArray(int[] a,int[] b){int result[]=newint[a.length + b.length];if(checkSort(a)&&checkSort(b)){// 说明ab数组都是有序的数组// 定义两个游标int i =0, j =0, k =0;while(i < a.length && j < b.length){if(a[i]<= b[j]){
result[k++]= a[i++];}else{
result[k++]= b[j++];}}while(i < a.length){// 说明a数组还有剩余
result[k++]= a[i++];}while(j < b.length){
result[k++]= b[j++];}}return result;}// 检查一个数组是否是有序1 2 3publicstaticbooleancheckSort(int[] a){boolean flag =false;// 默认不是有序的for(int i =0; i < a.length -1; i++){if(a[i]> a[i +1]){// 说明不是有序的
flag =false;break;}else{
flag =true;}}return flag;}}
5.归并排序算法实现
packagecom.luna.base;publicclassMergingSort{publicstaticvoidsort(int[] data,int left,int right){if(left < right){// 首先找出中间的索引 int center =(left + right)/2;// 对中间索引左边的数组进行递归 sort(data, left, center);// 对中间索引右边的数组进行递归 sort(data, center +1, right);// 合并 merge(data, left, center, right);}}publicstaticvoidmerge(int[] data,int left,int center,int right){int[] tmpArr =newint[data.length];int mid = center +1;// third记录中间数组的索引 int third = left;int tmp = left;while(left <= center && mid <= right){// 将两个数组中取出最小的数放入中间数组 if(data[left]<= data[mid]){
tmpArr[third++]= data[left++];}else{
tmpArr[third++]= data[mid++];}}// 剩余部分依次放入中间数组 while(mid <= right){
tmpArr[third++]= data[mid++];}while(left <= center){
tmpArr[third++]= data[left++];}while(tmp <= right){
data[tmp]= tmpArr[tmp++];}}publicstaticvoidmain(String[] args){int[] a ={3,2,5,4};sort(a,0, a.length -1);for(int i =0; i < a.length; i++){System.out.print(a[i]+" ");}}}