Problem:

Take N numbers as input and print their GCD

**Input Format:**

num1 num2 num3......ie numbers seperated by space

**Output Format:**

GCD

**Constraints:**

none

Sample Input

6 15 9 30

Sample Output:

GCD is 3

GCD is 3

Explanations:

3 is GCD of 6,15,9,30

3 is GCD of 6,15,9,30

Solution:

my ($x, $y) = @_;

($x, $y) = ($y, $x % $y) while $y;

return $x;

}

sub multigcf {

my $x = shift;

$x = gcf($x, shift) while @_;

return $x;

}

chomp($num=<STDIN>);

@arr=split(" ",$num);

$ans=multigcf(@arr);

print "GCD is $ans";

Tips:

Find GCD of 2 numbers at a time, say gcd1. In next cycle, find gcd of gcd1 and next number and so on.

## No comments:

## Post a Comment