递归有好有坏的……

xiaoxiao2024-04-12  18

迭代和递归,各有各的好,在我看来,递归好了程序员,害了电脑,而迭代相反,他要求程序员为程序考虑的很多,运行起来就会好很多。 举个例子 斐波那契数吧 以下是分别用两者实现的。请比较 package chap18;import java.util.Scanner;//用递归法是实现的斐波那契数public class febo { /** * @param args */ public static void main(String[] args) { while(true) { System.out.println("请输入你要计算的那项"); Scanner cin = new Scanner(System.in); int n = cin.nextInt(); MyTimer myTimer = new MyTimer(); myTimer.start(); System.out.println(feibo(n)); myTimer.end(); System.out.println("用时 "+myTimer.getUseTime()+"毫秒"); } } /* * 斐波那契方法 * @param n 要求的那项位置 * @return 结果 */ public static int feibo(int n) { if(n <= 2) return 1; else { return feibo(n-1)+feibo(n-2); } }} 运行结果: 请输入你要计算的那项 40 102334155 用时 1500毫秒 请输入你要计算的那项 package chap18;import java.util.Scanner;/* * 采用迭代方法解决的斐波那契数列 */public class feibo1 { /** * @param args */ public static void main(String[] args) { while(true) { System.out.println("请输入你要计算的那项"); Scanner cin = new Scanner(System.in); int n = cin.nextInt(); MyTimer myTimer = new MyTimer(); myTimer.start(); System.out.println(feibo(n)); myTimer.end(); System.out.println("用时 "+myTimer.getUseTime()+"毫秒"); } } /* * 斐波那契方法 采用迭代方法解决 * @param n 要求的那项位置 * @return 结果 */ public static int feibo(int n) { int start1 = 1; int start2 = 1; for(int i = 2; i < n; i++) { int temp = start1+start2; start1 = start2; start2 = temp; } return start2; }} 运行结果: 请输入你要计算的那项 40 102334155 用时 0毫秒 请输入你要计算的那项 还有啊,开个玩笑,如果把n取到50(不用很大,50足矣),用第一种,只有指望intel产个四核了……
转载请注明原文地址: https://www.6miu.com/read-5014921.html

最新回复(0)