C++ Program Probability for three randomly chosen numbers to be in AP

C++Server Side ProgrammingProgramming

Given with an array of numbers ‘n’ and the task is to find the probability of three randomly chosen numbers to be in AP.

Example

Input-: arr[] = { 2,3,4,7,1,2,3 }
Output-: Probability of three random numbers being in A.P is: 0.107692
Input-:arr[] = { 1, 2, 3, 4, 5 }
Output-: Probability of three random numbers being in A.P is: 0.151515

Approach used in the below program is as follows

  • Input the array of positive integers
  • Calculate the size of the array
  • Apply the formula given below to find the probability of three random numbers to be in AP

    3 n / (4 (n * n) – 1)

  • Print the result

ALGORITHM

Start
Step 1-> function to calculate the probability of three random numbers be in  AP
   double probab(int n)
      return (3.0 * n) / (4.0 * (n * n) - 1)
Step 2->In main()
   declare an array of elements as   int arr[] = { 2,3,4,7,1,2,3 }
   calculate size of an array as  int size = sizeof(arr)/sizeof(arr[0])
   call the function to calculate probability as probab(size)
Stop

Example

#include <bits/stdc++.h>
using namespace std;
//calculate probability of three random numbers be in AP
double probab(int n) {
    return (3.0 * n) / (4.0 * (n * n) - 1);
}
int main() {
    int arr[] = { 2,3,4,7,1,2,3 };
    int size = sizeof(arr)/sizeof(arr[0]);
    cout<<"probability of three random numbers being in A.P is : "<<probab(size);
    return 0;
}

Output

Probability of three random numbers being in A.P is: 0.107692
raja
Updated on 20-Nov-2019 12:24:58

Advertisements