I have some doubts regarding the time complexity of my code!

Basically I am storing all primes upto sqrt(10**9).
Now For checking a number as primes, I check if it is divisible by any of the primes upto srt(of that number).

Please tell me how to find the time complexity of such code.

Here is my code:-

#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define MX 31622
#define endl "\n"
vector<int> primes;
void init(){
    vector<bool> sieve(MX+1,true);
    sieve[0] = sieve[1] =false;
    for(int i=2;i<=MX;i++){
        if(sieve[i]){
            primes.push_back(i);
            for(int j=i*i;j<=MX;j+=i){
                sieve[j] = false;
            }
        }
    }
}

inline bool check(int num){
    int n = (int)sqrt(num);
    for(int i=0;i<primes.size() && primes[i]<=n;i++){
        if(num%primes[i] == 0){
            return false;
        }
    }
    return true;
}

void solve(int l, int r){
    for(int i=max(l,2);i<=r;i++){
        if(check(i))
            cout<<i<<endl;
    }
}

int main() {
    init();
    int n;
    cin>>n;
    while(n--){
        int l,r;
        cin>>l>>r;
        solve(l,r);
        cout<<endl;
    }
	return 0;
}

Hey @shivama_700
So lets assume sqrt(10*9) as N

  1. So for each i from 1 to N
  2. You run a loop from 1 to sqrt( i )

So loop 1 runs N times so complexity N
The inner loop runs till sqrt( i ) which you can approximate as sqrt ( N ) as avg case
So TC becomes Nsqrt(N)

If your doubt is resolved please close it

The outer loop is from L to R, which is not sqrt(10^9) it is 10^5.
So according to your analysis there should be average 10^5 * sqrt(10^9) operations
which is 3162277660 = 3*10^9, which is greater than 10^8, that means our solution should get tle, but our solution got accepted which means our TCA is wrong.

Please help with the above query.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.