Morgan Stanley Interview Question
Software Engineer / DevelopersHere is one written in Java,
public static boolean checkFibonacci (int array[])
{
for (int i=0; i < array.length/2; i++)
{
if(array[i] + array[i+1] ! = array [i+2])
{
return false;
}
}
if( array.length % 2 !=0 )
{
if (array[length -1] != array[length -2] + array[length -3])
{
return false;
}
}
return true;
}
this doesnt check if the first two digits are part of a fib sequence
I would think you have to start from 1 computing till you got to the first value first and check those values if you never reach a value greater then the first value w/o reaching the first value return false else compute like above.
this doesnt check if the first two digits are part of a fib sequence
I would think you have to start from 1 computing till you got to the first value first and check those values if you never reach a value greater then the first value w/o reaching the first value return false else compute like above.
public class isFibonacci{
public static void main(String args[]){
//int [] arr = {1,1,2,3,5,8,13,21,34,55,89,144};
int [] arr = {1,1,2,3,5,8,13,21,34,55,89,144};
int sum=0;
int i=1;
boolean flag = false;
while(i<arr.length-1){
sum =arr[i]+arr[i-1];
if(sum!=arr[i+1]){
flag=false;
System.out.println("Not a fibonacci sequence.");
break;
}
i++;
flag = true;
}
if(flag) System.out.println("A valid fiboncaai sequence.");
}
}
class FibonacciChecker {
/**
* @param args
*/
public static void main(String[] args) {
int[] data={1,1,2,3,5,8,13};
System.out.println("isFib : "+isFibonacci(data));
}
public static boolean isFibonacci(int[] data)
{
for(int i=2;i<data.length;i++)
{
int sum=data[i-2]+data[i-1];
if(sum!=data[i])
return false;
}
return true;
}
}
class FibonacciChecker {
/**
* @param args
*/
public static void main(String[] args) {
int[] data={1,4,5,9};
System.out.println("isFibonacci : "+isFibonacci(data));
}
private static boolean isFibonacci(int[] data)
{
if(data.length<2)
return false;
if(!checkForStartingNumbers(data[0])||!checkForStartingNumbers(data[1]))
return false;
for(int i=2;i<data.length;i++)
{
int sum=data[i-2]+data[i-1];
if(sum!=data[i])
return false;
}
return true;
}
private static boolean checkForStartingNumbers(int number)
{
int n=5*number*number+4;
int n1=5*number*number-4;
int sqrt1st=(int)Math.sqrt(n);
int sqrt2nd=(int)Math.sqrt(n1);
if(n==sqrt1st*sqrt1st||n1==sqrt2nd*sqrt2nd)
return true;
return false;
}
Check whether the given array follows the Fibonacci property.
- AP March 07, 2008eg if we are given 23,34,56,....
we know it cant be in Fibo seq as 23+34!=56
In case the given numbers follow the property
we can use the definition of Fibo seq..
F(n+1)=F(n)+F(n-1)
=> F(n-1) = F(n+1) - F(n)
in this if we go down then we should get 2,1,0 as last (+) nums.
eg for 23,34,57,....
other nums 'ld be 11,12,-1
so not in Fibo