Find the probability of picking a prime number in a range
Your question contains 2 pieces of code which makes it hard to review.

Issue specific to the C++ code

Your are using ++i in your code despite having handled the even numbers explicitely before. It should be i+=2 like in your Java code.

Issue in both implementations

Instead of maintaining an ans boolean value, you can simply return false whenever you know that the number can't be prime.

You write your loop like this for(int i = 3; i&lt;(Math.sqrt(n)+1);i=i+2) which is likely to compute the square root at each iteration. The compiler may be able to optimize this out but just in case, it is probably better to store it in a variable beforehand.

Different algorithm

To know whether many numbers are primes, a convenient and efficient algorithm is to use The Sieve of Eratosthenes to build a table to check primes.

You could build it one and for all to get the primes up to the maximum r value.

Going further, you could also build (once) a table giving for each number n the number of primes numbers smaller or equal to n. Then, for each input (a, b), the frequency is something along the lines of ( primes_up_to(b) - primes_up_to(a) / (b - a).