Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

""" 

Utility classes for multi-modular algorithms 

""" 

  

#***************************************************************************** 

# Copyright (C) 2006 William Stein 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 2 of the License, or 

# (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

from __future__ import absolute_import 

  

from cysignals.memory cimport check_allocarray, check_reallocarray, sig_free 

  

from sage.libs.gmp.mpz cimport * 

from sage.rings.integer cimport Integer, smallInteger 

from sage.arith.all import random_prime 

from types import GeneratorType 

from sage.ext.stdsage cimport PY_NEW 

from cpython.object cimport PyObject_RichCompare 

  

# should I have mod_int versions of these functions? 

# c_inverse_mod_longlong modular inverse used exactly once in _refresh_precomputations 

from sage.rings.fast_arith cimport arith_llong 

cdef arith_llong ai 

ai = arith_llong() 

  

# This is the maximum modulus for the code in this module, i.e. the 

# largest prime that can be used as modulus is 

# previous_prime(MAX_MODULUS) 

MAX_MODULUS = MOD_INT_MAX 

  

  

cdef class MultiModularBasis_base(object): 

r""" 

This class stores a list of machine-sized prime numbers, 

and can do reduction and Chinese Remainder Theorem lifting 

modulo these primes. 

  

Lifting implemented via Garner's algorithm, which has the advantage 

that all reductions are word-sized. For each `i`, precompute 

`\prod_j=1^{i-1} m_j` and `\prod_j=1^{i-1} m_j^{-1} (mod m_i)`. 

  

This class can be initialized in two ways, either with a list of prime 

moduli or an upper bound for the product of the prime moduli. The prime 

moduli are generated automatically in the second case. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([3, 5, 7]); mm 

MultiModularBasis with moduli [3, 5, 7] 

  

sage: height = 52348798724 

sage: mm = MultiModularBasis_base(height); mm 

MultiModularBasis with moduli [4561, 17351, 28499] 

sage: mm = MultiModularBasis_base(height); mm 

MultiModularBasis with moduli [32573, 4339, 30859] 

sage: mm = MultiModularBasis_base(height); mm 

MultiModularBasis with moduli [16451, 14323, 28631] 

  

sage: mm.prod()//height 

128 

  

TESTS:: 

  

sage: mm = MultiModularBasis_base((3,5,7)); mm 

MultiModularBasis with moduli [3, 5, 7] 

sage: mm = MultiModularBasis_base(primes(10,20)); mm 

MultiModularBasis with moduli [11, 13, 17, 19] 

  

There is no overflow if the modulus is below ``MAX_MODULUS``:: 

  

sage: from sage.arith.multi_modular import MAX_MODULUS 

sage: p0 = previous_prime(MAX_MODULUS) 

sage: p1 = previous_prime(p0) 

sage: MultiModularBasis_base([p0, p1]).crt([p0-1, p1-1]) 

-1 

  

If we add another bit to the prime length then there is an 

overflow, as expected:: 

  

sage: p0 = previous_prime(2*MAX_MODULUS) 

sage: p1 = previous_prime(p0) 

sage: MultiModularBasis_base([p0, p1]).crt([p0-1, p1-1]) 

Traceback (most recent call last): 

... 

OverflowError: given modulus 6074000981 is larger than 3037000498 

""" 

def __cinit__(self): 

r""" 

Allocate the space for the moduli and precomputation lists 

and initialize the first element of that list. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([1099511627791]) 

Traceback (most recent call last): 

... 

OverflowError: given modulus 1099511627791 is larger than 3037000498 

""" 

mpz_init(self.product) 

mpz_init(self.half_product) 

  

cdef _realloc_to_new_count(self, new_count): 

self.moduli = <mod_int*>check_reallocarray(self.moduli, new_count, sizeof(mod_int)) 

self.partial_products = <mpz_t*>check_reallocarray(self.partial_products, new_count, sizeof(mpz_t)) 

self.C = <mod_int*>check_reallocarray(self.C, new_count, sizeof(mod_int)) 

  

def __dealloc__(self): 

""" 

TESTS:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base(1099511627791); mm 

MultiModularBasis with moduli [4561, 17351, 28499] 

sage: del mm 

""" 

sig_free(self.moduli) 

for i in range(self.n): 

mpz_clear(self.partial_products[i]) 

sig_free(self.partial_products) 

sig_free(self.C) 

mpz_clear(self.product) 

