Find largest fib less than..

Back to topics list To post a new topic, please log in or register
avatar
8
nycraja 2016.07.07 02:50
 

I am trying to find the largest fib number less than a given input.  I know that a number is a fib number if (5 * n^2 + 4) or (5 * n^2 - 4) is a square number.  Here is the function I am trying but it doesn't seem to work for me.  Can someone more experienced please take a look?

 Thank you. 

 

double isfib (double fibo)
{
for (double n=fibo-1; n>0; n--) 
{
double exp=MathPow(n,2);
double plus = 5*exp+4;
double minus = 5*exp-4;
double plusrt = MathSqrt(plus);
double minusrt=MathSqrt(minus);
double plusrmdr = MathMod(plus,plusrt);
double minusrmdr = MathMod(minus,minusrt);
if (plusrmdr ==0 || minusrmdr ==0) return n;
else return(0);
}
}

 


avatar
8
nycraja 2016.07.07 03:12 #
 
nycraja:

I am trying to find the largest fib number less than a given input.  I know that a number is a fib number if (5 * n^2 + 4) or (5 * n^2 - 4) is a square number.  Here is the function I am trying but it doesn't seem to work for me.  Can someone more experienced please take a look?

 Thank you. 

 

 


Got it.

double isfib (double fibo)
{
for (double n=fibo-1; n>0; n--) 
{
double expt=MathPow(n,2);
double plus = 5*expt+4;
double minus = 5*expt-4;
double plusrt = MathSqrt(plus);
double minusrt=MathSqrt(minus);
double plusrmdr = MathMod(plus,plusrt);
double minusrmdr = MathMod(minus,minusrt);
if (plusrmdr ==0 || minusrmdr ==0)
break;
}
return(n);
}

 

avatar
13009
WHRoeder 2016.07.07 19:24 #
 
nycraja: I am trying to find the largest fib number less than a given input.  I know that a number is a fib number if (5 * n^2 + 4) or (5 * n^2 - 4) is a square number.
Why not just create them and stop when you get one too large?
int fib(int n){
   int prev=0, next = 1;
   while(next <= n){ 
      int old = prev; 
      prev = next; 
      next = old + prev; // 1, 2, 3, 5
   }
   return prev;
}

Back to topics list  

To add comments, please log in or register