function isPerfectSquare(num)
{
let n = parseInt(Math.sqrt(num));
return (n * n == num);
}
// Function to check
// if the number is
// in Fibonacci or not
function checkFib(array, n)
{
let count = 0;
for (let i = 0; i < n; i++)
{
if (isPerfectSquare(5 * array[i] *
array[i] + 4) ||
isPerfectSquare(5 * array[i] *
array[i] - 4))
{
console.log(array[i] + " ");
count++;
}
}
if (count == 0)
console.log("None present + <br>");
}
// Driver Code
let array = [15, 1, ,3];
let n = array.length;
checkFib(array, n);
that is function to check nearest fibonaci how to get the output
Question : with Array [ 15, 1, 3 ] Expected Output is 2 because nearest fibonacci of 19 is 21 = 2
Thank u for help. :)
Your code checks Fibonacci numbers in an array and outputs them. To check nearest Fibonacci, you need a number, why array? Are you summing numbers in array? If yes, then:
First, add array[i] as sum = sum + array[i]
Then, call NearestFibonacci (sum)
where,
NearestFibonacci (int sum){
if (sum == 0) {
cout << 0;
return;
}
int first = 0, mid = 1;
int last = first + mid;
while (last <= sum) {
first = mid;
mid=last;
last = first + mid;
}
int ans = min(last - sum, sum - mid);
cout << ans;
}