@@ -233,7 +233,9 @@ first_index( long period, long phase0, long step, long phase )
233
233
234
234
k_j * step = k_0 * step + j * step * period / d mod lcm(step, period)
235
235
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.
237
239
238
240
We do all calculations in signed long since we may encounter negative
239
241
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 )
264
266
const long d_phase_d = d_phase / d;
265
267
266
268
// 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 ) ;
268
270
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 );
280
272
}
0 commit comments