1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
#include "dzilib.h"
#include <bits/stdc++.h>
using std::vector;
using u32 = std::uint32_t;
using u64 = std::uint64_t;
#define DEBUG(x) std::cerr << "Line " << __LINE__ << ": " << #x << " = " << x << "\n"
#define TRACE(x) std::cerr << "Line " << __LINE__ << ": " << #x "\n"

// Configuration.

constexpr bool randomize_offset = true;
constexpr u64 randomize_offset_limit = 10;
constexpr u64 rng_nonce = 0;
const u64 solve_primes[] = {2, 3};
// 200 MB
constexpr u64 divisor_limit = 50'000'000; // must be > 10^(17/3), 1e6+ OK

u64 choose_brute_limit(const u64 max_n, const u64 max_questions_per_test_case) {
  if (max_n <= 1'000'000'000 || max_questions_per_test_case >= 130) {
    return 500'000;
  } else if (max_questions_per_test_case >= 82) {
    return 2'000'000;
  } else if (max_questions_per_test_case >= 75) {
    return 4'000'000;
  } else {
    return 5'000'000;
  }
}

/// =================================

const std::uint32_t secret_key[8] = {
  235542195, 2150993683, 4252960442, 2004619671, 1424085794, 3389625356, 3726775613, 3633112236
};

namespace chacha_private {
  template <int shift>
  void rotate_left(std::uint32_t &x) {
    x = (x << shift) | (x >> (32 - shift));
  }

  inline void quarter_round(std::uint32_t &a, std::uint32_t &b, std::uint32_t &c, std::uint32_t &d) {
    a += b;
    d ^= a;
    rotate_left<16>(d);
    c += d;
    b ^= c;
    rotate_left<12>(b);
    a += b;
    d ^= a;
    rotate_left<8>(d);
    c += d;
    b ^= c;
    rotate_left<7>(b);
  }
}

template<int rounds>
void chacha(const std::uint32_t (&key)[8],
            const std::uint64_t nonce,
            const std::uint64_t counter,
            std::uint32_t (&output)[16])
{
  static_assert(rounds == 8 || rounds == 12 || rounds == 20);

  using namespace chacha_private;

  std::uint32_t input[16];
  std::memcpy(input + 0, "expand 32-byte k", 4 * sizeof(std::uint32_t));
  std::memcpy(input + 4, key, 8 * sizeof(std::uint32_t));
  std::memcpy(input + 12, &counter, 2 * sizeof(std::uint32_t));
  std::memcpy(input + 14, &nonce, 2 * sizeof(std::uint32_t));

  std::uint32_t x[16];
  std::memcpy(x, input, 16 * sizeof(std::uint32_t));

  for (int double_round = 0; double_round < rounds / 2; ++double_round) {
    quarter_round(x[0], x[4], x[8], x[12]);
    quarter_round(x[1], x[5], x[9], x[13]);
    quarter_round(x[2], x[6], x[10], x[14]);
    quarter_round(x[3], x[7], x[11], x[15]);

    quarter_round(x[0], x[5], x[10], x[15]);
    quarter_round(x[1], x[6], x[11], x[12]);
    quarter_round(x[2], x[7], x[8], x[13]);
    quarter_round(x[3], x[4], x[9], x[14]);
  }

  for (int i = 0; i < 16; ++i) {
    x[i] += input[i];
  }

  std::memcpy(output, x, 16 * sizeof(std::uint32_t));
}

class ChachaRandom {
public:
  using result_type = std::uint32_t;
  static constexpr result_type min() { return 0; }
  static constexpr result_type max() { return std::numeric_limits<result_type>::max(); }

  explicit ChachaRandom(const std::uint32_t (&key)[8], const std::uint64_t nonce);
  std::uint32_t operator()() {
    if (m_buffer_next == 16) {
      refill_buffer();
    }
    return m_buffer[m_buffer_next++];
  }

private:
  void refill_buffer();

