Let's say I have a batch process that executes 4 times per loop, and needs to execute a total of 9 items.


  • Iteration 1 executes 4 items of 9, leaving 5 left
  • Iteration 2 executes 4 times of 9, leaving 1 left
  • Iteration 3 only executes 1 item because that's all that is left.

Currently I handle it with a modulus operation:

$number_of_items = 9
$number_of_executions_per_loop = 4

For $iteration = 1 to $number_of_items Step $number_of_executions_per_loop
   If $number_of_items < ($iteration * $number_of_executions_per_loop) Then
      $iteration_execution_count = MOD($number_of_items,$number_of_executions_per_loop)
      $iteration_execution_count = $number_of_executions_per_loop



I am wondering if there is a cleaner way to handle these types of scenarios that I see frequently. Is there a math trick that can be done to determine how many items to execute?

  • 1
    (n+k-1)/k where / is integer division. – CodesInChaos Feb 18 '15 at 7:40

Judging by the dollar signs sprinkled in your code, you appear to be using some extremely high level and possibly highly inefficient script, so taking a MOD() is probably the least of your concerns, and what you do is just fine.

But if you really really want to simplify it, then you might want to consider something like the following:

number_of_items = 9
number_of_executions_per_loop = 4

For iteration = 1 to number_of_items Step number_of_executions_per_loop
   iteration_execution_count = number_of_executions_per_loop
   If iteration_execution_count > number_of_items - iteration Then
      iteration_execution_count = number_of_items - iteration



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.