0
点赞
收藏
分享

微信扫一扫

Java数据结构之递归与三角函数的运用,使用3种方法实现三角


package com.struct.recusion;

/**
* @描述 递归与三角函数的运用
* @项目名称 Java_DataStruct
* @包名 com.struct.recusion
* @类名 Recusion
* @author chenlin
* @date 2010年6月28日 下午8:19:40
* @version 1.0
*/

public class Recusion {

/**
* 递归
* @param n
*/
public static void test(int n){
if (n == 0) {
return;
}
System.out.println(n);
test(--n);
System.out.println(n);
}

/**
* 三角 ,求第n项的数
* 1 3 6 10 15
* 3=1+2
* 6=3+3
* 10=6+4;
*/
public static void triangle(int n){
int count = 0;
for (int i = 1; i <= n; i++) {
count += i;
}

System.out.println(count);
}

/**
* 三角 ,求第n项的数
* 1 3 6 10 15
* 3=1+2
* 6=3+3
* 10=6+4;
*/
public static void triangle3(int n){
int count = 0;
while(n > 0){
count += n;
n--;
}

System.out.println(count);
}

/**
* 三角 ,求第n项的数
* 1 3 6 10 15
* 3=1+2
* 6=3+3
* 10=6+4;
*/
public static int triangle2(int n){
if (n <=0) {
throw new RuntimeException("不能小于0");
}
if (n == 1) {
return 1;
}else {
return triangle2(n-1) + n;
}
}

public static void main(String[] args) {
//test(6);
triangle(4);
System.out.println(triangle2(4));
}

}

举报

相关推荐

0 条评论