Skip to content

Commit a09b218

Browse files
heplesserjstapmanns
andcommitted
Simplify code for finding first index exploiting mathematical simplification.
Co-authored-by: Jonas Stapmanns <[email protected]>
1 parent d518288 commit a09b218

File tree

1 file changed

+5
-13
lines changed

1 file changed

+5
-13
lines changed

libnestutil/numerics.cpp

+5-13
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,9 @@ first_index( long period, long phase0, long step, long phase )
233233
234234
k_j * step = k_0 * step + j * step * period / d mod lcm(step, period)
235235
236-
below and take the smallest; we call step * period / d the outer_step below.
236+
below and take the smallest. But since step * period / d = lcm(step, period),
237+
the term in j above vanishes and k_0 * step mod lcm(step, period) is actually
238+
the solution.
237239
238240
We do all calculations in signed long since we may encounter negative
239241
values during the algorithm. The result will be non-negative and returned
@@ -264,17 +266,7 @@ first_index( long period, long phase0, long step, long phase )
264266
const long d_phase_d = d_phase / d;
265267

266268
// Compute k_0 and multiply by step, see explanation in introductory comment
267-
long k_step = d_phase_d * mod_inverse( step_d, period_d ) * step;
269+
const long idx = ( d_phase_d * mod_inverse( step_d, period_d ) * step ) % std::lcm( period, step );
268270

269-
const long outer_period = std::lcm( period, step );
270-
const long outer_step = step * period_d;
271-
272-
long min_ix = k_step % outer_period;
273-
for ( size_t j = 1; j < d; ++j )
274-
{
275-
k_step += outer_step;
276-
min_ix = std::min( min_ix, k_step % outer_period );
277-
}
278-
279-
return static_cast< size_t >( min_ix );
271+
return static_cast< size_t >( idx );
280272
}

0 commit comments

Comments
 (0)