mpz_clear(self.half_product) 

  

def __init__(self, val, unsigned long l_bound=2**10, unsigned long u_bound=2**15): 

r""" 

Initialize a multi-modular basis and perform precomputations. 

  

INPUT: 

  

- ``val`` -- as integer 

determines how many primes are computed 

(their product will be at least 2*val) 

as list, tuple or generator 

a list of prime moduli to start with 

- ``l_bound`` -- an integer: lower bound for the random primes 

(default: 2^10) 

- ``u_bound`` -- an integer: upper bound for the random primes 

(default: 2^15) 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([1009, 10007]); mm 

MultiModularBasis with moduli [1009, 10007] 

sage: mm.prod() 

10097063 

  

sage: height = 10097063 

sage: mm = MultiModularBasis_base(height); mm 

MultiModularBasis with moduli [...] 

  

sage: mm.prod()//height > 2 

True 

  

sage: mm = MultiModularBasis_base([1000000000000000000000000000057]) 

Traceback (most recent call last): 

... 

OverflowError: given modulus 1000000000000000000000000000057 is larger than 3037000498 

  

sage: mm = MultiModularBasis_base(0); mm 

MultiModularBasis with moduli [28499] 

  

sage: mm = MultiModularBasis_base([6, 10]) 

Traceback (most recent call last): 

... 

ArithmeticError: The inverse of 6 modulo 10 is not defined. 

""" 

if l_bound < 2: 

raise ValueError(f"minimum value for lower bound is 2, given: {l_bound}") 

if u_bound > MAX_MODULUS: 

raise ValueError(f"upper bound cannot be greater than {MAX_MODULUS}, given: {u_bound}") 

  

self._l_bound = l_bound 

self._u_bound = u_bound 

  

from sage.functions.prime_pi import prime_pi # must be here to avoid circular import 

self._num_primes = prime_pi(self._u_bound) - prime_pi(self._l_bound-1) 

  

if isinstance(val, (list, tuple, GeneratorType)): 

self.extend_with_primes(val, check=True) 

else: 

self._extend_moduli_to_height(val) 

  

cdef mod_int _new_random_prime(self, set known_primes) except 1: 

""" 

Choose a new random prime for inclusion in the list of moduli, 

or raise a ``RuntimeError`` if there are no more primes. 

  

INPUT: 

  

- ``known_primes`` -- Python set of already known primes in 

the allowed interval; we will not return a prime in 

known_primes. 

""" 

cdef Py_ssize_t i 

cdef mod_int p 

while True: 

if len(known_primes) >= self._num_primes: 

raise RuntimeError("there are not enough primes in the interval [%s, %s] to complete this multimodular computation"%(self._l_bound, self._u_bound)) 

p = random_prime(self._u_bound, lbound =self._l_bound) 

if p not in known_primes: 

return p 

  

def extend_with_primes(self, plist, partial_products = None, check=True): 

""" 

Extend the stored list of moduli with the given primes in ``plist``. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([1009, 10007]); mm 

MultiModularBasis with moduli [1009, 10007] 

sage: mm.extend_with_primes([10037, 10039]) 

4 

sage: mm 

MultiModularBasis with moduli [1009, 10007, 10037, 10039] 

""" 

if isinstance(plist, GeneratorType): 

plist = list(plist) 

elif not isinstance(plist, (tuple, list)): 

raise TypeError("plist should be a list, tuple or a generator, got: %s"%(str(type(plist)))) 

  

cdef Py_ssize_t len_plist = len(plist) 

  

if len_plist == 0: 

return self.n 

if check: 

for p in plist: 

if p > MAX_MODULUS: 

raise OverflowError(f"given modulus {p} is larger than {MAX_MODULUS}") 

self._realloc_to_new_count(self.n + len_plist) 

  

cdef Py_ssize_t i 

for i in range(len_plist): 

self.moduli[self.n+i] = plist[i] 

mpz_init(self.partial_products[self.n + i]) 

if partial_products: 

mpz_set(self.partial_products[self.n + i], 

(<Integer>partial_products[i]).value) 

  

cdef int old_count = self.n 

self.n += len_plist 

if not partial_products: 

self._refresh_products(old_count) 

else: 

self._refresh_prod() 

self._refresh_precomputations(old_count) 

return self.n 

  

def __richcmp__(self, other, int op): 

""" 

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([10007]) 

sage: nn = MultiModularBasis_base([10007]) 

sage: mm == nn 

True 

""" 