  std::uint32_t m_chacha_key[8];
  std::uint64_t m_chacha_nonce = 0;
  std::uint64_t m_chacha_counter = 0;

  std::uint32_t m_buffer[16];
  int m_buffer_next = 16;
};

ChachaRandom::ChachaRandom(const std::uint32_t (&key)[8], const std::uint64_t nonce) {
  std::memcpy(m_chacha_key, key, 8 * sizeof(std::uint32_t));
  m_chacha_nonce = nonce;
}

void ChachaRandom::refill_buffer() {
  chacha<8>(m_chacha_key, m_chacha_nonce, m_chacha_counter++, m_buffer);
  m_buffer_next = 0;
}

// ====================================

struct FastDiv {
  u64 divisor;
  u64 shift;
  u64 m;

  FastDiv(u64 d) {
    divisor = d;
    u64 n = 1;
    while ((u64(1)<<n) < divisor) n += 1;

    m = (__uint128_t(1) << (64+n)) / divisor + 1;
    shift = n-1;
  }

  std::pair<u64, u64> divrem(u64 a) const {
    u64 t = (__uint128_t(m) * a) >> 64;
    u64 q = (t + ((a-t)>>1)) >> shift;
    u64 r = a - q * divisor;
    return {q, r};
  }
};

vector<u32> divisor_table;
vector<u32> primes;
vector<FastDiv> fast_divs;

void compute_primes() {
  divisor_table.assign(divisor_limit, 0);
  for (u64 p=2; p < divisor_limit; ++p) {
    if (divisor_table[p] != 0) continue;
    primes.push_back(p);
    fast_divs.push_back(FastDiv(p));
    divisor_table[p] = p;
    for (u64 x = p * p; x < divisor_limit; x += p) {
      if (divisor_table[x] == 0) {
        divisor_table[x] = p;
      }
    }
  }
}

u64 integer_sqrt(const u64 n) {
  u64 x = u64(std::sqrt(n));
  while (x * x > n) --x;
  while ((x+1) * (x+1) <= n) ++x;
  return x;
}

u64 integer_cube_root(const u64 n) {
  u64 x = u64(std::pow(n, 1.0/3));
  while (x * x * x > n) --x;
  while ((x+1) * (x+1) * (x+1) <= n) ++x;
  return x;
}

u64 mult_mod(const u64 a, const u64 b, const u64 m) {
  return __uint128_t(a) * __uint128_t(b) % m;
}

u64 power(u64 a, u64 b, u64 m) {
  u64 res = 1;
  while (b) {
    if (b&1u) res = mult_mod(res, a, m);
    b >>= 1;
    a = mult_mod(a, a, m);
  }
  return res;
}

bool miller_rabin(const u64 n, const u64 a) {
  u64 b = n-1;
  u64 s = 0;
  while (b%2 == 0) {
    b /= 2;
    ++s;
  }
  u64 x = power(a, b, n);
  for (u64 i=0; i<s; ++i) {
    const u64 y = mult_mod(x, x, n);
    if (y == 1 && x != 1 && x != n-1) {
      return false;
    }
    x = y;
  }
  if (x != 1) return false;
  return true;
}

bool large_prime_test(const u64 n) {
  for (const u64 p : primes) {
    if (p > 23) break;
    if (!miller_rabin(n, p)) return false;
  }
  return true;
}

bool is_prime(const u64 n) {
  if (n < divisor_limit) {
    return divisor_table[n] == n;
  } else {
    return large_prime_test(n);
  }
}

