什么是“渐近紧张的时间复杂性”?这段代码的时间复杂性是否渐近紧张?

时间:2015-04-12 00:25:09

标签: c++ big-o complexity-theory

为什么这段代码的时间复杂度为O(x n m)?

此代码的时间复杂度是否渐近紧张?

为什么?

#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
    int a[10][10], b[10][10], c[10][10];
    int x, y, i, j, m, n;


    cout << "\nEnter the number of rows and columns for Matrix A:::\n\n";
    cin >> x >> y;


    // x denotes number rows in matrix A
    // y denotes number columns in matrix A
    cout << "\n\nEnter elements for Matrix A :::\n\n";
    for (i = 0; i < x; i++)
    {
        for (j = 0; j < y; j++)
        {
            cin >> a[i][j];
        }
        cout << "\n";
    }
    cout << "\n\nMatrix A :\n\n";
    for (i = 0; i < x; i++)
    {
        for (j = 0; j < y; j++)
        {
            cout << "\t" << a[i][j];
        }
        cout << "\n\n";
    }
    cout << "\n-----------------------------------------------------------\n";
    cout << "\nEnter the number of rows and columns for Matrix B:::\n\n";
    cin >> m >> n;
    // m denotes number rows in matrix B
    // n denotes number columns in matrix B


    cout << "\n\nEnter elements for Matrix B :::\n\n";
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            cin >> b[i][j];
        }
        cout << "\n";
    }
    cout << "\n\nMatrix B :\n\n";
    for (i = 0; i < m; i++)
    {
        for (j = 0; j < n; j++)
        {
            cout << "\t" << b[i][j];
        }
        cout << "\n\n";
    }
    if (y == m)
    {
        for (i = 0; i < x; i++)
        {
            for (j = 0; j < n; j++)
            {
                c[i][j] = 0;
                for (int k = 0; k < m; k++)
                {
                    c[i][j] = c[i][j] + a[i][k] * b[k][j];
                }
            }
        }
        cout
                << "\n-----------------------------------------------------------\n";
        cout << "\n\nMultiplication of Matrix A and Matrix B :\n\n";
        for (i = 0; i < x; i++)
        {
            for (j = 0; j < n; j++)
            {
                cout << "\t" << c[i][j];
            }
            cout << "\n\n";
        }
    }
    else
    {
        cout << "\n\nMultiplication is not possible";
    }
    getch();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

因为大多数计算都是在这里完成的:

for (i = 0; i < x; i++)
    {
        for (j = 0; j < n; j++)
        {
            c[i][j] = 0;
            for (int k = 0; k < m; k++)
            {
                c[i][j] = c[i][j] + a[i][k] * b[k][j];
            }
        }
    }

此处的加法,乘法和赋值等基本操作数的近似值为x*n*m。这就是为什么这个算法有O(x*n*m)渐近的原因。但是就渐近而言,矩阵乘法可以更快地完成。只需查看有关矩阵乘法和大数字符号的相关文章。

Complexity introduction

Faster matrix multiplication approach