More refactoring…

#!/usr/bin/perl use strict; use warnings; # Get the input... print "\nEnter the power (a positive integer from 1 through 33): "; chomp(my $power = (<STDIN>)); # Quietly end if there's no input... $power =~ m/\S/ or exit 1; # Validate the input... $power =~ m/^(?:[1-9]|[12][0-9]|3[0-3])$/ or die "$power is not a positive integer from 1 through 33\n"; # Expand the binomial... my $expansion = binomial_expansion(1, $power, 1); # ...and then print the result... print "(x + y)^$power = $expansion\n"; exit 0; sub binomial_expansion { my ($k, $x, $y) = @_; my $term = sprintf "%dx^%dy^%d", $k, $x, ($y - 1); $term =~ s/\b1(?=x)//; # Remove 1 from 1x $term =~ s/(?<=[xy])\^1(?!\d)//g; # Remove ^1 from x^1 and y^1 $term =~ s/[xy]\^0//; # Remove x^0 and y^0 return $x > 0 ? sprintf "%s + %s", $term, binomial_expansion(($k * $x) / $y, ($x - 1), ($y + 1)) : $term ; }

In reply to Re^2: Algebraic Expansion of Binomials Using a Recursive Subroutine by Jim
in thread Algebraic Expansion of Binomials Using a Recursive Subroutine by lilgreen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.