3 October 2014

Quiz 37:Find LCM of multiple numbers

Problem:
Take N numbers as input and print their LCM

Input Format: 
num1 num2 num3......ie numbers seperated by space

Output Format: 
LCM

Constraints: 
none

Sample Input
20 30 40 50

Sample Output:
LCM is 600

Explanations:
600 is LCM of 20.30.40.50


Solution:

sub gcf {
  my ($x, $y) = @_;
  ($x, $y) = ($y, $x % $y) while $y;
  return $x;
}

sub lcm {
  return($_[0] * $_[1] / gcf($_[0], $_[1]));
}

sub multilcm {
       my $x = shift;
       $x = lcm($x, shift) while @_;
       return $x;
    }

chomp($num=<STDIN>);
@arr=split(" ",$num);
$ans=multilcm(@arr);
print "LCM is $ans";


Tips:
Find LCM of 2 numbers at a time, say lcm1. In next cycle, find lcm of lcm1 and next number and so on.

No comments:

Post a Comment