#!perl -w # BinomialExpansion.pl # usage perl BinomialExpansion.pl n, where n is an integer > 0 # ** the memory goes crazy after the 170th power # the expansion of (x+y)^170 peaks at 9.14484184513157e+049 * x^85 * y^85 # so you can imagine what happens if you put int n>170 my \$n = (\$_=shift) > 0 ? int \$_ : die "'usage perl BinomialExpansion.pl 9, where n > 0'"; print _titled_hr(' Binomial Expansion For (x+y)^',\$n,' '); for my \$j (0 .. \$n) { my \$coefficient = nCr(\$n,\$j); my \$nj=\$n-\$j; print \$coefficient; print \$_ = (\$nj!=0)?( (\$nj>1)?(' * x^'.\$nj):(' * x') ):''; print \$_ = (\$j!=0)?( (\$j==1)?(' * y'):(' * y^'.\$j) ):''; print \$_ = (\$j!=\$n)?(" +\n"):("\n"); } print ' 'x 25,' = (x + y)^',\$n, "\n"x 3; # returns n!/r!(n-r)! sub nCr { my \$n=shift; my \$r=shift; return int nFactorial(\$n) / int nFactorial(\$r) * int nFactorial(\$n-\$r); } # like the name says, n! sub nFactorial { my \$n=shift; my \$product = 1; while(\$n>0) { \$product *= \$n--; } return \$product; } # neat little titled hr, that does a < 80 chars since int rounds down # i really, really, like it sub _titled_hr { my \$string = join('', @_); my \$oy = int (80 -(length \$string) )/ 2; return "\n","-" x \$oy, \$string, "-" x \$oy,"\n"; } __END__ # some random things i say #1 "--. .-. . . - --.. -.-- .----. .- .-.. .-.." #2 "...- .-. --- --- -- --..-- ...- .-. --- --- -- .----." #3 --- ..-. .- .-.. .-.. - .... . - .... .. -. --. ... .. .-.. --- ... - --..-- .. -- .. ... ... -- -.-- -- .. -. -.. - .... . -- --- ... - .-.-.- -....- -....- --- --.. --.. .. . --- ... -... --- ..- .-. -. . # a lil sample from my machine F:\>perl BinomialExpansion.pl 9 1 * x^9 + 9 * x^8 * y + 36 * x^7 * y^2 + 84 * x^6 * y^3 + 126 * x^5 * y^4 + 126 * x^4 * y^5 + 84 * x^3 * y^6 + 36 * x^2 * y^7 + 9 * x * y^8 + 1 * * y^9 = (x + y)^9 F:\> # Notice a pattern? Fleet attack! # > # > # > # > # > # > # > # > # > # >