for (ll i = 2; i <= sqrt(n); ++i)
: sqrt is costly, you could use i*i <= nfor (ll j = 2; (i*j) <= n; ++j)
: you need not start j from 2, start it from i*i, this is because you would have already checked the combination 2 and i before when i was 2.- I am not sure if multiplication is costlier than addition, you could refactor
i*j
in second loop to use addition. - Instead of finding primes for each input range separately, you could take all inputs at once and calculate for the highest number, and sort out the outputs later, so basically find primes once and not multiple times.