if not isinstance(other, MultiModularBasis_base): 

return NotImplemented 

left = self.__getstate__() 

right = other.__getstate__() 

return PyObject_RichCompare(left, right, op) 

  

def __setstate__(self, state): 

""" 

Initialize a new :class:`MultiModularBasis_base` object from a 

state stored in a pickle. 

  

TESTS:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([10007, 10009]) 

sage: mm == loads(dumps(mm)) 

True 

  

sage: mm = MultiModularBasis_base([]) 

sage: mm.__setstate__(([10007, 10009], 2^10, 2^15)) 

  

sage: mm 

MultiModularBasis with moduli [10007, 10009] 

""" 

nmoduli, lbound, ubound = state 

self._realloc_to_new_count(len(nmoduli)) 

self._l_bound = lbound 

self._u_bound = ubound 

self.extend_with_primes(nmoduli, check=False) 

  

def __getstate__(self): 

""" 

Return a tuple describing the state of this object for pickling. 

  

TESTS:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([10007, 10009]) 

sage: mm.__getstate__() 

([10007, 10009], 1024L, 32768L) 

""" 

return (self.list(), self._l_bound, self._u_bound) 

  

def _extend_moduli_to_height(self, height): 

""" 

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base(0); mm 

MultiModularBasis with moduli [4561] 

  

sage: mm._extend_moduli_to_height(10000) 

sage: mm 

MultiModularBasis with moduli [4561, 17351] 

  

sage: mm = MultiModularBasis_base([46307]); mm 

MultiModularBasis with moduli [46307] 

  

sage: mm._extend_moduli_to_height(10^30); mm 

MultiModularBasis with moduli [46307, 28499, 32573, 4339, 30859, 16451, 14323, 28631] 

  

TESTS: 

  

Verify that :trac:`11358` is fixed:: 

  

sage: set_random_seed(0); m = sage.arith.multi_modular.MultiModularBasis_base(0) 

sage: m._extend_moduli_to_height(prod(prime_range(50))) 

sage: m = sage.arith.multi_modular.MultiModularBasis_base([],2,100) 

sage: m._extend_moduli_to_height(prod(prime_range(90))) 

sage: m._extend_moduli_to_height(prod(prime_range(150))) 

Traceback (most recent call last): 

... 

RuntimeError: there are not enough primes in the interval [2, 100] to complete this multimodular computation 

  

Another check (which fails horribly before :trac:`11358` is fixed):: 

  

sage: set_random_seed(0); m = sage.arith.multi_modular.MultiModularBasis_base(0); m._extend_moduli_to_height(10**10000) 

sage: len(set(m)) == len(m) 

True 

sage: len(m) 

2438 

""" 

cdef Integer h = Integer(height) 

if h < self._l_bound: 

h = Integer(self._l_bound) 

self._extend_moduli_to_height_c(h.value) 

  

cdef int _extend_moduli_to_height_c(self, mpz_t height0) except -1: 

r""" 

Expand the list of primes and perform precomputations. 

  

INPUT: 

  

- ``height`` -- determines how many primes are computed 

(their product must be at least 2*height) 

""" 

# real height we use is twice the given, set height to 2*height0 

cdef mpz_t height 

mpz_init(height) 

mpz_mul_2exp(height, height0, 1) 

# check if we already have enough prime moduli 

if self.n > 0 and mpz_cmp(height, self.partial_products[self.n-1]) <= 0: 

mpz_clear(height) 

return self.n 

  

# find new prime moduli 

cdef int i 

new_moduli = [] 

new_partial_products = [] 

cdef Integer M # keeps current height 

cdef mod_int p # keeps current prime moduli 

  

if self.n == 0: 

M = smallInteger(1) 

else: 

M = PY_NEW(Integer) 

mpz_set(M.value, self.partial_products[self.n-1]) 

  

known_primes = set(self) 

while mpz_cmp(height, M.value) > 0: 

p = self._new_random_prime(known_primes) 

new_moduli.append(p) 

known_primes.add(p) 

M *= p 

new_partial_products.append(M) 

mpz_clear(height) 

return self.extend_with_primes(new_moduli, new_partial_products, 

check=False) 

  

def _extend_moduli_to_count(self, int count): 

