|
-
Apr 15th, 2006, 05:22 PM
#1
Thread Starter
Arabic Poster
[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:
Function nnn(N as Integer) As Integer
If N>1 Then
Return nnn(N-1)+nnn(N-2);
Else
Return 1;
End If
End Function
"I'm not normally a praying man, but if you're up there, save me... Superman!" - Homer Simpson
My Blog
-
May 4th, 2006, 06:13 AM
#2
Addicted Member
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
-
May 4th, 2006, 06:30 AM
#3
Addicted Member
Re: Remove recursion
Whoops! didn't test far enough - that only works for values up to 3 
looking......
-
May 4th, 2006, 06:43 AM
#4
Addicted Member
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 ... .
-
May 4th, 2006, 08:23 AM
#5
Addicted Member
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;
-
May 5th, 2006, 04:23 AM
#6
Addicted Member
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|