In this Hackerrank Day 4: Geometric Distribution I 10 Days of Statistics problem The probability that a machine produces a defective product is 1/3. What is the probability that the 1sth defect occurs in the 5th item produced?


HackerRank Day 4: Geometric Distribution I | 10 Days of Statistics problem solution


Problem solution in Python programming.

# Enter your code here. Read input from STDIN. Print output to STDOUT
def geometric_distributon(n, p):
    return ((1-p)**(n-1))*p

a, b = list(map(int, input().split()))
n = int(input())
print('{:.3f}'.format(geometric_distributon(n, a/b)))



Problem solution in Java Programming.

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        final double p = 1.0/3.0;
        final double n = 5;
        
        final double r = Math.pow(1.0-p, n-1) * p;
        
        System.out.printf("%.3f", r);
    }
}


Problem solution in C++ programming.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */   
    double p = 1.0/3;
    int n=5;
    printf("%0.3f\n", pow(1-p, n-1)*p);
    return 0;
}


Problem solution in C programming.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */    
    int a, b, c;
    scanf("%d %d %d", &a, &b, &c);
    double p = (double) a / (double) b;
    double q = 1 - p;
    double ans = pow(q, c - 1) * p;
    printf("%.3lf", ans);
    return 0;
}


Problem solution in JavaScript programming.

function factorial(n) {
    var f = 1;
    for(var i=1; i<=n; i++) f *= i;
    return f;
}

function b(x, n, p) {
    var q = 1-p;
    return (factorial(n) / (factorial(x) * factorial(n-x))) * Math.pow(p, x) * Math.pow(q, n-x);
}

function bneg(x, n, p) {
    var q = 1-p;
    return (factorial(n-1) / (factorial(x-1) * factorial(n-x))) * Math.pow(p, x) * Math.pow(q, n-x);
}

function g(n, p) {
    var q = 1-p;
    return Math.pow(q, n-1) * p;
}

function processData(input) {
    var lines = input.split('\n');
    var values = lines[0].split(' ').map(Number);
    var p = values[0] / values[1];
    var runs = parseInt(lines[1]);
    var prob = g(runs, p);
    
    console.log(prob.toFixed(3));
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});