Results 1 to 6 of 6

Thread: [RESOLVED] Remove recursion

  1. #1

    Thread Starter
    Arabic Poster ComputerJy's Avatar
    Join Date
    Nov 2005
    Location
    Happily misplaced
    Posts
    2,513

    Resolved [RESOLVED] Remove recursion

    Hi all
    I need help converting this recursive function to non-recursive


    Code:
    int nnn(int n){
    	if(n>1){
    		return nnn(n-1)+nnn(n-2);
    	}else{
    		return 1;
    	}
    }
    VB Code:
    1. Function nnn(N as Integer) As Integer
    2.     If N>1 Then
    3.         Return nnn(N-1)+nnn(N-2);
    4.     Else
    5.         Return 1;
    6.     End If
    7. End Function
    "I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
    My Blog

  2. #2
    Addicted Member
    Join Date
    Feb 2001
    Posts
    198

    Re: Remove recursion

    Surprised to see this still open, here's my guess:
    It looks like for any positive value of N, nnn(N) will return N.
    For any value of N less than 1, nnn(N) will return 1.
    Very simplified would be:
    Function nnn(N as Integer) As Integer
    If N>1 Then 'N is an integer value so >0 is 1 or more
    Return N;
    Else
    Return 1;
    End If
    End Function

  3. #3
    Addicted Member
    Join Date
    Feb 2001
    Posts
    198

    Re: Remove recursion

    Whoops! didn't test far enough - that only works for values up to 3
    looking......

  4. #4
    Addicted Member
    Join Date
    Feb 2001
    Posts
    198

    Re: Remove recursion

    There is a formula on here, and a working example (they say). It does look better as a recursive.

    http://www.mcs.surrey.ac.uk/Personal...ibFormula.html


    nnn(N) = (Phi^N – (–Phi)^–N)/sqrt(5)

    where Phi = 1·61803 39887 49894 84820 45868 34365 63811 77203 09179 80576 ... .

  5. #5
    Addicted Member
    Join Date
    Feb 2001
    Posts
    198

    Re: Remove recursion

    not quite vb, but I expect you can understand this:
    stolen from the page I referenced, and I've removed the warnings and overflow checks for clarity - it's close but lacks accuracy and best not call it with N=2.

    function nnn(N number)return number
    is
    i number;
    p1 number;
    p2 number;
    begin
    i:=N;
    p1:=power((sqrt(5)+1)/2,i)/sqrt(5);
    p2=-power((-sqrt(5)+1)/2,i)/sqrt(5);
    return trunc(p1+p2);
    end;

  6. #6
    Addicted Member
    Join Date
    Feb 2001
    Posts
    198

    Re: [RESOLVED] Remove recursion

    I think the environment I was testing in was causing the inaccuracies I experienced, this seems fine in excel (paste into b1 and add N into a1):

    =POWER((SQRT(5)+1)/2,A1)/SQRT(5)-POWER((-SQRT(5)+1)/2,A1)/SQRT(5)

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