原文:
给定一个数字 n 和一个包含 1 到(2n 1)个连续数字的数组。随机选择三个元素。找出所选元素出现在 中的概率 :
input : n = 2
output : 0.4
the array would be {1, 2, 3, 4, 5}
out of all elements, triplets which
are in ap: {1, 2, 3}, {2, 3, 4},
{3, 4, 5}, {1, 3, 5}
no of ways to choose elements from
the array: 10 (5c3)
so, probability = 4/10 = 0.4
input : n = 5
output : 0.1515
从(2n 1)个数字中选择任意 3 个数字的方法有:(2n 1)c3 现在,对于要在 ap 中的数字: 同差 1—{1,2,3}、{2,3,4}、{3,4,5}……{2n-1,2n,2n 1} 同差 2—{1,3,5 }、{ 2,4,6}、{3,5 (2n 1)数中 3 个数的 ap 组总数为: (2n–1) (2n–3) (2n–5) … 3 1 =n * n( ) 所以,(2n 1)连续数中 3 个随机选择的数在 ap 中的概率= (n * n) / (2n 1) c 3
c
// cpp program to find probability that
// 3 randomly chosen numbers form ap.
#include
using namespace std;
// function to calculate probability
double procal(int n)
{
return (3.0 * n) / (4.0 * (n * n) - 1);
}
// driver code to run above function
int main()
{
int a[] = { 1, 2, 3, 4, 5 };
int n = sizeof(a)/sizeof(a[0]);
cout << procal(n);
return 0;
}
java 语言(一种计算机语言,尤用于创建网站)
// java program to find probability that
// 3 randomly chosen numbers form ap.
class gfg {
// function to calculate probability
static double procal(int n)
{
return (3.0 * n) / (4.0 * (n * n) - 1);
}
// driver code to run above function
public static void main(string arg[])
{
int a[] = { 1, 2, 3, 4, 5 };
int n = a.length;
system.out.print(math.round(procal(n) * 1000000.0) / 1000000.0);
}
}
// this code is contributed by anant agarwal.
python 3
# python3 program to find probability that
# 3 randomly chosen numbers form ap.
# function to calculate probability
def procal(n):
return (3.0 * n) / (4.0 * (n * n) - 1)
# driver code
a = [1, 2, 3, 4, 5]
n = len(a)
print(round(procal(n), 6))
# this code is contributed by smitha dinesh semwal.
c
// c# program to find probability that
// 3 randomly chosen numbers form ap.
using system;
class gfg {
// function to calculate probability
static double procal(int n)
{
return (3.0 * n) / (4.0 * (n * n) - 1);
}
// driver code
public static void main()
{
int []a = { 1, 2, 3, 4, 5 };
int n = a.length;
console.write(math.round(procal(n) *
1000000.0) / 1000000.0);
}
}
// this code is contributed by nitin mittal
服务器端编程语言(professional hypertext preprocessor 的缩写)
java 描述语言
输出:
0.151515
时间复杂度:o(1)
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处