📜  在给定范围内选择随机数时获得完美平方的可能性

📅  最后修改于: 2021-04-22 01:31:46             🧑  作者: Mango

给定两个表示范围的整数LR ,任务是找到当在L到R的范围内选择一个随机数时获得完美平方数的概率。
例子:

方法:此问题的主要观察结果是,可用给定公式计算从0到数字范围内的理想平方数:

同样,可以在上述公式的帮助下,按以下公式计算给定范围内的理想平方数:

下面是上述方法的实现:

C++
// C++ implementation to find the
// probability of getting a
// perfect square number
 
#include 
using namespace std;
 
// Function to return the probability
// of getting a perfect square
// number in a range
float findProb(int l, int r)
{
    // Count of perfect squares
    float countOfPS = floor(sqrt(r)) - ceil(sqrt(l)) + 1;
 
    // Total numbers in range l to r
    float total = r - l + 1;
 
    // Calculating probability
    float prob = (float)countOfPS / (float)total;
    return prob;
}
 
// Driver Code
int main()
{
    int L = 16, R = 25;
    cout << findProb(L, R);
 
    return 0;
}


Java
// Java implementation to find the
// probability of getting a
// perfect square number
 
class GFG{
 
// Function to return the probability
// of getting a perfect square
// number in a range
static float findProb(int l, int r)
{
 
    // Count of perfect squares
    float countOfPS = (float) (Math.floor(Math.sqrt(r)) -
                               Math.ceil(Math.sqrt(l)) + 1);
 
    // Total numbers in range l to r
    float total = r - l + 1;
 
    // Calculating probability
    float prob = (float)countOfPS / (float)total;
    return prob;
}
 
// Driver Code
public static void main(String[] args)
{
    int L = 16, R = 25;
    System.out.print(findProb(L, R));
}
}
 
// This code is contributed by Amit Katiyar


Python3
# Python3 implementation to find 
# the probability of getting a
# perfect square number
import math
 
# Function to return the probability
# of getting a perfect square
# number in a range
def findProb(l, r):
     
    # Count of perfect squares
    countOfPS = (math.floor(math.sqrt(r)) -
                  math.ceil(math.sqrt(l)) + 1)
     
    # Total numbers in range l to r
    total = r - l + 1
 
    # Calculating probability
    prob = countOfPS / total
     
    return prob
     
# Driver code
if __name__=='__main__':
     
    L = 16
    R = 25
     
    print(findProb(L, R))
     
# This code is contributed by rutvik_56


C#
// C# implementation to find the probability
// of getting a perfect square number
using System;
 
class GFG{
 
// Function to return the probability
// of getting a perfect square
// number in a range
static float findProb(int l, int r)
{
     
    // Count of perfect squares
    float countOfPS = (float)(Math.Floor(Math.Sqrt(r)) -
                            Math.Ceiling(Math.Sqrt(l)) + 1);
 
    // Total numbers in range l to r
    float total = r - l + 1;
 
    // Calculating probability
    float prob = (float)countOfPS / (float)total;
    return prob;
}
 
// Driver Code
public static void Main(String[] args)
{
    int L = 16, R = 25;
     
    Console.Write(findProb(L, R));
}
}
 
// This code is contributed by Amit Katiyar


Javascript


输出:
0.2

时间复杂度: O(1)