#!/usr/bin/perl -w

use strict;
use 5.030;

# La función de distribución acumulada binomial es
# P(X <= x) = SUM from k=0 to x { comb(n over k) * p^k * (1-p)^(n-k) } 
# en la distribución X ~ Bin(n,p)

N:
print "Binomial: enter N = ";
chomp(my $N = <STDIN>);
if (0+$N ne $N || $N != int $N) { goto N; }

P:
print "Binomial: enter P = ";
chomp(my $P = <STDIN>);
if (0+$P ne $P) { goto P; }

x:
print "Enter x so P(X<=x) will be calculated: ";
chomp (my $x = <STDIN>);
if (0+$x ne $x || $x != int $x || $x > $N ) { goto x; }

say "";

my $sum;
for my $k (0..$x){
    $sum += comb( $N, $k ) * ($P**$k) * (1-$P)**($N-$k);  
}
say "Probability = $sum";

exit 1;





# El test binomial




sub comb {
    my $n = shift;
    my $m = shift;
    
    # comb(n,m) = n!/(m! * (n-m)!)
    
    if ($m > $n) { warn "M mayor que N"; return ;}
    
    my $nn=1;
    my $mm=1;
    
    for (2..$m){
	$mm *= $_;
    }
    for (($n-$m+1)..$n){  # esto es n!/(n-m)! = n*(n-1)* ... (n-m+1) y stop
	$nn *= $_;
    }
#    print "Las combinaciones son ",$nn/$mm,"\n";
    return ($nn/$mm);    
}

