1

I came across this problem here. It was a programming contest held earlier this year.
Here is the summary :
Given an array of N integers, find LCM of all consecutive M integers.
For e.g.

Array = [3,5,6,4,8] (hence N = 5)  
M = 3  

Output :

LCM(3,5,6) = 30  
LCM(5,6,4) = 60  
LCM(6,4,8) = 24

In fact there's a solution sketch here but I couldn't understand the Dynamic Programming Part.
So if someone could elaborate on the same solution with some examples it will be great.
A new, easy to understand solution will also be appreciated.

simplfuzz
  • 12,479
  • 24
  • 84
  • 137
  • That sketch appears to have three parts: 1) an approach, 2) the part beginning "Another approach would be factorize each A[i]...", and 3) the last part, "Another method used by many contestants was...". Which part(s) do you want help with? – Beta Mar 05 '12 at 05:35
  • @Beta I want help with the Dynamic Programming part. – simplfuzz Mar 05 '12 at 06:39
  • 1
    @Carl I could think of the simplest solution which is finding LCM of all the consecutive M numbers without using DP or any other shortcut. Which is of O(MN) time. – simplfuzz Mar 05 '12 at 06:41

1 Answers1

0

I can not access the solution any more (maybe the link is broken?), but here is what I would do: I would have my program work like a pyramid. On the lowest row, I would have the array with the given numbers. On each row above, I would have an array with one field less than the array below. It would store the LCM of two values from the array below.

[   30    ]
[ 15,  30 ]
[3,  5,  6]

This way you can work with a recursive function and you have to build M-1 layers of the pyramid. Here's a Pseudo-Code implementation:

rekursivePyramid (Integer[] numbers, Integer height) {
    if (height == 0) return numbers;
    else {
        newNumbers = Integer[numbers.size() - 1];
        for (i=0; i<newNumbers.size(); i++) {
            newNumbers[i] = LCM ( numbers[i], numbers[i+1]);
        }
        return rekursivePyramid( newNumbers, height-1);
    }
}

This will give you an array, where you find the LCM of the first M numbers in first field, the LCM from the second to the M+1st number in the second field, etc.

Skrodde
  • 41
  • 10