# Ternary nesting -- bad idea?

• 04-12-2005
CodeMonkey
Ternary nesting -- bad idea?
This functions returns the n-th number in the fibonacci sequence. Besides crappy readability, is there any reason for not doing it this way?
Code:

```long unsigned int fibby(int n, long unsigned int num1 = 0LU, long unsigned int num2 = 1LU, int count = 1); {   return (!n || n == 1) ? 0 : ((count < n) ? fibby(n, num2, num2 + num1, count + 1) : num2); }```
I've learned that the ternary can be very optimal, but does using it this way backfire that optimization? I don't think so, but tell we what you know. Just a thought.
• 04-13-2005
CodeMonkey
whoops -- it's (n - 1):
Code:

```long unsigned int fibby(int n, long unsigned int num1 = 0LU, long unsigned int num2 = 1LU, int count = 1); {   return (!n || n == 1) ? 0 : ((count < n - 1) ? fibby(n, num2, num2 + num1, count + 1) : num2); }```
• 04-14-2005
misplaced
looks like crap
• 04-14-2005
treenef
Quote:

looks like crap
lol

Try this, although this is more of a hack.

Code:

```/*   1/sqrt(5)  *  [1/2(1+sqrt(5)] ^n     Approximates the nth term of the fibby sequence   Works well when n >= 5 */ #include<iostream> #include<math.h> #include<iomanip> int fibby(int); using namespace std; int main() {     int enter;     cout<<"Enter the nth term for the fibby sequence.";     cout<<"Works well when n>=5:";     cin>>enter;         //call the function fibby pass in the variable 'enter'     fibby(enter);         int stop;     cin>>stop; }    //function declaration int fibby(int n) {     float partone;     float parttwo;     float partthree;     float answer;         partone=1/sqrt(5.0);         parttwo=0.5*(1+sqrt(5.0));         partthree=pow(parttwo,n);     answer=(partone*partthree);     int var;     if(answer<10)     {         var=1;     }     if((answer>=10)&&(answer<=100))     {         var=2;     }     if  ((answer>=100)&&(answer<=1000))     {            var=3;     }       if  ((answer>=1000)&&(answer<=10000))     {            var=4;     }     if  ((answer>=10000)&&(answer<=100000))     {            var=5;     }         cout<< setprecision(var)<<answer; }```

You can condense the set precision bit but I couldn't be bothered.

:confused:
• 04-14-2005
TheColonial

Code:

```unsigned long fib(int n, unsigned long current = 1, unsigned long prev = 0) {     return(n <= 1 ? current : fib(n - 1, prev + current, current)); } int main() {     for(int i = 1; i <= 20; i++)     {         std::cout << fib(i) << std::endl;     }     return(0); }```
I realise it doesn't answer your question, but I had fun ;)