in reply to Re: Algebraic Expansion of Binomials Using a Recursive Subroutine
in thread Algebraic Expansion of Binomials Using a Recursive Subroutine
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 ; }
|
|---|