Cassini’s Identity
Last Updated :
15 Sep, 2023
Given a number N, the task is to evaluate below expression. Expected time complexity is O(1).
f(n-1)*f(n+1) - f(n)*f(n)
Where f(n) is the n-th Fibonacci number with n >= 1. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, ………..i.e. (considering 0 as 0th Fibonacci number) Examples :
Input : n = 5
Output : -1
f(5-1=4) = 3
f(5+1=6) = 8
f(5)*f(5)= 5*5 = 25
f(4)*f(6)- f(5)*f(5)= 24-25= -1
Although the task is simple i.e. find n-1th, nth and (n+1)-th Fibonacci numbers. Evaluate the expression and display the result. But this can be done in O(1) time using Cassini’s Identity which states that:
f(n-1)*f(n+1) - f(n*n) = (-1)^n
So, we don’t need to calculate any Fibonacci term,the only thing is to check whether n is even or odd. How does above formula work? The formula is based on matrix representation of Fibonacci numbers.
C/C++
C++
#include <bits/stdc++.h>
using namespace std;
int cassini( int n) { return (n & 1) != 0 ? -1 : 1; }
int main()
{
int n = 5;
cout << (cassini(n));
return 0;
}
|
Java
class Gfg
{
static int cassini( int n)
{
return (n & 1 ) != 0 ? - 1 : 1 ;
}
public static void main(String args[])
{
int n = 5 ;
System.out.println(cassini(n));
}
}
|
Python3
def cassini(n):
return - 1 if (n & 1 ) else 1
n = 5
print (cassini(n))
|
C#
using System;
class GFG {
static int cassini( int n)
{
return (n & 1) != 0 ? -1 : 1;
}
public static void Main()
{
int n = 5;
Console.Write(cassini(n));
}
}
|
PHP
<?php
function cassini( $n )
{
return ( $n & 1) ? -1 : 1;
}
$n = 5;
echo (cassini( $n ));
?>
|
JavaScript
<script>
function cassini(n)
{
return (n & 1) ? -1 : 1;
}
let n = 5;
document.write(cassini(n));
</script>
|
Output :
-1
Time complexity: O(1) since only constant operations are performed
Auxiliary Space: O(1)
Reference : https://en.wikipedia.org/wiki/Cassini_and_Catalan_identities
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...