Minimum number of numbers to sum to exactly n

Pyth, 12 11 bytes

lhafqsTQyEY

This takes n as the first line of input and the list on the second line.

lhafqsTQyEY     (Implicit: Q = 1st line of input; E = 2nd line)
         E      The list
        yE      Powerset (sorted by increasing length; empty set first)
   f            Filter by lambda T:
     sT         sum(T)
    q                  ==
       Q                  Q
   fqSTQyE      Sublists that sum to Q, sorted by increasing length
  a       Y     append an empty array (in case none match)
lh              take the length of the first element (0 for empty array)

Try it here.


Japt, 30 21 18 bytes

Turns out there was a much more efficient method. ;)

Uà f_x ¥V} ml n- g

Test it online! (Note: n- has been changed to n@X-Y} for compatibility reasons)

This takes input as a space- or comma-separated array, followed by a number. Outputs undefined for test cases without solutions.

Uà f_  x ¥ V} ®   l} n- g
UàfmZ{Zx ==V} mZ{Zl} n- g

            // Implicit: U = input array, V = input integer
Uà fZ{   }  // Generate all possible combinations of U, then filter to only items Z where
Zx ==V      //   the sum of Z is equal to V.
mZ{Zl}      // Map each remaining combination to its length.
n-          // Sort by subtraction; smaller items end up in the front.
g           // Take the first item.
            // Implicit: output last expression

I can't believe I didn't think of this version when I originally wrote this...

Several optimizations have been made since then which come in handy here:

  • A U at the beginning of the program can usually be left out.
  • Ã is a shortcut for .
  • n now sorts numbers properly by default.

Each of these takes off a byte, for a total of 15:

à f_x ¥VÃml n g

Test it online!