2013-05-08 07:34:24 -07:00
|
|
|
package DDG::Goodie::GreatestCommonFactor;
|
2014-08-20 11:45:33 -07:00
|
|
|
# ABSTRACT: Returns the greatest common factor of the two numbers entered
|
2013-05-08 07:34:24 -07:00
|
|
|
|
2015-02-22 12:09:29 -08:00
|
|
|
use strict;
|
2013-05-08 07:34:24 -07:00
|
|
|
use DDG::Goodie;
|
|
|
|
|
|
|
|
zci answer_type => "greatest_common_factor";
|
2014-10-14 09:57:55 -07:00
|
|
|
zci is_cached => 1;
|
2013-05-08 07:34:24 -07:00
|
|
|
|
2015-03-11 03:17:03 -07:00
|
|
|
triggers startend => 'greatest common factor', 'gcf', 'greatest common divisor', 'gcd';
|
2013-05-08 07:34:24 -07:00
|
|
|
|
|
|
|
primary_example_queries 'GCF 121 11';
|
|
|
|
secondary_example_queries '99 9 greatest common factor';
|
|
|
|
description 'returns the greatest common factor of the two entered numbers';
|
|
|
|
name 'GreatestCommonFactor';
|
|
|
|
topics 'math';
|
|
|
|
category 'calculations';
|
2015-01-07 10:37:42 -08:00
|
|
|
attribution github => [ 'https://github.com/austinheimark', 'Austin Heimark' ];
|
2013-05-08 07:34:24 -07:00
|
|
|
|
|
|
|
handle remainder => sub {
|
|
|
|
|
2015-03-17 15:09:47 -07:00
|
|
|
return unless /^\s*\d+(?:(?:\s|,)+\d+)*\s*$/;
|
2014-10-28 11:36:15 -07:00
|
|
|
|
2015-03-11 03:58:56 -07:00
|
|
|
# Here, $_ is a string of digits separated by whitespaces. And $_
|
|
|
|
# holds at least one number.
|
2014-10-14 09:57:55 -07:00
|
|
|
|
2015-03-17 15:09:47 -07:00
|
|
|
my @numbers = grep(/^\d/, split /(?:\s|,)+/);
|
2015-03-11 03:58:56 -07:00
|
|
|
@numbers = sort { $a <=> $b } @numbers;
|
|
|
|
|
|
|
|
my $formatted_numbers = join(', ', @numbers);
|
|
|
|
$formatted_numbers =~ s/, ([^,]*)$/ and $1/;
|
|
|
|
|
|
|
|
my $result = shift @numbers;
|
|
|
|
foreach (@numbers) {
|
|
|
|
$result = gcf($result, $_)
|
|
|
|
}
|
|
|
|
|
|
|
|
return "Greatest common factor of $formatted_numbers is $result.",
|
2014-10-14 09:57:55 -07:00
|
|
|
structured_answer => {
|
2015-03-11 03:58:56 -07:00
|
|
|
input => [$formatted_numbers],
|
2015-01-09 00:01:04 -08:00
|
|
|
operation => 'Greatest common factor',
|
2014-10-14 09:57:55 -07:00
|
|
|
result => $result
|
|
|
|
};
|
2013-05-08 07:34:24 -07:00
|
|
|
};
|
|
|
|
|
2014-10-14 09:57:55 -07:00
|
|
|
sub gcf {
|
|
|
|
my ($x, $y) = @_;
|
|
|
|
($x, $y) = ($y, $x % $y) while $y;
|
|
|
|
return $x;
|
|
|
|
}
|
|
|
|
|
2013-05-08 07:34:24 -07:00
|
|
|
1;
|