r/dailyprogrammer • • May 16 '12

[5/16/2012] Challenge #53 [difficult]

The set {2,3,5,7,11} has 32 subsets, and if you multiply the elements of each subset together, you get the "product" of that specific subset. So for instance, {2,5,7} is a subset of {2,3,5,7,11} and it has the product 70 (i.e. 2*5*7).

The subset of {2,3,5,7,11} with the largest product that does not exceed 100 is {7,11}, with the product 77.

Given a set s and a number v, define A(s,v) as the subset of s with the largest product that does not exceed v. Also, define p(n) as the set of the first n primes (thus p(5) is equal to {2,3,5,7,11}). Here are some examples of A(p(n), v):

A(p(5), 100) = {7, 11}                        
A(p(7), 1000) = {5, 11, 17}                   
A(p(8), 2000) = {3, 5, 7, 19}                 
A(p(10), 10000000) = {2, 5, 7, 11, 19, 23, 29}

Find A(p(20), 1018 )


BONUS: Find A(p(40), 1060 )


NOTES: If it is more convienient, you are allowed to make your A(s,v) function output the product instead of the subset itself, so A(p(5), 100) = 77 instead of {7,11}. Watch out though, the numbers can get very big.

5 Upvotes

12 comments sorted by

View all comments

Show parent comment

1

u/bh3 May 17 '12

(Spoilers)

I've actually worked with a problem like this involving subset sums in C++ during a class last semester. (Modified version of this: http://www.cs.princeton.edu/courses/archive/spr03/cs226/assignments/password.html). But, that uses exact matching. Reading through the wikipedia page reminded me of that. For the subset sum problem you just need to be able to check for the existence of the some sum in one table that adds up to the total you are looking for when added to a sum in other table. This is basically the same, only instead of looking for equality you just check if it's in the limit and better than the previous best solution. (Eh, bug in my program above, had less than cap, should be less than or equal to; will fix it now).