<?php
//!--------------------------------------------------------
// @class bNewton
// @desc Solve the Newton's binomial.
// Use the binomial theorem to solve and
// to display the equation.
// Solving the binomial coefficients it show
// the equivalent equation.
// @author Israel de Souza Rocha
//!--------------------------------------------------------
class bNewton {
//!--------------------------------------------------
// @function bNewton::calculate
// @desc Main class method. Calculate and dislplay
// the result.
// @param a string first binomial's element
// @param b string second binonial's element
// @param grade int binomial's grade
// @access public
// @return void
//!--------------------------------------------------
function calculate($a, $b, $grade) {
$res = $a . '<sup>' . $grade . '</sup>';
$negative = (trim($b[0])=='-');
if ($negative) {
$b = substr($b, 1, strlen($b));
}
$signal = '+';
for ($i = 1; $i < $grade; $i++) {
$signal = (($negative) ? $this->signal(&$negative) : $signal);
$res .= $signal . ' ' . $this->binomialNumber($grade, $i) . ' . ' . $a . '<sup>' . (($grade - $i == 1) ? '' :$grade - $i) . '</sup> . ' . $b . '<sup>' . (($i==1) ?'':$i) . '</sup> ';
}
$signal = (($negative) ? $this->signal(&$negative) : $signal);
$res .= $signal . ' ' . $b . '<sup>' . $grade . '</sup>';
echo $res;
}
//!--------------------------------------------------
// @function bNewton::binomialNumber
// @desc Used to calculate the binomial coefficient.
// @param n int
// @param p int
// @access public
// @return int
//!--------------------------------------------------
function binomialNumber($n, $p) {
return $this->fat($n) / ( $this->fat($p) * $this->fat($n - $p) );
}
//!--------------------------------------------------
// @function bNewton::fat
// @desc Simple factorial.
// @param val int Number to factorate
// @param pos string Position to calculate the next value
// @access public
// @return int
//!--------------------------------------------------
function fat( $val, $pos = null ) {
$pos = ($pos == null) ? $val : $pos;
if ($pos != 1) {
return $this->fat($val * ($pos - 1), $pos -1);
}
return $val;
}
//!--------------------------------------------------
// @function bNewton::signal
// @desc Alternate the binomial's terms signal.
// @param sig string The signal
// @access public
// @return string
//!--------------------------------------------------
function signal($sig) {
if ($sig=='-') {
$sig = '+';
} else {
$sig = '-';
}
return $sig;
}
}
?>