Probability of getting a perfect square when a random number is chosen in a given range
Last Updated :
16 Sep, 2022
Given two integers L and R that denote a range, the task is to find the probability of getting a perfect square number when a random number is chosen in the range L to R.
Examples:
Input: L = 6, R = 20
Output: 0.133333
Explanation:
Perfect squares in range [6, 20] = {9, 16} => 2 perfect squares
Total numbers in range [6, 20] = 15
Probability = 2 / 15 = 0.133333
Input: L = 16, R = 25
Output: 0.2
Approach: The key observation in this problem is the count of the perfect squares in the range from 0 to a number can be computed with the given formulae:
// Count of perfect squares in the range 0 to N is given as
Count of perfect squares = Floor(sqrt(N))
Similarly, the count of the perfect squares in the given range can be computed with the help of the above formulae as follows:
Count of perfect Squares[L, R] = floor(sqrt(R)) – ceil(sqrt(L)) + 1
Total numbers in the range = R – L + 1
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float findProb( int l, int r)
{
float countOfPS = floor ( sqrt (r)) - ceil ( sqrt (l)) + 1;
float total = r - l + 1;
float prob = ( float )countOfPS / ( float )total;
return prob;
}
int main()
{
int L = 16, R = 25;
cout << findProb(L, R);
return 0;
}
|
Java
class GFG{
static float findProb( int l, int r)
{
float countOfPS = ( float ) (Math.floor(Math.sqrt(r)) -
Math.ceil(Math.sqrt(l)) + 1 );
float total = r - l + 1 ;
float prob = ( float )countOfPS / ( float )total;
return prob;
}
public static void main(String[] args)
{
int L = 16 , R = 25 ;
System.out.print(findProb(L, R));
}
}
|
Python3
import math
def findProb(l, r):
countOfPS = (math.floor(math.sqrt(r)) -
math.ceil(math.sqrt(l)) + 1 )
total = r - l + 1
prob = countOfPS / total
return prob
if __name__ = = '__main__' :
L = 16
R = 25
print (findProb(L, R))
|
C#
using System;
class GFG{
static float findProb( int l, int r)
{
float countOfPS = ( float )(Math.Floor(Math.Sqrt(r)) -
Math.Ceiling(Math.Sqrt(l)) + 1);
float total = r - l + 1;
float prob = ( float )countOfPS / ( float )total;
return prob;
}
public static void Main(String[] args)
{
int L = 16, R = 25;
Console.Write(findProb(L, R));
}
}
|
Javascript
<script>
function findProb(l, r)
{
var countOfPS = (Math.floor(Math.sqrt(r)) -
Math.ceil(Math.sqrt(l)) + 1);
var total = r - l + 1;
var prob = countOfPS / total;
return prob;
}
var L = 16, R = 25;
document.write(findProb(L, R));
</script>
|
Time Complexity: O(log(r) + log(l))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...