0

This code should do the LCM from N numbers.

I tried to put prints wherever I can in order to see where is the mistake. and I think is in:

if($vec[0] == $vec[$n-1]){
    $resultado = $vec[0];
    last;
}

But I can not make it work. Could you please help me?

I'm a rookie with Perl. Hope you can solve this problem.
Also I tried to change the variables but it does not work. I mean

$u = 0 , $w = $n-1;

FULL CODE

serenesat
  • 4,611
  • 10
  • 37
  • 53
  • 1
    Please put `use strict;` `use warnings;` as the first lines in your script, it checks for many basic errors ( syntax and others ). There is no $u/$w in the code linked that I can see. What exactly is the problem, i.e. "make it work" -> what is expected output, and what do you get? – bytepusher Sep 30 '15 at 07:20
  • You might want to take a look at perl sort http://perldoc.perl.org/functions/sort.html , used like so: `my @sorted = sort { $a <=> $b }@input;` for sorting numbers. – bytepusher Sep 30 '15 at 07:31
  • Thank You, iam going to try that :D – Edgar Arroyo Sep 30 '15 at 07:36

1 Answers1

-1

To get the LCM, you can split the task into multiple subroutines:

  • is_prime # returns true if the value is prime
  • roots # returns the roots of a number (all prime numbers that make up a value. Ex: roots of 12 are: 2, 2, 3)
  • LCM # takes a list of values. Extract the roots while the number is not prime. Store in a hash like and increment everytime we see the root

So we'll have a hash like:

%sub_total = (
  VALUE => TIMES_FOUND,
  2 => 2,
  3 => 1,
);

We have another hash which is the total. If the sub_total hash has a key that is used more often than in the total hash, we add it to the total.

Finally, we loop through the total hash and and find the product using the algorithm:

for (%total){
   $prod *= $_ ** $total {$_};
}

Note

I'll shortly attach the code I wrote for getting the LCM. It's not with me now here.

Tim Potapov
  • 431
  • 2
  • 12