u64 compute_num_divisors(u64 n) {
  u64 result = 1;
  for (const u64 p : primes) {
    if (n < divisor_limit || p * p * p > n) break;
    if (n % p != 0) continue;
    u64 cnt = 1;
    n /= p;
    while (n % p == 0) {
      ++cnt;
      n /= p;
    }
    result *= (cnt + 1);
  }

  while (n > 1 && n < divisor_limit) {
    const u64 p = divisor_table[n];
    u64 cnt = 1;
    n /= p;
    while (n % p == 0) {
      ++cnt;
      n /= p;
    }
    result *= (cnt + 1);
  }

  if (n == 1) return result;
  const u64 a = integer_sqrt(n);
  if (a * a == n && is_prime(a)) {
    result *= 3;
  } else if (is_prime(n)) {
    result *= 2;
  } else {
    // n = p * q
    result *= 4;
  }
  return result;
}

// Returns 2 if may be false positive.
bool check_num_divisors(u64 n, u64 num_divisors) {
  if (n >= divisor_limit && num_divisors > 3) {
    u64 p_limit = integer_cube_root(n);
    for (u64 p_index = 0; p_index < primes.size(); ++p_index) {
      u64 p = primes[p_index];
      if (p > p_limit) break;
      const FastDiv &fast_div = fast_divs[p_index];
      auto [q, rem] = fast_div.divrem(n);
      if (rem != 0) continue;
      u64 cnt = 1;
      n = q;
      for (;;) {
        auto [q2, rem2] = fast_div.divrem(n);
        if (rem2 != 0) break;
        ++cnt;
        n = q2;
      }
      ++cnt;
      if (num_divisors % cnt != 0) return false;
      num_divisors /= cnt;
      if (n < divisor_limit || num_divisors <= 3) break;
      p_limit = integer_cube_root(n);
    }
  }

  while (n > 1 && n < divisor_limit) {
    const u64 p = divisor_table[n];
    u64 cnt = 1;
    n /= p;
    while (n % p == 0) {
      ++cnt;
      n /= p;
    }
    ++cnt;
    if (num_divisors % cnt != 0) return false;
    num_divisors /= cnt;
  }

  if (n == 1) return num_divisors == 1;
  if (num_divisors < 2 || num_divisors > 4) return false;
  const u64 a = integer_sqrt(n);
  if (a * a == n) {
    return num_divisors == 3;
  }
  if (num_divisors == 3) return false;
  
  return is_prime(n) == (num_divisors == 2);
}

u64 brute_compute_num_divisors(const u64 n) {
  u64 res = 0;
  u64 d = 1;
  for (; d*d < n; ++d) {
    if (n%d == 0) res += 2;
  }
  if (d*d==n) res += 1;
  return res;
}

bool is_power_of_2(const u32 n) {
  return n != 0 && (n & (n-1)) == 0;
}

ChachaRandom rng(secret_key, rng_nonce);

constexpr u64 none = -u64(1);

u64 max_offset;

// n = r (mod m)
struct Equation {
  u64 r;
  u64 m;
};

Equation trivial_equation() {
  return Equation{0, 1};
}

// n = r (mod p^k)
struct PowerEquation {
  u64 r;
  u64 p;
  u64 k;
};

Equation combine(Equation eq, const PowerEquation peq) {
  u64 pk = 1;
  for (u64 k = 1; k <= peq.k; ++k) {
    pk *= peq.p;
    while (eq.r % pk != peq.r % pk) {
      eq.r += eq.m;
    }
    eq.m *= peq.p;
  }
  return eq;
}

u64 find_offset_for(const Equation eq) {
  u64 offset = (eq.m - eq.r) % eq.m;
  assert(offset <= max_offset);
  if (randomize_offset) {
    u64 limit = std::min((max_offset - offset) / eq.m, randomize_offset_limit);
    std::uniform_int_distribution<u64> dist(0, limit);
    offset += eq.m * dist(rng);
  }
  return offset;
}

struct QuestionAnswer {
  u64 offset;
  u64 num_divisors;

  u64 difficulty() const {
    u64 odd_divisors = num_divisors;
    u64 pow2 = 0;
    while (odd_divisors % 2 == 0) { 
      odd_divisors /= 2;
      pow2++;
    }
    return -u64(1) - 100 * odd_divisors - pow2;
  }
};

