确定程序的渐近复杂性

时间:2013-01-22 08:02:28

标签: c++ polynomial-math asymptotic-complexity

嘿伙计们我对c ++很新,我试图确定我的程序的渐近复杂性,它接受输入并确定它是否是多项式。

“如果输入表达式的长度是m chars,那么你的程序相对于m的复杂程度是多少?”

我的猜测是O(m * log m),其中第一个m是for循环,迭代m次,log m是while循环,它计算大于1位的指数。

另外,我正在尝试保存一个包含最大指数的“最大”值,以便计算多项式运行时复杂度。但是,我对正确存储指数感到困惑。谁能推荐一种更简单的方法?

示例输入:“n ^ 23 + 4n ^ 10 - 3”应该有23作为最大指数

#include <iostream>
#include <string>
using namespace std;

int main() {

string input;
int pcount = 1; //count for # of variables( min 3 to be poly)
int largest = 0; // used for complexity
int temp=0;

cout << "Enter equation below. " << endl;
getline(cin,input); //to input polynomial
cout << endl << input << endl;

if (input[0] == '-' || input[0] == '+') //to check for '-' as first char
pcount--;

bool pcheck = true; 

for (unsigned i = 0; i < input.size(); i++)
{
temp = 0;

cout << input[i] << endl;
if ( input[i] == '+' || input[i] == '-' )
pcount++;

if ( input[i] == 'n') //checks for integer
{

    if ( input[i+1] && input[i+1] == '^' )
    { 
        if (input[i+2] == 46 || input[i+2] == 43 || input[i+2] == 45)
         {
             cout << "fail" << endl;
             pcheck = false;
         }

        temp = input[i+2]-48; // to check for largest exp

        while ( input[i+2] != 43 && input[i+2] != 45) 
        {           

            if ( i+3 == input.size())
            {
                cout << "break";
                break;
            }
            if( input[i+2] < 48 || input[i+2] >57) // 48-57 is ascii 
            {
                cout << "fail" << endl;
                pcheck = false;     
            }                
            i++;

            temp = temp * 10;
            temp = temp + (input[i+2]-48);
            if (temp > largest)
            largest = temp;
        }
    }
}               
}

if ( pcheck == true && pcount >= 3) //valid ints and at least 3 variables
{
cout << "polynomial detected!" << endl << "The big-Oh complexity is O(n^" <<
largest << ")." << endl;
}
else            
cout << "not a poly" << endl;       

return 0;
}

1 个答案:

答案 0 :(得分:0)

对于输入的O(N)个字符,您的程序应该具有N复杂度(线性),只要您跟踪到目前为止的最高指数。通过这种方式,您无需重新阅读以前的字符。