r""" 

Expand the list of primes and perform precomputations. 

  

INPUT: 

  

- ``count`` -- the minimum number of moduli in the resulting list 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([46307]); mm 

MultiModularBasis with moduli [46307] 

sage: mm._extend_moduli_to_count(3) 

3 

sage: mm 

MultiModularBasis with moduli [46307, 4561, 17351] 

""" 

if count <= self.n: 

return self.n 

new_moduli = [] 

  

cdef int i 

cdef mod_int p 

known_primes = set(self) 

for i in range(self.n, count): 

p = self._new_random_prime(known_primes) 

known_primes.add(p) 

new_moduli.append(p) 

  

return self.extend_with_primes(new_moduli, check=False) 

  

def _extend_moduli(self, count): 

""" 

Expand the list of prime moduli with `count` new random primes. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([46307]); mm 

MultiModularBasis with moduli [46307] 

sage: mm._extend_moduli(2); mm 

MultiModularBasis with moduli [46307, 4561, 17351] 

""" 

self._extend_moduli_to_count(self.n + count) 

  

cdef void _refresh_products(self, int start): 

r""" 

Compute and store `\prod_j=1^{i-1} m_j` for i > start. 

""" 

cdef mpz_t z 

mpz_init(z) 

if start == 0: 

mpz_set_si(self.partial_products[0], self.moduli[0]) 

start += 1 

for i in range(start, self.n): 

mpz_set_si(z, self.moduli[i]) 

mpz_mul(self.partial_products[i], self.partial_products[i-1], z) 

mpz_clear(z) 

self._refresh_prod() 

  

cdef void _refresh_prod(self): 

# record the product and half product for balancing the lifts. 

mpz_set(self.product, self.partial_products[self.n-1]) 

mpz_fdiv_q_ui(self.half_product, self.product, 2) 

  

cdef void _refresh_precomputations(self, int start) except *: 

r""" 

Compute and store `\prod_j=1^{i-1} m_j^{-1} (mod m_i)` for i >= start. 

""" 

if start == 0: 

start = 1 # first one is trivial, never used 

self.C[0] = 1 

for i in range(start, self.n): 

self.C[i] = ai.c_inverse_mod_longlong(mpz_fdiv_ui(self.partial_products[i-1], self.moduli[i]), self.moduli[i]) 

  

cdef int min_moduli_count(self, mpz_t height) except -1: 

r""" 

Compute the minimum number of primes needed to uniquely determine 

an integer mod height. 

""" 

self._extend_moduli_to_height_c(height) 

  

cdef int count 

count = self.n * mpz_sizeinbase(height, 2) / mpz_sizeinbase(self.partial_products[self.n-1], 2) # an estimate 

count = max(min(count, self.n), 1) 

while count > 1 and mpz_cmp(height, self.partial_products[count-1]) < 0: 

count -= 1 

while mpz_cmp(height, self.partial_products[count-1]) > 0: 

count += 1 

  

return count 

  

cdef mod_int last_prime(self): 

return self.moduli[self.n-1] 

  

cdef int mpz_reduce_tail(self, mpz_t z, mod_int* b, int offset, int len) except -1: 

r""" 

Perform reduction mod `m_i` for offset <= i < len. 

  

`b[i] = z mod m_{i+offset}` for 0 <= i < len 

  

INPUT: 

  

- ``z`` - the integer being reduced 

- ``b`` - array to hold the reductions mod each m_i. 

It MUST be allocated and have length at least len 

- ``offset`` - first prime in list to reduce against 

- ``len`` - number of primes in list to reduce against 

""" 

cdef int i 

cdef mod_int* m 

m = self.moduli + offset 

for i in range(len): 

b[i] = mpz_fdiv_ui(z, m[i]) 

return 0 

  

cdef int mpz_reduce_vec_tail(self, mpz_t* z, mod_int** b, int vn, int offset, int len) except -1: 

r""" 

Perform reduction mod `m_i` for offset <= i < len. 

  

`b[i][j] = z[j] mod m_{i+offset}` for 0 <= i < len 

  

INPUT: 

  

- ``z`` - an array of integers being reduced 

- ``b`` - array to hold the reductions mod each m_i. 

It MUST be fully allocated and each 

have length at least len 

- ``vn`` - length of z and each b[i] 

- ``offset`` - first prime in list to reduce against 

- ``len`` - number of primes in list to reduce against 

""" 

cdef int i, j 

cdef mod_int* m 

m = self.moduli + offset 

for i in range(len): 

mi = m[i] 

for j in range(vn): 

