finding the running time for my algorithm for finding whether an input is prime in terms of the input

為{幸葍}努か 提交于 2019-12-02 18:43:04

问题


This is my function for finding prime numbers

void print(int num)
{
    for(int i=2; i<num/2; i++)
    {
        if(num%i==0)
        {
            cout<<"not prime\n";
            exit(0);
        }
    }
    cout<<"prime\n";        
}

My input in num. I'm trying to find the runtime using big oh. I remember that finding the run time had something to do with log.

The worst case would be that my program would run the n/2 -1 times?


回答1:


Yes, the loop runs n/2-1 times and only contains commands of constant complexity, so your runtime scales as a*(n/2-1) for some a. In big-o this is written as O(n/2-1) and because constant factors don't matter this is equal to O(n).

(as an aside: it is actually theta(n) which means, that it is not just bounded from above by n but also from below by n)



来源:https://stackoverflow.com/questions/21976894/finding-the-running-time-for-my-algorithm-for-finding-whether-an-input-is-prime

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!