The Fibonacci numbers are the numbers in the following integer sequence (Fn):
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...
such as
F(n) = F(n-1) + F(n-2) with F(0) = 0 and F(1) = 1.
Given a number, say prod (for product), we search two Fibonacci numbers F(n) and F(n+1) verifying
F(n) * F(n+1) = prod.
Your function productFib takes an integer (prod) and returns an array:
[F(n), F(n+1), true] or {F(n), F(n+1), 1} or (F(n), F(n+1), True)
depending on the language if F(n) * F(n+1) = prod.
If you don't find two consecutive F(m) verifying F(m) * F(m+1) = prod
you will return
[F(m), F(m+1), false] or {F(n), F(n+1), 0} or (F(n), F(n+1), False)
F(m) being the smallest one such as F(m) * F(m+1) > prod
.
productFib(714) # should return {21, 34, 1},
# since F(8) = 21, F(9) = 34 and 714 = 21 * 34
productFib(800) # should return {34, 55, 0},
# since F(8) = 21, F(9) = 34, F(10) = 55 and 21 * 34 < 800 < 34 * 55
Notes: Not useful here but we can tell how to choose the number n up to which to go: we can use the "golden ratio" phi which is (1 + sqrt(5))/2
knowing that F(n) is asymptotic to: phi^n / sqrt(5)
. That gives a possible upper bound to n.
You can see examples in "Example test".
http://en.wikipedia.org/wiki/Fibonacci_number
http://oeis.org/A000045
others:
public class ProdFib { // must be public for codewars
public static long[] productFib(long prod) {
long fibProd = 0;
int i = 1;
while (fibProd < prod) {
fibProd = fibNum(i) * fibNum(i + 1);
i++;
}
if (fibProd == prod) return new long[] {fibNum(i - 1),fibNum(i),1};
return new long[] {fibNum(i - 1),fibNum(i),0};
}
public static long fibNum(int n) {
double a = (Math.sqrt(5) + 1) / 2;
return (long) ((1 / Math.sqrt(5))*(Math.pow(a, n) + Math.pow(a-1, n)));
}
}
public class ProdFib { //SRY AMA BAD GUY :))))
static long[] mas={0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89,
144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711,
28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040,
1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817,
39088169, 63245986, 102334155, 165580141, 267914296, 433494437,
701408733, 1134903170,1836311903L,2971215073L};
public static long[] productFib(long prod) {
long[] result={0,0,0};
long buf;
for(int i=0;iprod){result[0]=mas[i];result[1]=mas[i+1];break;}
}
return result;
}
}
public class ProdFib { // must be public for codewars
public static long[] productFib(long prod) {
long a = 0L;
long b = 1L;
while (a * b < prod) {
long tmp = a;
a = b;
b = tmp + b;
}
return new long[] { a, b, a * b == prod ? 1 : 0 };
}
}
my:
public static long[] productFib(long prod) {
// your code
long [] out=new long[3];
long a=0;
long b=1;
while (prod>a*b)
{
long tmp=a+b;
a=b;
b=tmp;
System.out.println(a+";"+b);
}
out[0]=a;
out[1]=b;
out[2]=(a*b==prod)?1:0;
return out;
}