QuestionAnswer ask_random_question() {
  std::uniform_int_distribution<u64> dist(0, max_offset);
  QuestionAnswer qa;
  qa.offset = dist(rng);
  qa.num_divisors = Ask(qa.offset);
  return qa;
}

bool matches(const QuestionAnswer qa, const u64 n) {
  return check_num_divisors(n + qa.offset, qa.num_divisors);
}

class PowerSolver {
public:
  explicit PowerSolver(const u64 p_): p(p_) {
    reset();
  }

  void reset() {
    options.clear();
    step = 1;
    p_step = p;
    if (is_power_of_2(k+step+1)) {
      step = 2;
      p_step = p * p;
    }

    for (u64 s = 0; s < p_step; ++s) {
      options.emplace(s, none);
    }
    refill_shots();
  }

  void refill_shots() {
    shots_remaining.clear();
    for (const auto [s, exception] : options) {
      for (u64 exc = 0; exc < p; ++exc) {
        if (exc == exception) continue;
        shots_remaining.emplace_back(s, exc);
      }
    }
    std::shuffle(shots_remaining.begin(), shots_remaining.end(), rng);
  }

  u64 known_range() const {
    return pk;
  }

  PowerEquation knowledge() const {
    return PowerEquation{r, p, k};
  }

  PowerEquation choose_question() {
    for (;;) {
      if (shots_remaining.empty()) {
        refill_shots();
      }

      const auto [s, exception] = shots_remaining.back();
      shots_remaining.pop_back();
      const auto it = options.find(s);
      if (it == options.end()) continue;
      // We wouldn't put it in the shots list.
      assert(it->second != exception);
      return PowerEquation{
        r + s * pk + exception * pk * p_step,
        p,
        k + step + 1
      };
    }
  }

  // Returns if significant progress.
  bool process_answer(const PowerEquation eq, const u64 num_divisors) {
    // If the remainder is valid mod p^(k+2), with one exception mod p^(k+3) we should have:
    // num_divisors is divisible by (k+3).
    // If this is not true, then we know an option is invalid.
    // If it is true, we learn nothing.
    if (num_divisors % (k + step + 1) == 0) {
      return false;
    }
    assert(eq.p == p && eq.k == k+step+1);
    const u64 s = eq.r / pk % p_step;
    const u64 exception = eq.r / (pk * p_step);

    const auto it = options.find(s);
    // We wouldn't ask a useless question.
    assert(it != options.end());
    if (it->second == none) {
      it->second = exception;
    } else {
      // We wouln't ask a useless question.
      assert(it->second != exception);
      options.erase(it);
      if (options.size() == 1) {
        upgrade();
        return true;
      }
    }
    return false;
  }

  void upgrade() {
    assert(options.size() == 1);
    const auto it = options.begin();
    const u64 s = it->first;
    r += s * pk;
    k += step;
    pk *= p_step;

    reset();
  }

private:
  // n = remainder (mod p^k)
  u64 p;
  u64 p_step; // p^step
  u64 step;
  u64 k = 0;
  u64 r = 0;
  u64 pk = 1; // p^k

  // maps s to exception, where:
  // s < p_step is such that n = r + s * p^k (mod p^(k+step))
  // exception < p is such that if s works, then:
  //   n = r + s * p^k + exception * p^(k+step) (mod p^(k+step+1))
  // exception can be none
  std::map<u64, u64> options;
  vector<std::pair<u64, u64>> shots_remaining;
};

class Solver {
public:
  explicit Solver(const u64 max_n1, const u64 brute_limit1) :
    max_n(max_n1),
    brute_limit(brute_limit1)
  {
    for (const u64 p : solve_primes) {
      solvers.emplace(p, PowerSolver(p));
    }
  }

  u64 solve() {
    phase_1();
    generate_n_options();
    phase_2();
    assert(n_options.size() == 1);
    return n_options[0];
  }

private:

