SlideShare a Scribd company logo
1
Fibonacci using recursive squaring
The naive bottom-up algorithm to compute the nth 󰅬ibonacci number take linear
time O(n). We can do better than linear time. One of the well-known properties
of 󰅬ibonacci numbers is :
Fn+1 Fn
Fn Fn−1
=
1 1
1 0
n
We can therefore compute the nth power of A = ((1, 1), (1, 0)) using recursive
squaring. That is, if n is even, we recursively compute An/2
. This sub-problem
takes T(n/2) time. Cache this result in a temp variable. The desired result is An
=
An/2
× An/2
. Since, we have already computed An/2
, it’s the same subproblem,
we don’t have to repeat this work. So, all we do is temp*temp. Multiplying two
2 × 2 matrices takes constant time - O(1). So, the total running time is T(n) =
T(n/2) + O(1) which has upper bound O(lg n).
Here’s the code snippet:
#include <iostream >
class matrix
{
int items[2][2];
public:
matrix();
matrix(const matrix& A);
matrix(int init_value);
matrix& operator = (const matrix& A);
matrix operator * (const matrix& A) const;
void print() const;
void set(int i, int j, int x);
matrix rec_power(int n);
};
int main()
{
matrix A;
matrix B = A.rec_power(5);
std::cout << "nA^5 = ";
B.print();
std::cin.clear();
2
std::cin.get();
return 0;
}
matrix::matrix()
{
items[0][0] = items[1][0] = items[0][1] = 1;
items[1][1] = 0;
}
matrix::matrix(const matrix& A)
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
items[i][j] = A.items[i][j];
}
matrix::matrix(int init_value)
{
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
items[i][j] = init_value;
}
matrix& matrix::operator = (const matrix& A)
{
if (this == &A)
return *this;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
items[i][j] = A.items[i][j];
return *this;
}
matrix matrix::operator * (const matrix& A) const
{
matrix temp(0);
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
temp.items[i][j] += items[i][k] * A.items[k][j];
3
}
}
}
return temp;
}
void matrix::print() const
{
std::cout << "n(" << items[0][0] << "," << items[0][1]
<< ")";
std::cout << "n(" << items[1][0] << "," << items[1][1]
<< ")";
}
void matrix::set(int i, int j, int x)
{
items[i][j] = x;
}
matrix matrix::rec_power(int n)
{
if (n == 0)
{
matrix temp;
temp.items[0][0] = temp.items[1][1] = 1;
temp.items[0][1] = temp.items[1][0] = 0;
return temp;
}
if (n == 1)
{
return *this;
}
else
{
if (n % 2 == 0)
{
matrix temp = rec_power(n / 2);
return temp * temp;
}
else
{
matrix temp = rec_power((n - 1) / 2);
return temp * temp * (*this);
}
}
4
}
Listing 1: RecursiveSquaring.cpp

More Related Content

PPTX
Merge sort algorithm
PPTX
Tower Of Hanoi
PPTX
Lecture 17 Iterative Deepening a star algorithm
PPTX
Search Algorithms in AI.pptx
PPTX
Space complexity-DAA.pptx
PPTX
Knapsack Problem
DOC
Branch and bound
PPT
Lower bound
Merge sort algorithm
Tower Of Hanoi
Lecture 17 Iterative Deepening a star algorithm
Search Algorithms in AI.pptx
Space complexity-DAA.pptx
Knapsack Problem
Branch and bound
Lower bound

What's hot (20)

PPT
Asymptotic notations
PPT
1.prallelism
PPTX
Best First Search.pptx
PPTX
tic-tac-toe: Game playing
PPTX
LM7_ Embedded Sql and Dynamic SQL in dbms
PPTX
Depth first search [dfs]
PPTX
Unit-III-AI Search Techniques and solution's
PPTX
sum of subset problem using Backtracking
PPT
Sorting in Linear Time in Analysis & Design of Algorithm
PPTX
Graph in data structure
PPTX
1.7. eqivalence of nfa and dfa
PDF
13 Amortized Analysis
PDF
I.BEST FIRST SEARCH IN AI
PPTX
Breadth first search (bfs)
PPTX
Performance analysis and randamized agoritham
PDF
Daa notes 1
PPTX
NP completeness
PPTX
Traveling salesman problem
PPTX
NFA & DFA
Asymptotic notations
1.prallelism
Best First Search.pptx
tic-tac-toe: Game playing
LM7_ Embedded Sql and Dynamic SQL in dbms
Depth first search [dfs]
Unit-III-AI Search Techniques and solution's
sum of subset problem using Backtracking
Sorting in Linear Time in Analysis & Design of Algorithm
Graph in data structure
1.7. eqivalence of nfa and dfa
13 Amortized Analysis
I.BEST FIRST SEARCH IN AI
Breadth first search (bfs)
Performance analysis and randamized agoritham
Daa notes 1
NP completeness
Traveling salesman problem
NFA & DFA
Ad

Similar to Recursive squaring (20)

