# How to obtain the minimal index n in a list (A) so that Total[A[[1;;n]]] is bigger than a specific value m?

Imagine the A array is {1,2,3,4,5,1,2} and m = 4. Then in this case, Total[A[[1;;3]]] is 6, so 3 is the minimal index that the summation of the first n elements are bigger than 4. I try to do it using For loop but it's not efficient.

• Welcome to Mathematica.SE! I suggest the following: 1) As you receive help, try to give it too, by answering questions in your area of expertise. 2) Take the tour and check the faqs! 3) When you see good questions and answers, vote them up by clicking the gray triangles, because the credibility of the system is based on the reputation gained by users sharing their knowledge. Also, please remember to accept the answer, if any, that solves your problem, by clicking the checkmark sign! – Dunlop Oct 24 '19 at 18:20

This is a problem where function LengthWhile is very useful:

findIndex[list_List, m_?NumericQ] := Module[{sum = 0},
LengthWhile[list, (sum += #) <= m &] + 1
];
findIndex[{1, 2, 3, 4, 5, 1, 2}, 4]


3

If you're instead interested in the elements of the list, use TakeWhile instead.

Is this what you are looking for?

m = 4;
LengthWhile[Accumulate@A, # < m &] + 1


3

A = Range[5]~Join~{1, 2};
m = 4;

sums = FoldList[Plus, A]
method1 = Position[sums < m // Thread, False][[1, 1]]
method2 = Total@Boole[sums < m // Thread] + 1;
method3 = Total@UnitStep[m - sums] + 1;
method1 == method2 == method3


{1, 3, 6, 10, 15, 16, 18}

3

True