  void phase_1() {
    for (;;) {
      if (phase_1_iteration()) {
        const u64 brute_size = max_n / known_range();
        if (brute_size <= brute_limit) {
          return;
        }
      }
    }
  }

  // Returns true if significant progress.
  bool phase_1_iteration() {
    const vector<PowerEquation> queries = generate_queries();

    Equation equation = trivial_equation();
    for (const PowerEquation &query : queries) {
      equation = combine(equation, query);
    }

    const u64 offset = find_offset_for(equation);
    const u64 num_divisors = Ask(offset);
    history.push_back(QuestionAnswer{offset, num_divisors});

    bool progress = false;
    for (const PowerEquation &query : queries) {
      const auto it = solvers.find(query.p);
      assert(it != solvers.end());
      PowerSolver &solver = it->second;
      if (solver.process_answer(query, num_divisors)) {
        progress = true;
      }
    }

    return progress;
  }

  u64 known_range() const {
    u64 range = 1;
    for (const auto &[p, solver] : solvers) {
      range *= solver.known_range();
    }
    return range;
  }

  vector<PowerEquation> generate_queries() {
    vector<PowerEquation> queries;

    for (auto &[p, solver] : solvers) {
      queries.push_back(solver.choose_question());
    }
    return queries;
  }

  Equation phase_1_solve() const {
    Equation total_knowledge = trivial_equation();
    for (const auto &[p, solver] : solvers) {
      const PowerEquation pe = solver.knowledge();
      total_knowledge = combine(total_knowledge, pe);
    }
    return total_knowledge;
  }

  void generate_n_options() {
    const Equation equation = phase_1_solve();
    u64 n = equation.r;
    if (n == 0) n += equation.m;
    for (;n <= max_n; n += equation.m) {
      n_options.push_back(n);
    }
  }

  void phase_2() {
    std::sort(history.begin(), history.end(),
        [](const QuestionAnswer a, const QuestionAnswer b) -> bool
        {
          return a.difficulty() < b.difficulty();
        }
    );

    for (const QuestionAnswer qa : history) {
      if (n_options.size() <= 1) return;
      filter_options(qa);
    }
    // Very unlikely this will happen.
    while (n_options.size() > 1) {
      const QuestionAnswer qa = ask_random_question();
      filter_options(qa);
    }
  }

  void filter_options(const QuestionAnswer qa) {
    auto it = std::remove_if(n_options.begin(), n_options.end(),
        [qa](const u64 n) -> bool {
          return !matches(qa, n);
        }
    );
    n_options.erase(it, n_options.end());
  }

  u64 max_n;
  u64 brute_limit;
  std::map<u64, PowerSolver> solvers;
  vector<QuestionAnswer> history;
  vector<u64> n_options;
};

void test_fast_div() {
  std::uniform_int_distribution<u64> dist{1, 1000000000000};
  std::uniform_int_distribution<u64> dist2{1, 1000000000000000};
  for (u64 i=0;i<1000;++i) {
    u64 d = dist(rng);
    FastDiv fd(d);
    u64 n = dist2(rng);
    assert((fd.divrem(n) == std::pair<u64, u64>{n/d, n%d}));
  }
}

void test_num_divisors() {
  for (u64 n=1; n<=1000000; ++n) {
    assert(brute_compute_num_divisors(n) == compute_num_divisors(n));
  }
  assert(compute_num_divisors(u64(100000007) * 100000007) == 3);
  assert(compute_num_divisors(u64(100000007) * 100000037) == 4);
  assert(compute_num_divisors(100000000000031) == 2);
}


int main() {
  compute_primes();

  const u64 ntc = GetT();
  const u64 max_n = GetN();
  const u64 max_questions = GetQ();
  max_offset = GetC();
  const u64 brute_limit = choose_brute_limit(max_n, max_questions / ntc);

  for (u64 tc = 0; tc < ntc; ++tc) {
    Solver solver(max_n, brute_limit);
    const u64 n = solver.solve();
    Answer(n);
  }
}