# Thread: Ternary nesting -- bad idea?

1. ## 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.

2. 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);
}```

3. looks like crap

4. 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;

partone=1/sqrt(5.0);

parttwo=0.5*(1+sqrt(5.0));

partthree=pow(parttwo,n);
int var;
{
var=1;
}
{
var=2;
}
{
var=3;
}
{
var=4;
}
{
var=5;
}

}```

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

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

Popular pages Recent additions