b[i][j] = mpz_fdiv_ui(z[j], mi) 

return 0 

  

cdef int mpz_crt_tail(self, mpz_t z, mod_int* b, int offset, int len) except -1: 

r""" 

Calculate lift mod `\prod_{i=0}^{offset+len-1} m_i`. 

  

z = b[i] mod `m_{i+offset}` for 0 <= i < len 

  

In the case that offset > 0, 

z remains unchanged mod `\prod_{i=0}^{offset-1} m_i` 

  

INPUT: 

  

- ``z`` - a placeholder for the constructed integer 

z MUST be initialized IF and ONLY IF offset > 0 

- ``b`` - array holding the reductions mod each m_i. 

It MUST have length at least len 

- ``offset`` - first prime in list to reduce against 

- ``len`` - number of primes in list to reduce against 

""" 

cdef int i, s 

cdef mpz_t u 

cdef mod_int* m 

m = self.moduli + offset 

mpz_init(u) 

if offset == 0: 

s = 1 

mpz_init_set_si(z, b[0]) 

if b[0] == 0: 

while s < len and b[s] == 0: # fast forward to first non-zero 

s += 1 

else: 

s = 0 

for i in range(s, len): 

mpz_set_si(u, ((b[i] + m[i] - mpz_fdiv_ui(z, m[i])) * self.C[i]) % m[i]) 

mpz_mul(u, u, self.partial_products[i-1]) 

mpz_add(z, z, u) 

  

# normalize to be between -prod/2 and prod/2. 

if mpz_cmp(z, self.half_product) > 0: 

mpz_sub(z, z, self.product) 

mpz_clear(u) 

return 0 

  

cdef int mpz_crt_vec_tail(self, mpz_t* z, mod_int** b, int vc, int offset, int len) except -1: 

r""" 

Calculate lift mod `\prod_{i=0}^{offset+len-1} m_i`. 

  

`z[j] = b[i][j] mod m_{i+offset}` for 0 <= i < len 

  

In the case that offset > 0, 

z[j] remains unchanged mod `\prod_{i=0}^{offset-1} m_i` 

  

INPUT: 

  

- ``z`` - a placeholder for the constructed integers 

z MUST be allocated and have length at least vc 

z[j] MUST be initialized IF and ONLY IF offset > 0 

- ``b`` - array holding the reductions mod each m_i. 

MUST have length at least len 

- ``vn`` - length of z and each b[i] 

- ``offset`` - first prime in list to reduce against 

- ``len`` - number of primes in list to reduce against 

""" 

cdef int i, j 

cdef mpz_t u 

cdef mod_int* m 

  

m = self.moduli + offset 

mpz_init(u) 

if offset == 0: 

s = 1 

else: 

s = 0 

  

for j in range(vc): 

i = s 

if offset == 0: 

mpz_set_si(z[j], b[0][j]) 

if b[0][j] == 0: 

while i < len and b[i][j] == 0: # fast forward to first non-zero 

i += 1 

while i < len: 

mpz_set_si(u, ((b[i][j] + m[i] - mpz_fdiv_ui(z[j], m[i])) * self.C[i]) % m[i]) # u = ((b_i - z) * C_i) % m_i 

mpz_mul(u, u, self.partial_products[i-1]) 

mpz_add(z[j], z[j], u) 

i += 1 

  

# normalize to be between -prod/2 and prod/2. 

if mpz_cmp(z[j], self.half_product) > 0: 

mpz_sub(z[j], z[j], self.product) 

  

  

cdef Integer zz 

zz = PY_NEW(Integer) 

mpz_set(zz.value, self.half_product) 

  

mpz_clear(u) 

return 0 

  

def crt(self, b): 

r""" 

Calculate lift mod `\prod_{i=0}^{len(b)-1} m_i`. 

  

In the case that offset > 0, 

z[j] remains unchanged mod `\prod_{i=0}^{offset-1} m_i` 

  

INPUT: 

  

- ``b`` - a list of length at most self.n 

  

OUTPUT: 

  

Integer z where `z = b[i] mod m_i` for 0 <= i < len(b) 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([10007, 10009, 10037, 10039, 17351]) 

sage: res = mm.crt([3,5,7,9]); res 

8474803647063985 

sage: res % 10007 

3 

sage: res % 10009 

5 

sage: res % 10037 

7 

sage: res % 10039 

9 

  

""" 

cdef int i, n 

n = len(b) 

if n > self.n: 

raise IndexError("beyond bound for multi-modular prime list") 

cdef mod_int* bs 

bs = <mod_int*>check_allocarray(n, sizeof(mod_int)) 

for i in range(n): 

bs[i] = b[i] 

cdef Integer z 

z = PY_NEW(Integer) 

self.mpz_crt_tail(z.value, bs, 0, n) 

sig_free(bs) 

return z 

  

def precomputation_list(self): 

""" 

Return a list of the precomputed coefficients 

`\prod_j=1^{i-1} m_j^{-1} (mod m_i)` 

where `m_i` are the prime moduli. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([46307, 10007]); mm 

MultiModularBasis with moduli [46307, 10007] 

sage: mm.precomputation_list() 

[1, 4013] 

""" 

return [Integer(self.C[i]) for i in range(self.n)] 

  

def partial_product(self, n): 

""" 

Return a list containing precomputed partial products. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([46307, 10007]); mm 

MultiModularBasis with moduli [46307, 10007] 

sage: mm.partial_product(0) 

46307 

sage: mm.partial_product(1) 

463394149 

  

TESTS:: 

  

sage: mm.partial_product(2) 

Traceback (most recent call last): 

... 

IndexError: beyond bound for multi-modular prime list 

sage: mm.partial_product(-2) 

Traceback (most recent call last): 

... 

IndexError: negative index not valid 

  

""" 

if n >= self.n: 

raise IndexError("beyond bound for multi-modular prime list") 

if n < 0: 

raise IndexError("negative index not valid") 

cdef Integer z 

z = PY_NEW(Integer) 

mpz_set(z.value, self.partial_products[n]) 

return z 

  

def prod(self): 

""" 

Return the product of the prime moduli. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([46307]); mm 

MultiModularBasis with moduli [46307] 

sage: mm.prod() 

46307 

sage: mm = MultiModularBasis_base([46307, 10007]); mm 

MultiModularBasis with moduli [46307, 10007] 

sage: mm.prod() 

463394149 

  

TESTS:: 

  

sage: mm = MultiModularBasis_base([]); mm 

MultiModularBasis with moduli [] 

sage: len(mm) 

0 

sage: mm.prod() 

1 

""" 

if self.n == 0: 

return 1 

cdef Integer z 

z = PY_NEW(Integer) 

mpz_set(z.value, self.partial_products[self.n-1]) 

return z 

  

def list(self): 

""" 

Return a list with the prime moduli. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([46307, 10007]) 

sage: mm.list() 

[46307, 10007] 

""" 

return [Integer(self.moduli[i]) for i in range(self.n)] 

  

def __len__(self): 

""" 

Returns the number of moduli stored. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([10007]) 

sage: len(mm) 

1 

sage: mm._extend_moduli_to_count(2) 

2 

sage: len(mm) 

2 

""" 

return self.n 

  

def __iter__(self): 

""" 

Return an iterator over the prime moduli. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([10007, 10009]) 

sage: t = iter(mm); t 

<list...iterator object at ...> 

sage: list(mm.__iter__()) 

[10007, 10009] 

""" 

return iter(self.list()) 

  

def __getitem__(self, ix): 

""" 

Return the moduli stored at index `ix` as a Python long. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: mm = MultiModularBasis_base([10007, 10009]) 

sage: mm[1] 

10009 # 64-bit 

10009L # 32-bit 

sage: mm[-1] 

Traceback (most recent call last): 

... 

IndexError: index out of range 

  

sage: mm[:1] 

MultiModularBasis with moduli [10007] 

""" 

if isinstance(ix, slice): 

return self.__class__(self.list()[ix], l_bound = self._l_bound, 

u_bound = self._u_bound) 

  

cdef Py_ssize_t i = ix 

if i != ix: 

raise TypeError("index must be an integer") 

if i < 0 or i >= self.n: 

raise IndexError("index out of range") 

return self.moduli[i] 

  

def __repr__(self): 

""" 

Return a string representation of this object. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MultiModularBasis_base 

sage: MultiModularBasis_base([10007]) 

MultiModularBasis with moduli [10007] 

""" 

return "MultiModularBasis with moduli "+str(self.list()) 

  

  

cdef class MultiModularBasis(MultiModularBasis_base): 

""" 

Class used for storing a MultiModular bases of a fixed length. 

""" 

