CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 16

Threaded View

  1. #11
    Join Date
    Feb 2009
    Posts
    32

    Re: need help with loops plz

    Quote Originally Posted by ProgramThis View Post
    The method you have is about as simple and as elegant as it gets.
    Inefficiency isn't elegant.

    Don't use recursion for the Fibonacci sequence. It's running time is exponential --(3/2)^N. Every CS book that has a chapter on algorithmic analysis tells you this.
    Code:
    public class Test {
    	private final static int N = 40;
    	public static void main(String[] args) {
    		long start = System.currentTimeMillis();
    		int a = 0, b = 1, c = 1;
    		for (int i = 4; i <= N; i++) {	// i = 4 -> 5 -> 6 -> 7 ...
    			a = b;			// a = 1    1    2    3
    			b = c;			// b = 1    2    3    5
    			c = a + b;		// c = 2    3    5    8
    		}
    		long end = System.currentTimeMillis();
    		
    		System.out.println("f_" + N + " = " + c + " and iteratively took " +
    			(end - start) + " milliseconds.");
    		
    		
    		start = System.currentTimeMillis();
    		c = fib(N);
    		end = System.currentTimeMillis();
    		
    		System.out.print("f_" + N + " = " + c + " and recursively took " +
    			(end - start) + " milliseconds.");
    	}
    	private static int fib(int n) {
    		if (n <= 3)
    			return 1;
    		return fib(n - 1) + fib (n - 2);
    	}
    }
    Output:
    Code:
    f_30 = 514229 and iteratively took 0 milliseconds.
    f_30 = 514229 and recursively took 16 milliseconds.
    
    f_40 = 63245986 and iteratively took 0 milliseconds.
    f_40 = 63245986 and recursively took 672 milliseconds.
    
    f_50 = -811192543 and iteratively took 0 milliseconds.     (longs obv. don't work well with big N)
    f_50 = -811192543 and recursively took 77359 milliseconds. (1 minute 17.359 seconds...)
    Last edited by Nim; September 25th, 2009 at 11:38 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured