Java递归算法
2018-07-20 来源:open-open
递归算法 其实就是程序的自身调用。在做递归算法的时候,必须要有一个明确的递归结束条件,
当满足了这个条件的时候就不再递归了。
下面用Java实现两个基础的递归算法
/**
* 求1+2+3+...+n的和
*/
class Recurrent {
int sum = 0;
int flag = 1;
public void count(int number) {
sum += flag;
flag++;
if (flag <= number) {
count(number);
}
}
}
public class T {
public static void main(String[] args) {
Recurrent r = new Recurrent();
r.count(5);
System.out.println(r.sum);
}
}
/**
* 求n的阶乘
*/
class Factorial {
public long mul(int n) {
if (n <= 1) {
return 1;
} else {
return n * mul(n - 1);
}
}
}
public class T {
public static void main(String[] args) {
Factorial fac = new Factorial();
System.out.println(fac.mul(15));
}
}
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。
最新资讯
热门推荐