I would probably do it on the cart page manually by looping through the cart and adding the correct free items.
The more simple way to do it is use math and simply don't charge for the free items. The drawback is that if it is buy 3 get 2 free and someone buys 4 they only get charged for three but don't get their other free one automatically.
This would be much easier to do. You would add columns to your cart "BuyX" and "GetY".
Then TotalPrice calculation becomes: (floor([Quantity]/([BuyX]+[GetY])) * [Price] * [BuyX]) + (([Quantity]%([BuyX]+[GetY]) < [BuyX])?[Quantity]%([BuyX]+[GetY]):[BuyX])