递归算法(1)

  1. /**  
  2.  *  
  3.  * @author SunnyMoon  
  4.  */  
  5.   
  6.   
  7. /**  
  8.  * 概念介绍:  
  9.  * 递归是一种方法(函数)调用自已编程技术。  
  10.  * 递归就是程序设计中的数学归纳法。  
  11.  * 例如:tri(n)=1            if n=1  
  12.  *     tri(n)=n+tri(n-1)    if n>1  
  13.  * 可能while循环方法执行的速度比递归方法快,但是为什么采用递归呢。  
  14.  * 采用递归,是因为它从概念上简化了问题,而不是因为它提高效率。  
  15.  */  
  16.   
  17. import java.io.BufferedReader;   
  18. import java.io.IOException;   
  19. import java.io.InputStreamReader;   
  20.   
  21.   
  22. public class Recursion {//求三角数字的递归算法:1,3,6,10,15,21, ......   
  23.   
  24.     static int theNumber;   
  25.   
  26.     public static void main(String[] args) throws IOException {   
  27.         System.out.print("Enter a number: ");   
  28.         theNumber = getInt();   
  29.         //使用递归时调用,默认   
  30.         int theAnswer = triangle(theNumber);   
  31.         //使用非递归时调用   
  32.         //int theAnswer=triangle2(theNumber);   
  33.         System.out.println("Result: " + theAnswer);   
  34.     }   
  35.   
  36.     public static int triangle(int n) {//递归方法,循环调用   
  37.         if (n == 1) {   
  38.             return 1;   
  39.         } else {   
  40.             return (n + triangle(n - 1));   
  41.         }   
  42.     }   
  43.   
  44.     public static int triangle2(int n) {//非递归方法   
  45.         int total = 0;   
  46.         while (n > 0) {   
  47.             total = total + n--;   
  48.         }   
  49.         return total;   
  50.     }   
  51.   
  52.     public static String getString() throws IOException {   
  53.         InputStreamReader isr = new InputStreamReader(System.in);   
  54.         BufferedReader br = new BufferedReader(isr);   
  55.         String s = br.readLine();   
  56.         return s;   
  57.     }   
  58.   
  59.     public static int getInt() throws IOException {   
  60.         String s = getString();   
  61.         return Integer.parseInt(s);   
  62.     }   
  63. }   
  64.   
  65. /**  
  66.  * 运行结果:  
  67.  * Enter a number:   
  68.  * 3  
  69.  * Result: 6  
  70.  */  
  71.   
  72. /**  
  73.  * 总结:  
  74.  * 使用非递归的方式更简洁,更易懂,运行效率更高,为什么还要用递归的算法呢。  
  75.  * 递归使规模逐渐降低的方式解决问题,以这种统一的方式解决足够复杂的问题。  
  76.  */  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值