cdef int mpz_reduce(self, mpz_t z, mod_int* b) except -1: 

r""" 

Perform reduction mod `m_i` for each modulus `m_i`. 

  

`b[i] = z mod m_i` for 0 <= i < len(self) 

  

INPUT: 

  

- ``z`` -- the integer being reduced 

- ``b`` -- array to hold the reductions mod each m_i. 

It MUST be allocated and have length at least len 

""" 

self.mpz_reduce_tail(z, b, 0, self.n) 

  

cdef int mpz_reduce_vec(self, mpz_t* z, mod_int** b, int vn) except -1: 

r""" 

Perform reduction mod `m_i` for each modulus `m_i`. 

  

`b[i][j] = z[j] mod m_i` for 0 <= i < len(self) 

  

INPUT: 

  

- ``z`` -- an array of integers being reduced 

- ``b`` -- array to hold the reductions mod each m_i. 

It MUST be fully allocated and each 

have length at least len 

- ``vn`` -- length of z and each b[i] 

""" 

self.mpz_reduce_vec_tail(z, b, vn, 0, self.n) 

  

cdef int mpz_crt(self, mpz_t z, mod_int* b) except -1: 

r""" 

Calculate lift mod `\prod m_i`. 

  

`z = b[i] mod m_{i+offset}` for 0 <= i < len(self) 

  

INPUT: 

  

- ``z`` -- a placeholder for the constructed integer 

z MUST NOT be initialized 

- ``b`` -- array holding the reductions mod each `m_i`. 

It MUST have length at least len(self) 

""" 

self.mpz_crt_tail(z, b, 0, self.n) 

  

cdef int mpz_crt_vec(self, mpz_t* z, mod_int** b, int vn) except -1: 

r""" 

Calculate lift mod `\prod m_i`. 

  

`z[j] = b[i][j] mod m_i` for 0 <= i < len(self) 

  

INPUT: 

  

- ``z`` -- a placeholder for the constructed integers 

z MUST be allocated and have length at least vn, 

but each z[j] MUST NOT be initialized 

- ``b`` -- array holding the reductions mod each `m_i`. 

It MUST have length at least len(self) 

- ``vn`` -- length of z and each b[i] 

""" 

self.mpz_crt_vec_tail(z, b, vn, 0, self.n) 

  

  

cdef class MutableMultiModularBasis(MultiModularBasis): 

""" 

Class used for performing multi-modular methods, 

with the possibility of removing bad primes. 

""" 

cpdef mod_int next_prime(self) except -1: 

""" 

Pick a new random prime between the bounds given during the 

initialization of this object, update the precomputed data, 

and return the new prime modulus. 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MutableMultiModularBasis 

sage: mm = MutableMultiModularBasis([10007]) 

sage: mm.next_prime() 

4561 # 64-bit 

4561L # 32-bit 

sage: mm 

MultiModularBasis with moduli [10007, 4561] 

""" 

self._extend_moduli(1) 

return self.moduli[self.n-1] 

  

cpdef mod_int replace_prime(self, int ix) except -1: 

""" 

Replace the prime moduli at the given index with a different one, 

update the precomputed data accordingly, and return the new prime. 

  

INPUT: 

  

- ``ix`` -- index into list of moduli 

  

OUTPUT: the new prime modulus 

  

EXAMPLES:: 

  

sage: from sage.arith.multi_modular import MutableMultiModularBasis 

sage: mm = MutableMultiModularBasis([10007, 10009, 10037, 10039]) 

sage: mm 

MultiModularBasis with moduli [10007, 10009, 10037, 10039] 

sage: mm.prod() 

10092272478850909 

sage: mm.precomputation_list() 

[1, 5004, 6536, 6060] 

sage: mm.partial_product(2) 

1005306552331 

sage: mm.replace_prime(1) 

4561 # 64-bit 

4561L # 32-bit 

sage: mm 

MultiModularBasis with moduli [10007, 4561, 10037, 10039] 

sage: mm.prod() 

4598946425820661 

sage: mm.precomputation_list() 

[1, 2314, 3274, 3013] 

sage: mm.partial_product(2) 

458108021299 

""" 

cdef mod_int new_p 

  

if ix < 0 or ix >= self.n: 

raise IndexError("index out of range") 

  

new_p = self._new_random_prime(set(self)) 

self.moduli[ix] = new_p 

  

self._refresh_products(ix) 

self._refresh_precomputations(ix) 

return new_p