DOCX
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
PPT
Practical Meta Programming
PDF
C programs
PDF
C++ practical
PPT
Recursion
PDF
Tower of hanoi problem
PPT
chapter1.ppt
PPT
chapter1.ppt
PDF
C++ normal assignments by maharshi_jd.pdf
PPT
Computer Programming- Lecture 9
PPT
Basic_analysis.ppt
PPT
Time complexity
PDF
02 Notes Divide and Conquer
PPT
Lec-32 Recursion - Divide and Conquer in Queue
PDF
Ch01 basic concepts_nosoluiton
PDF
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
PDF
C# Assignmet Help
PDF
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
PDF
C++ TUTORIAL 5
PPT
chapter1.ppt
Task4output.txt 2 5 9 13 15 10 1 0 3 7 11 14 1.docx
Practical Meta Programming
C programs
C++ practical
Recursion
Tower of hanoi problem
chapter1.ppt
chapter1.ppt
C++ normal assignments by maharshi_jd.pdf
Computer Programming- Lecture 9
Basic_analysis.ppt
Time complexity
02 Notes Divide and Conquer
Lec-32 Recursion - Divide and Conquer in Queue
Ch01 basic concepts_nosoluiton
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
C# Assignmet Help
Solution Manual for Data Structures and Algorithm Analysis in C++, 4/E 4th Ed...
C++ TUTORIAL 5
chapter1.ppt
Ad

More from Quasar Chunawala (8)

PDF
PDF
Options pricing using Lattice models
PDF
Systems of linear algebraic equations i
PDF
Vector Addition
PDF
Investigation of functions
PDF
Vector spaces
PDF
On building FX Volatility surface - The Vanna Volga method
PDF
Interpolation techniques - Background and implementation
Options pricing using Lattice models
Systems of linear algebraic equations i
Vector Addition
Investigation of functions
Vector spaces
On building FX Volatility surface - The Vanna Volga method
Interpolation techniques - Background and implementation

Recently uploaded (20)

PDF
Developing a website for English-speaking practice to English as a foreign la...
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
OMC Textile Division Presentation 2021.pptx
PDF
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
Tartificialntelligence_presentation.pptx
PDF
Hindi spoken digit analysis for native and non-native speakers
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
WOOl fibre morphology and structure.pdf for textiles
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PPTX
observCloud-Native Containerability and monitoring.pptx
Developing a website for English-speaking practice to English as a foreign la...
Web App vs Mobile App What Should You Build First.pdf
NewMind AI Weekly Chronicles - August'25-Week II
OMC Textile Division Presentation 2021.pptx
2021 HotChips TSMC Packaging Technologies for Chiplets and 3D_0819 publish_pu...
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
A novel scalable deep ensemble learning framework for big data classification...
Tartificialntelligence_presentation.pptx
Hindi spoken digit analysis for native and non-native speakers
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
NewMind AI Weekly Chronicles – August ’25 Week III
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
cloud_computing_Infrastucture_as_cloud_p
WOOl fibre morphology and structure.pdf for textiles
Programs and apps: productivity, graphics, security and other tools
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
observCloud-Native Containerability and monitoring.pptx

Recursive squaring

  • 1. 1 Fibonacci using recursive squaring The naive bottom-up algorithm to compute the nth 󰅬ibonacci number take linear time O(n). We can do better than linear time. One of the well-known properties of 󰅬ibonacci numbers is : Fn+1 Fn Fn Fn−1 = 1 1 1 0 n We can therefore compute the nth power of A = ((1, 1), (1, 0)) using recursive squaring. That is, if n is even, we recursively compute An/2 . This sub-problem takes T(n/2) time. Cache this result in a temp variable. The desired result is An = An/2 × An/2 . Since, we have already computed An/2 , it’s the same subproblem, we don’t have to repeat this work. So, all we do is temp*temp. Multiplying two 2 × 2 matrices takes constant time - O(1). So, the total running time is T(n) = T(n/2) + O(1) which has upper bound O(lg n). Here’s the code snippet: #include <iostream > class matrix { int items[2][2]; public: matrix(); matrix(const matrix& A); matrix(int init_value); matrix& operator = (const matrix& A); matrix operator * (const matrix& A) const; void print() const; void set(int i, int j, int x); matrix rec_power(int n); }; int main() { matrix A; matrix B = A.rec_power(5); std::cout << "nA^5 = "; B.print(); std::cin.clear();
  • 2. 2 std::cin.get(); return 0; } matrix::matrix() { items[0][0] = items[1][0] = items[0][1] = 1; items[1][1] = 0; } matrix::matrix(const matrix& A) { for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) items[i][j] = A.items[i][j]; } matrix::matrix(int init_value) { for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) items[i][j] = init_value; } matrix& matrix::operator = (const matrix& A) { if (this == &A) return *this; for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) items[i][j] = A.items[i][j]; return *this; } matrix matrix::operator * (const matrix& A) const { matrix temp(0); for (int i = 0; i < 2; i++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { temp.items[i][j] += items[i][k] * A.items[k][j];
  • 3. 3 } } } return temp; } void matrix::print() const { std::cout << "n(" << items[0][0] << "," << items[0][1] << ")"; std::cout << "n(" << items[1][0] << "," << items[1][1] << ")"; } void matrix::set(int i, int j, int x) { items[i][j] = x; } matrix matrix::rec_power(int n) { if (n == 0) { matrix temp; temp.items[0][0] = temp.items[1][1] = 1; temp.items[0][1] = temp.items[1][0] = 0; return temp; } if (n == 1) { return *this; } else { if (n % 2 == 0) { matrix temp = rec_power(n / 2); return temp * temp; } else { matrix temp = rec_power((n - 1) / 2); return temp * temp * (*this); } }