行列指数を使用してフィボナッチ数を見つけるC++プログラム
一般にFnで表されるフィボナッチ数は、フィボナッチ数列と呼ばれる数列を形成します。各数値は、0と1から始まる、先行する2つの数値の合計です。つまり-
F0 = 0 and F1 = 1 And Fn = Fn-1 + Fn-2 for n > 1.
アルゴリズム
Begin
Take two 2 dimensional array
Create a function and Perform matrix multiplication
Create another function to find out power of matrix
Create a function then to find out the Fibonacci number
Multiply(arr1[2][2], arr2[2][2])
Take 4 variables a, b, c, d
a = arr1[0][0] * arr2[0][0] + arr1[0][1] * arr2[1][0]
b= arr1[0][0] * arr2[0][1] + arr1[0][1] * arr2[1][1]
c = arr1[1][0] * arr2[0][0] + arr1[1][1] * arr2[1][0]
d = arr1[1][0] * arr2[0][1] + arr1[1][1] * arr2[1][1]
arr1[0][0] = a
arr1[0][1] = b
arr1[1][0] = c
arr1[1][1] = d
Power(arr1[2][2], take integer n as input)
if (n == 0 or n == 1)
return;
arr1 [2][2] = {{1,1}, {1,0}}
power(arr1, n / 2)
multiply(arr1, arr1)
if (n mod 2 not equal to 0)
multiply(arr1, arr2)
fibonacci_matrix(n)
arr1[2][2] = {{1,1}, {1,0}}
if n ==0
return 0
power(arr1 n - 1)
return arr1[0][0]
End サンプルコード
#include <iostream>
using namespace std;
void multiply(int F[2][2], int M[2][2]) {
int a = F[0][0] * M[0][0] + F[0][1] * M[1][0];
int b= F[0][0] * M[0][1] + F[0][1] * M[1][1];
int c = F[1][0] * M[0][0] + F[1][1] * M[1][0];
int d = F[1][0] * M[0][1] + F[1][1] * M[1][1];
F[0][0] = a;
F[0][1] = b;
F[1][0] = c;
F[1][1] = d;
}
void power(int F[2][2], int n) {
if (n == 0 || n == 1)
return;
int M[2][2] = {{1,1},{1,0}};
power(F, n / 2);
multiply(F, F);
if (n % 2 != 0)
multiply(F, M);
}
int fibonacci_matrix(int n) {
int F[2][2] = {{1,1},{1,0}};
if (n == 0)
return 0;
power(F, n - 1);
return F[0][0];
}
int main() {
int n;
while (1) {
cout<<"Enter the integer n to find nth fibonacci no. (enter 0 to exit):";
cin>>n;
if (n == 0)
break;
cout<<fibonacci_matrix(n)<<endl;
}
return 0;
} 出力
Enter the integer n to find nth fibonacci no. (enter 0 to exit): 2 1 Enter the integer n to find nth fibonacci no. (enter 0 to exit): 6 8 Enter the integer n to find nth fibonacci no. (enter 0 to exit): 7 13 Enter the integer n to find nth fibonacci no. (enter 0 to exit): 0
-
接続行列を使用してグラフを表現するC++プログラム
グラフの接続行列は、メモリに保存するグラフの別の表現です。この行列は正方行列ではありません。接続行列の次数はVxEです。ここで、Vは頂点の数、Eはグラフのエッジの数です。 この行列の各行に頂点を配置し、各列にエッジを配置します。エッジe{u、v}のこの表現では、列eの場所uとvに対して1でマークされます。 隣接行列表現の複雑さ 接続行列表現は、計算中にO(Vx E)のスペースを取ります。完全グラフの場合、エッジの数はV(V-1)/2になります。したがって、接続行列はメモリ内でより大きなスペースを取ります。 入力 出力 E0 E1 E2
-
隣接行列を使用してグラフを表現するC++プログラム
グラフの隣接行列は、サイズV x Vの正方行列です。Vは、グラフGの頂点の数です。この行列では、各辺にV個の頂点がマークされています。グラフにiからjの頂点までのエッジがある場合、i thの隣接行列に 行とjth 列は1(または加重グラフの場合はゼロ以外の値)になります。それ以外の場合、その場所は0を保持します。 隣接行列表現の複雑さ 隣接行列表現はO(V 2 )計算中のスペースの量。グラフに最大数のエッジと最小数のエッジがある場合、どちらの場合も必要なスペースは同じになります。 入力 出力 0 1 2 3 4 5