I present here a recursive algorithm in java to check if a number is in the fibonacci sequence or not.

In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones : 0-1-1-2-3-5-8-13-21-34.....

for that I developed those two functions:

download the source project here

In mathematics, the Fibonacci numbers are the numbers in the following integer sequence, called the Fibonacci sequence, and characterized by the fact that every number after the first two is the sum of the two preceding ones : 0-1-1-2-3-5-8-13-21-34.....

for that I developed those two functions:

```
public static boolean checkNumber(int number,int precedentOne, int precedentTwo){
if ( number == precedentOne + precedentTwo)
return true;
else if( number < (precedentOne + precedentTwo) )
return false;
else
return checkNumber(number,precedentTwo,precedentOne+precedentTwo);
}
```

this function takes 3 parameters, the number and the two precedent numbers in the fibonacci sequence. here we have 3 possible cases : - the sum of precedent numbers is equal to the number and that means the number is a fibonacci number.
- the sum of precedent numbers is greater than the number and that means the number is not in the fibonacci sequence.
- the sum of precedent numbers is less than the number so we need to go one step further by passing the sum of the two precedent numbers as the second precedent and precedentTwo as precedentOne.

```
public static boolean isInFibonacci(int number){
if(number == 0 )
return true;
return checkNumber(number,1,1);
}
```

This function starts first by checking if the number is equals to 0 then it will return true, otherwise it returns the check function download the source project here

Jun. 18 2017

Be the first one to leave a comment