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

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

2259

2260

2261

2262

2263

2264

2265

2266

2267

2268

2269

2270

2271

2272

2273

2274

2275

2276

2277

2278

2279

2280

2281

2282

2283

2284

2285

2286

2287

2288

2289

2290

2291

2292

2293

2294

2295

2296

2297

2298

2299

2300

2301

2302

2303

2304

2305

2306

2307

2308

2309

2310

2311

2312

2313

2314

2315

2316

2317

2318

2319

2320

2321

2322

2323

2324

2325

2326

2327

2328

2329

2330

2331

2332

2333

2334

2335

2336

2337

2338

2339

2340

2341

2342

2343

2344

2345

2346

2347

2348

2349

2350

2351

2352

2353

2354

2355

2356

2357

2358

2359

2360

2361

2362

2363

2364

2365

2366

2367

2368

2369

2370

2371

2372

2373

2374

2375

2376

2377

2378

2379

2380

2381

2382

2383

2384

2385

2386

2387

2388

2389

2390

2391

2392

2393

2394

2395

2396

2397

2398

2399

2400

2401

2402

2403

2404

2405

2406

2407

2408

2409

2410

2411

2412

2413

2414

2415

2416

2417

2418

2419

2420

2421

2422

2423

2424

2425

2426

2427

2428

2429

2430

2431

2432

2433

2434

2435

2436

2437

2438

2439

2440

2441

2442

2443

2444

2445

2446

2447

2448

2449

2450

2451

2452

2453

2454

2455

2456

2457

2458

2459

2460

2461

2462

2463

2464

2465

2466

2467

2468

2469

2470

2471

2472

2473

2474

2475

2476

2477

2478

2479

2480

2481

2482

2483

2484

2485

2486

2487

2488

2489

2490

2491

2492

2493

2494

2495

2496

2497

2498

2499

2500

2501

2502

2503

2504

2505

2506

2507

2508

2509

2510

2511

2512

2513

2514

2515

2516

2517

2518

2519

2520

2521

2522

2523

2524

2525

2526

2527

2528

2529

2530

2531

2532

2533

2534

2535

2536

2537

2538

2539

2540

2541

2542

2543

2544

2545

2546

2547

2548

2549

2550

2551

2552

2553

2554

2555

2556

2557

2558

2559

2560

2561

2562

2563

2564

2565

2566

2567

2568

2569

2570

2571

2572

2573

2574

2575

2576

2577

2578

2579

2580

2581

2582

2583

2584

2585

2586

2587

2588

2589

2590

2591

2592

2593

2594

2595

2596

2597

2598

2599

2600

2601

2602

2603

2604

2605

2606

2607

2608

2609

2610

2611

2612

2613

2614

2615

2616

2617

2618

2619

2620

2621

2622

2623

2624

2625

2626

2627

2628

2629

2630

2631

2632

2633

2634

2635

2636

2637

2638

2639

2640

2641

2642

2643

2644

2645

2646

2647

2648

2649

2650

2651

2652

2653

2654

2655

2656

2657

2658

2659

2660

2661

2662

2663

2664

2665

2666

2667

2668

2669

2670

2671

2672

2673

2674

2675

2676

2677

2678

2679

2680

2681

2682

2683

2684

2685

2686

2687

2688

2689

2690

2691

2692

2693

2694

2695

2696

2697

2698

2699

2700

2701

2702

2703

2704

2705

2706

2707

2708

2709

2710

2711

2712

2713

2714

2715

2716

2717

2718

2719

2720

2721

2722

2723

2724

2725

2726

2727

2728

2729

2730

2731

2732

2733

2734

2735

2736

2737

2738

2739

2740

2741

2742

2743

2744

2745

2746

2747

2748

2749

2750

2751

2752

2753

2754

2755

2756

2757

2758

2759

2760

2761

2762

2763

2764

2765

2766

2767

2768

2769

2770

2771

2772

2773

2774

2775

2776

2777

2778

2779

2780

2781

2782

2783

2784

2785

2786

2787

2788

2789

2790

2791

2792

2793

2794

2795

2796

2797

2798

2799

2800

2801

2802

2803

2804

2805

2806

2807

2808

2809

2810

2811

2812

2813

2814

2815

2816

2817

2818

2819

2820

2821

2822

2823

2824

2825

2826

2827

2828

2829

2830

2831

2832

2833

2834

2835

2836

2837

2838

2839

2840

2841

2842

2843

2844

2845

2846

2847

2848

2849

2850

2851

2852

2853

2854

2855

2856

2857

2858

2859

2860

2861

2862

2863

2864

2865

2866

2867

2868

2869

2870

2871

2872

2873

2874

2875

2876

2877

2878

2879

2880

2881

2882

2883

2884

2885

2886

2887

2888

2889

2890

2891

2892

2893

2894

2895

2896

2897

2898

2899

2900

2901

2902

2903

2904

2905

2906

2907

2908

2909

2910

2911

2912

2913

2914

2915

2916

2917

2918

2919

2920

2921

2922

2923

2924

2925

2926

2927

2928

2929

2930

2931

2932

2933

2934

2935

2936

2937

2938

2939

2940

2941

2942

2943

2944

2945

2946

2947

2948

2949

2950

2951

2952

2953

2954

2955

2956

2957

2958

2959

2960

2961

2962

2963

2964

2965

2966

2967

2968

2969

2970

2971

2972

2973

2974

2975

2976

2977

2978

2979

2980

2981

2982

2983

2984

2985

2986

2987

2988

2989

2990

2991

2992

2993

2994

2995

2996

2997

2998

2999

3000

3001

3002

3003

3004

3005

3006

3007

3008

3009

3010

3011

3012

3013

3014

3015

3016

3017

3018

3019

3020

3021

3022

3023

3024

3025

3026

3027

3028

3029

3030

3031

3032

3033

3034

3035

3036

3037

3038

3039

3040

3041

3042

3043

3044

3045

3046

3047

3048

3049

3050

3051

3052

3053

3054

3055

3056

3057

3058

3059

3060

3061

3062

3063

3064

3065

3066

3067

3068

3069

3070

3071

3072

3073

3074

3075

3076

3077

3078

3079

3080

3081

3082

3083

3084

3085

3086

3087

3088

3089

3090

3091

3092

3093

3094

3095

3096

3097

3098

3099

3100

3101

3102

3103

3104

3105

3106

3107

3108

3109

3110

3111

3112

3113

3114

3115

3116

3117

3118

3119

3120

3121

3122

3123

3124

3125

3126

3127

3128

3129

3130

3131

3132

3133

3134

3135

3136

3137

3138

3139

3140

3141

3142

3143

3144

3145

3146

3147

3148

3149

3150

3151

3152

3153

3154

3155

3156

3157

3158

3159

3160

3161

3162

3163

3164

3165

3166

3167

3168

3169

3170

3171

3172

3173

3174

3175

3176

3177

3178

3179

3180

3181

3182

3183

3184

3185

3186

3187

3188

3189

3190

3191

3192

3193

3194

3195

3196

3197

3198

3199

3200

3201

3202

3203

3204

3205

3206

3207

3208

3209

3210

3211

3212

3213

3214

3215

3216

3217

3218

3219

3220

3221

3222

3223

3224

3225

3226

3227

3228

3229

3230

3231

3232

3233

3234

3235

3236

3237

3238

3239

3240

3241

3242

3243

3244

3245

3246

3247

3248

3249

3250

3251

3252

3253

3254

3255

3256

3257

3258

3259

3260

3261

3262

3263

3264

3265

3266

3267

3268

3269

3270

3271

3272

3273

3274

3275

3276

3277

3278

3279

3280

3281

3282

3283

3284

3285

3286

3287

3288

3289

3290

3291

3292

3293

3294

3295

3296

3297

3298

3299

3300

3301

3302

3303

3304

3305

3306

3307

3308

3309

3310

3311

3312

3313

3314

3315

3316

3317

3318

3319

3320

3321

3322

3323

3324

3325

3326

3327

3328

3329

3330

3331

3332

3333

3334

3335

3336

3337

3338

3339

3340

3341

3342

3343

3344

3345

3346

3347

3348

3349

3350

3351

3352

3353

3354

3355

3356

3357

3358

3359

3360

3361

3362

3363

3364

3365

3366

3367

3368

3369

3370

3371

3372

3373

3374

3375

3376

3377

3378

3379

3380

3381

3382

3383

3384

3385

3386

3387

3388

3389

3390

3391

3392

3393

3394

3395

3396

3397

3398

3399

3400

3401

3402

3403

3404

3405

3406

3407

3408

3409

3410

3411

3412

3413

3414

3415

3416

3417

3418

3419

3420

3421

3422

3423

3424

3425

3426

3427

3428

3429

3430

3431

3432

3433

3434

3435

3436

3437

3438

3439

3440

3441

3442

3443

3444

3445

3446

3447

3448

3449

3450

3451

3452

3453

3454

3455

3456

3457

3458

3459

3460

3461

3462

3463

3464

3465

3466

3467

3468

3469

3470

3471

3472

3473

3474

3475

3476

3477

3478

3479

3480

3481

3482

3483

3484

3485

3486

3487

3488

3489

3490

3491

3492

3493

3494

3495

3496

3497

3498

3499

3500

3501

3502

3503

3504

3505

3506

3507

3508

3509

3510

3511

3512

3513

3514

3515

3516

3517

3518

3519

3520

3521

3522

3523

3524

3525

3526

3527

3528

3529

3530

3531

3532

3533

3534

3535

3536

3537

3538

3539

3540

3541

3542

3543

3544

3545

3546

3547

3548

3549

3550

3551

3552

3553

3554

3555

3556

3557

3558

3559

3560

3561

3562

3563

3564

3565

3566

3567

3568

3569

3570

3571

3572

3573

3574

3575

3576

3577

3578

3579

3580

3581

3582

3583

3584

3585

3586

3587

3588

3589

3590

3591

3592

3593

3594

3595

3596

3597

3598

3599

3600

3601

3602

3603

3604

3605

3606

3607

3608

3609

3610

3611

3612

3613

3614

3615

3616

3617

3618

3619

3620

3621

3622

3623

3624

3625

3626

3627

3628

3629

3630

3631

3632

3633

3634

3635

3636

3637

3638

3639

3640

3641

3642

3643

3644

3645

3646

3647

3648

3649

3650

3651

3652

3653

3654

3655

3656

3657

3658

3659

3660

3661

3662

3663

3664

3665

3666

3667

3668

3669

3670

3671

3672

3673

3674

3675

3676

3677

3678

3679

3680

3681

3682

3683

3684

3685

3686

3687

3688

3689

3690

3691

3692

3693

3694

3695

3696

3697

3698

3699

3700

3701

3702

3703

3704

3705

3706

3707

3708

3709

3710

3711

3712

3713

3714

3715

3716

3717

3718

3719

3720

3721

3722

3723

3724

3725

3726

3727

3728

3729

3730

3731

3732

3733

3734

3735

3736

3737

3738

3739

3740

3741

3742

3743

3744

3745

3746

3747

3748

3749

3750

3751

3752

3753

3754

3755

3756

3757

3758

3759

3760

3761

3762

3763

3764

3765

3766

3767

3768

3769

3770

3771

3772

3773

3774

3775

3776

3777

3778

3779

3780

3781

3782

3783

3784

3785

3786

3787

3788

3789

3790

3791

3792

3793

3794

3795

3796

3797

3798

3799

3800

3801

3802

3803

3804

3805

3806

3807

3808

3809

3810

3811

3812

3813

3814

3815

3816

3817

3818

3819

3820

3821

3822

3823

3824

3825

3826

3827

3828

3829

3830

3831

3832

3833

3834

3835

3836

3837

3838

3839

3840

3841

3842

3843

3844

3845

3846

3847

3848

3849

3850

3851

3852

3853

3854

3855

3856

3857

3858

3859

3860

3861

3862

3863

3864

3865

3866

3867

3868

3869

3870

3871

3872

3873

3874

3875

3876

3877

3878

3879

3880

3881

3882

3883

3884

3885

3886

3887

3888

3889

3890

3891

3892

3893

3894

3895

3896

3897

3898

3899

3900

3901

3902

3903

3904

3905

3906

3907

3908

3909

3910

3911

3912

3913

3914

3915

3916

3917

3918

3919

3920

3921

3922

3923

3924

3925

3926

3927

3928

3929

3930

3931

3932

3933

3934

3935

3936

3937

3938

3939

3940

3941

3942

3943

3944

3945

3946

3947

3948

3949

3950

3951

3952

3953

3954

3955

3956

3957

3958

3959

3960

3961

3962

3963

3964

3965

3966

3967

3968

3969

3970

3971

3972

3973

3974

3975

3976

3977

3978

3979

3980

3981

3982

3983

3984

3985

3986

3987

3988

3989

3990

3991

3992

3993

3994

3995

3996

3997

3998

3999

4000

4001

4002

4003

4004

4005

4006

4007

4008

4009

4010

4011

4012

4013

4014

4015

4016

4017

4018

4019

4020

4021

4022

4023

4024

4025

4026

4027

4028

4029

4030

4031

4032

4033

4034

4035

4036

4037

4038

4039

4040

4041

4042

4043

4044

4045

4046

4047

4048

4049

4050

4051

4052

4053

4054

4055

4056

4057

4058

4059

4060

4061

4062

4063

4064

4065

4066

4067

4068

4069

4070

4071

4072

4073

4074

4075

4076

4077

4078

4079

4080

4081

4082

4083

4084

4085

4086

4087

4088

4089

4090

4091

4092

4093

4094

4095

4096

4097

4098

4099

4100

4101

4102

4103

4104

4105

4106

4107

4108

4109

4110

4111

4112

4113

4114

4115

4116

4117

4118

4119

4120

4121

4122

4123

4124

4125

4126

4127

4128

4129

4130

4131

4132

4133

4134

4135

4136

4137

4138

4139

4140

4141

4142

4143

4144

4145

4146

4147

4148

4149

4150

4151

4152

4153

4154

4155

4156

4157

4158

4159

4160

4161

4162

4163

4164

4165

4166

4167

4168

4169

4170

4171

4172

4173

4174

4175

4176

4177

4178

4179

4180

4181

4182

4183

4184

4185

4186

4187

4188

4189

4190

4191

4192

4193

4194

4195

4196

4197

4198

4199

4200

4201

4202

4203

4204

4205

4206

4207

4208

4209

4210

4211

4212

4213

4214

4215

4216

4217

4218

4219

4220

4221

4222

4223

4224

4225

4226

4227

4228

4229

4230

4231

4232

4233

4234

4235

4236

4237

4238

4239

4240

4241

4242

4243

4244

4245

4246

4247

4248

4249

4250

4251

4252

4253

4254

4255

4256

4257

4258

4259

4260

4261

4262

4263

4264

4265

4266

4267

4268

4269

4270

4271

4272

4273

4274

4275

4276

4277

4278

4279

4280

4281

4282

4283

4284

4285

4286

4287

4288

4289

4290

4291

4292

4293

4294

4295

4296

4297

4298

4299

4300

4301

4302

4303

4304

4305

4306

4307

4308

4309

4310

4311

4312

4313

4314

4315

4316

4317

4318

4319

4320

4321

4322

4323

4324

4325

4326

4327

4328

4329

4330

4331

4332

4333

4334

4335

4336

4337

4338

4339

4340

4341

4342

4343

4344

4345

4346

4347

4348

4349

4350

4351

4352

4353

4354

4355

4356

4357

4358

4359

4360

4361

4362

4363

4364

4365

4366

4367

4368

4369

4370

4371

4372

4373

4374

4375

4376

4377

4378

4379

4380

4381

4382

4383

4384

4385

4386

4387

4388

4389

4390

4391

4392

4393

4394

4395

4396

4397

4398

4399

4400

4401

4402

4403

4404

4405

4406

4407

4408

4409

4410

4411

4412

4413

4414

4415

4416

4417

4418

4419

4420

4421

4422

4423

4424

4425

4426

4427

4428

4429

4430

4431

4432

4433

4434

4435

4436

4437

4438

4439

4440

4441

4442

4443

4444

4445

4446

4447

4448

4449

4450

4451

4452

4453

4454

4455

4456

4457

4458

4459

4460

4461

4462

4463

4464

4465

4466

4467

4468

4469

4470

4471

4472

4473

4474

4475

4476

4477

4478

4479

4480

4481

4482

4483

4484

4485

4486

4487

4488

4489

4490

4491

4492

4493

4494

4495

4496

4497

4498

4499

4500

4501

4502

4503

4504

4505

4506

4507

4508

4509

4510

4511

4512

4513

4514

4515

4516

4517

4518

4519

4520

4521

4522

4523

4524

4525

4526

4527

4528

4529

4530

4531

4532

4533

4534

4535

4536

4537

4538

4539

4540

4541

4542

4543

4544

4545

4546

4547

4548

4549

4550

4551

4552

4553

4554

4555

4556

4557

4558

4559

4560

4561

4562

4563

4564

4565

4566

4567

4568

4569

4570

4571

4572

4573

4574

4575

4576

4577

4578

4579

4580

4581

4582

4583

4584

4585

4586

4587

4588

4589

4590

4591

4592

4593

4594

4595

4596

4597

4598

4599

4600

4601

4602

4603

4604

4605

4606

4607

4608

4609

4610

4611

4612

4613

4614

4615

4616

4617

4618

4619

4620

4621

4622

4623

4624

4625

4626

4627

4628

4629

4630

4631

4632

4633

4634

4635

4636

4637

4638

4639

4640

4641

4642

4643

4644

4645

4646

4647

4648

4649

4650

4651

4652

4653

4654

4655

4656

4657

4658

4659

4660

4661

4662

4663

4664

4665

4666

4667

4668

4669

4670

4671

4672

4673

4674

4675

4676

4677

4678

4679

4680

4681

4682

4683

4684

4685

4686

4687

4688

4689

4690

4691

4692

4693

4694

4695

4696

4697

4698

4699

4700

4701

4702

4703

4704

4705

4706

4707

4708

4709

4710

4711

4712

4713

4714

4715

4716

4717

4718

4719

4720

4721

4722

4723

4724

4725

4726

4727

4728

4729

4730

4731

4732

4733

4734

4735

4736

4737

4738

4739

4740

4741

4742

4743

4744

4745

4746

4747

4748

4749

4750

4751

4752

4753

4754

4755

4756

4757

4758

4759

4760

4761

4762

4763

4764

4765

4766

4767

4768

4769

4770

4771

4772

4773

4774

4775

4776

4777

4778

4779

4780

4781

4782

4783

4784

4785

4786

4787

4788

4789

4790

4791

4792

4793

4794

4795

4796

4797

4798

4799

4800

4801

4802

4803

4804

4805

4806

4807

4808

4809

4810

4811

4812

4813

4814

4815

4816

4817

4818

4819

4820

4821

4822

4823

4824

4825

4826

4827

4828

4829

4830

4831

4832

4833

4834

4835

4836

4837

4838

4839

4840

4841

4842

4843

4844

4845

4846

4847

4848

4849

4850

4851

4852

4853

4854

4855

4856

4857

4858

4859

4860

4861

4862

4863

4864

4865

4866

4867

4868

4869

4870

4871

4872

4873

4874

4875

4876

4877

4878

4879

4880

4881

4882

4883

4884

4885

4886

4887

4888

4889

4890

4891

4892

4893

4894

4895

4896

4897

4898

4899

4900

4901

4902

4903

4904

4905

4906

4907

4908

4909

4910

4911

4912

4913

4914

4915

4916

4917

4918

4919

4920

4921

4922

4923

4924

4925

4926

4927

4928

4929

4930

4931

4932

4933

4934

4935

4936

4937

4938

4939

4940

4941

4942

4943

4944

4945

4946

4947

4948

4949

4950

4951

4952

4953

4954

4955

4956

4957

4958

4959

4960

4961

4962

4963

4964

4965

4966

4967

4968

4969

4970

4971

4972

4973

4974

4975

4976

4977

4978

4979

4980

4981

4982

4983

4984

4985

4986

4987

4988

4989

4990

4991

4992

4993

4994

4995

4996

4997

4998

4999

5000

5001

5002

5003

5004

5005

5006

5007

5008

5009

5010

5011

5012

5013

5014

5015

5016

5017

5018

5019

5020

5021

5022

5023

5024

5025

5026

5027

5028

5029

5030

5031

5032

5033

5034

5035

5036

5037

5038

5039

5040

5041

5042

5043

5044

5045

5046

5047

5048

5049

5050

5051

5052

5053

5054

5055

5056

5057

5058

5059

5060

5061

5062

5063

5064

5065

5066

5067

5068

5069

5070

5071

5072

5073

5074

5075

5076

5077

5078

5079

5080

5081

5082

5083

5084

5085

5086

5087

5088

5089

5090

5091

5092

5093

5094

5095

5096

5097

5098

5099

5100

5101

5102

5103

5104

5105

5106

5107

5108

5109

5110

5111

5112

5113

5114

5115

5116

5117

5118

5119

5120

5121

5122

5123

5124

5125

5126

5127

5128

5129

5130

5131

5132

5133

5134

5135

5136

5137

5138

5139

5140

5141

5142

5143

5144

5145

5146

5147

5148

5149

5150

5151

5152

5153

5154

5155

5156

5157

5158

5159

5160

5161

5162

5163

5164

5165

5166

5167

5168

5169

5170

5171

5172

5173

5174

5175

5176

5177

5178

5179

5180

5181

5182

5183

5184

5185

5186

5187

5188

5189

5190

5191

5192

5193

5194

5195

5196

5197

5198

5199

5200

5201

5202

5203

5204

5205

5206

5207

5208

5209

5210

5211

5212

5213

5214

5215

5216

5217

5218

5219

5220

5221

5222

5223

5224

5225

5226

5227

5228

5229

5230

5231

5232

5233

5234

5235

5236

5237

5238

5239

5240

5241

5242

5243

5244

5245

5246

5247

5248

5249

5250

5251

5252

5253

5254

5255

5256

5257

5258

5259

5260

5261

5262

5263

5264

5265

5266

5267

5268

5269

5270

5271

5272

5273

5274

5275

5276

5277

5278

5279

5280

5281

5282

5283

5284

5285

5286

5287

5288

5289

5290

5291

5292

5293

5294

5295

5296

5297

5298

5299

5300

5301

5302

5303

5304

5305

5306

5307

5308

5309

5310

5311

5312

5313

5314

5315

5316

5317

5318

5319

5320

5321

5322

5323

5324

5325

5326

5327

5328

5329

5330

5331

5332

5333

5334

5335

5336

5337

5338

5339

5340

5341

5342

5343

5344

5345

5346

5347

5348

5349

5350

5351

5352

5353

5354

5355

5356

5357

5358

5359

5360

5361

5362

5363

5364

5365

5366

5367

5368

5369

5370

5371

5372

5373

5374

5375

5376

5377

5378

5379

5380

5381

5382

5383

5384

5385

5386

5387

5388

5389

5390

5391

5392

5393

5394

5395

5396

5397

5398

5399

5400

5401

5402

5403

5404

5405

5406

5407

5408

5409

5410

5411

5412

5413

5414

5415

5416

5417

5418

5419

5420

5421

5422

5423

5424

5425

5426

5427

5428

5429

5430

5431

5432

5433

5434

5435

5436

5437

5438

5439

5440

5441

5442

5443

5444

5445

5446

5447

5448

5449

5450

5451

5452

5453

5454

5455

5456

5457

5458

5459

5460

5461

5462

5463

5464

5465

5466

5467

5468

5469

5470

5471

5472

5473

5474

5475

5476

5477

5478

5479

5480

5481

5482

5483

5484

5485

5486

5487

5488

5489

5490

5491

5492

5493

5494

5495

5496

5497

5498

5499

5500

5501

5502

5503

5504

5505

5506

5507

5508

5509

5510

5511

5512

5513

5514

5515

5516

5517

5518

5519

5520

5521

5522

5523

5524

5525

5526

5527

5528

5529

5530

5531

5532

5533

5534

5535

5536

5537

5538

5539

5540

5541

5542

5543

5544

5545

5546

5547

5548

5549

5550

5551

5552

5553

5554

5555

5556

5557

5558

5559

5560

5561

5562

5563

5564

5565

5566

5567

5568

5569

5570

5571

5572

5573

5574

5575

5576

5577

5578

5579

5580

5581

5582

5583

5584

5585

5586

5587

5588

5589

5590

5591

5592

5593

5594

5595

5596

5597

5598

5599

5600

5601

5602

5603

5604

5605

5606

5607

5608

5609

5610

5611

5612

5613

5614

5615

5616

5617

5618

5619

5620

5621

5622

5623

5624

5625

5626

5627

5628

5629

5630

5631

5632

5633

5634

5635

5636

5637

5638

5639

5640

5641

5642

5643

5644

5645

5646

5647

5648

5649

5650

5651

5652

5653

5654

5655

5656

5657

5658

5659

5660

5661

5662

5663

5664

5665

5666

5667

5668

5669

5670

5671

5672

5673

5674

5675

5676

5677

5678

5679

5680

5681

5682

5683

5684

5685

5686

5687

5688

5689

5690

5691

5692

5693

5694

5695

5696

5697

5698

5699

5700

5701

5702

5703

5704

5705

5706

5707

5708

5709

5710

5711

5712

5713

5714

5715

5716

5717

5718

5719

5720

5721

5722

5723

5724

5725

5726

5727

5728

5729

5730

5731

5732

5733

5734

5735

5736

5737

5738

5739

5740

5741

5742

5743

5744

5745

5746

5747

5748

5749

5750

5751

5752

5753

5754

5755

5756

5757

5758

5759

5760

5761

5762

5763

5764

5765

5766

5767

5768

5769

5770

5771

5772

5773

5774

5775

5776

5777

5778

5779

5780

5781

5782

5783

5784

5785

5786

5787

5788

5789

5790

5791

5792

5793

5794

5795

5796

5797

5798

5799

5800

5801

5802

5803

5804

5805

5806

5807

5808

5809

5810

5811

5812

5813

5814

5815

5816

5817

5818

5819

5820

5821

5822

5823

5824

5825

5826

5827

5828

5829

5830

5831

5832

5833

5834

5835

5836

5837

5838

5839

5840

5841

5842

5843

5844

5845

5846

5847

5848

5849

5850

5851

5852

5853

5854

5855

5856

5857

5858

5859

5860

5861

5862

5863

5864

5865

5866

5867

5868

5869

5870

5871

5872

5873

5874

5875

5876

5877

5878

5879

5880

5881

5882

5883

5884

5885

5886

5887

5888

5889

5890

5891

5892

5893

5894

5895

5896

5897

5898

5899

5900

5901

5902

5903

5904

5905

5906

5907

5908

5909

5910

5911

5912

5913

5914

5915

5916

5917

5918

5919

5920

5921

5922

5923

5924

5925

5926

5927

5928

5929

5930

5931

5932

5933

5934

5935

5936

5937

5938

5939

5940

5941

5942

5943

5944

5945

5946

5947

5948

5949

5950

5951

5952

5953

5954

5955

5956

5957

5958

5959

5960

5961

5962

5963

5964

5965

5966

5967

5968

5969

5970

5971

5972

5973

5974

5975

5976

5977

5978

5979

5980

5981

5982

5983

5984

5985

5986

5987

5988

5989

5990

5991

5992

5993

5994

5995

5996

5997

5998

5999

6000

6001

6002

6003

6004

6005

6006

6007

6008

6009

6010

6011

6012

6013

6014

6015

6016

6017

6018

6019

6020

6021

6022

6023

6024

6025

6026

6027

6028

6029

6030

6031

6032

6033

6034

6035

6036

6037

6038

6039

6040

6041

6042

6043

6044

6045

6046

6047

6048

6049

6050

6051

6052

6053

6054

6055

6056

6057

6058

6059

6060

6061

6062

6063

6064

6065

6066

6067

6068

6069

6070

6071

6072

6073

6074

6075

6076

6077

6078

6079

6080

6081

6082

6083

6084

6085

6086

6087

6088

6089

6090

6091

6092

6093

6094

6095

6096

6097

6098

6099

6100

6101

6102

6103

6104

6105

6106

6107

6108

6109

6110

6111

6112

6113

6114

6115

6116

6117

6118

6119

6120

6121

6122

6123

6124

6125

6126

6127

6128

6129

6130

6131

6132

6133

6134

6135

6136

6137

6138

6139

6140

6141

6142

6143

6144

6145

6146

6147

6148

6149

6150

6151

6152

6153

6154

6155

6156

6157

6158

6159

6160

6161

6162

6163

6164

6165

6166

6167

6168

6169

6170

6171

6172

6173

6174

6175

6176

6177

6178

6179

6180

6181

6182

6183

6184

6185

6186

6187

6188

6189

6190

6191

6192

6193

6194

6195

6196

6197

6198

6199

6200

6201

6202

6203

6204

6205

6206

6207

6208

6209

6210

6211

6212

6213

6214

6215

6216

6217

6218

6219

6220

6221

6222

6223

6224

6225

6226

6227

6228

6229

6230

6231

6232

6233

6234

6235

6236

6237

6238

6239

6240

6241

6242

6243

6244

6245

6246

6247

6248

6249

6250

6251

6252

6253

6254

6255

6256

6257

6258

6259

6260

6261

6262

6263

6264

6265

6266

6267

6268

6269

6270

6271

6272

6273

6274

6275

6276

6277

6278

6279

6280

6281

6282

6283

6284

6285

6286

6287

6288

6289

6290

6291

6292

6293

6294

6295

6296

6297

6298

6299

6300

6301

6302

6303

6304

6305

6306

6307

6308

6309

6310

6311

6312

6313

6314

6315

6316

6317

6318

6319

6320

6321

6322

6323

6324

6325

6326

6327

6328

6329

6330

6331

6332

6333

6334

6335

6336

6337

6338

6339

6340

6341

6342

6343

6344

6345

6346

6347

6348

6349

6350

6351

6352

6353

6354

6355

6356

6357

6358

6359

6360

6361

6362

6363

6364

6365

6366

6367

6368

6369

6370

6371

6372

6373

6374

6375

6376

6377

6378

6379

6380

6381

6382

6383

6384

6385

6386

6387

6388

6389

6390

6391

6392

6393

6394

6395

6396

6397

6398

6399

6400

6401

6402

6403

6404

6405

6406

6407

6408

6409

6410

6411

6412

6413

6414

6415

6416

6417

6418

6419

6420

6421

6422

6423

6424

6425

6426

6427

6428

6429

6430

6431

6432

6433

6434

6435

6436

6437

6438

6439

6440

6441

6442

6443

6444

6445

6446

6447

6448

6449

6450

6451

6452

6453

6454

6455

6456

6457

6458

6459

6460

6461

6462

6463

6464

6465

6466

6467

6468

6469

6470

6471

6472

6473

6474

6475

6476

6477

6478

6479

6480

6481

6482

6483

6484

6485

6486

6487

6488

6489

6490

6491

6492

6493

6494

6495

6496

6497

6498

6499

6500

6501

6502

6503

6504

6505

6506

6507

6508

6509

6510

6511

6512

6513

6514

6515

6516

6517

6518

6519

6520

6521

6522

6523

6524

6525

6526

6527

6528

6529

6530

6531

6532

6533

6534

6535

6536

6537

6538

6539

6540

6541

6542

6543

6544

6545

6546

6547

6548

6549

6550

6551

6552

6553

6554

6555

6556

6557

6558

6559

6560

6561

6562

6563

6564

6565

6566

6567

6568

6569

6570

6571

6572

6573

6574

6575

6576

6577

6578

6579

6580

6581

6582

6583

6584

6585

6586

6587

6588

6589

6590

6591

6592

6593

6594

6595

6596

6597

6598

6599

6600

6601

6602

6603

6604

6605

6606

6607

6608

6609

6610

6611

6612

6613

6614

6615

6616

6617

6618

6619

6620

6621

6622

6623

6624

6625

6626

6627

6628

6629

6630

6631

6632

6633

6634

6635

6636

6637

6638

6639

6640

6641

6642

6643

6644

6645

6646

6647

6648

6649

6650

6651

6652

6653

6654

6655

6656

6657

6658

6659

6660

6661

6662

6663

6664

6665

6666

6667

6668

6669

6670

6671

6672

6673

6674

6675

6676

6677

6678

6679

6680

6681

6682

6683

6684

6685

6686

6687

6688

6689

6690

6691

6692

6693

6694

6695

6696

6697

6698

6699

6700

6701

6702

6703

6704

6705

6706

6707

6708

6709

6710

6711

6712

6713

6714

6715

6716

6717

6718

6719

6720

6721

6722

6723

6724

6725

6726

6727

6728

6729

6730

6731

6732

6733

6734

6735

6736

6737

6738

6739

6740

6741

6742

6743

6744

6745

6746

6747

6748

6749

6750

6751

6752

6753

6754

6755

6756

6757

6758

6759

6760

6761

6762

6763

6764

6765

6766

6767

6768

6769

6770

6771

6772

6773

6774

6775

6776

6777

6778

6779

6780

6781

6782

6783

6784

6785

6786

6787

6788

6789

6790

6791

6792

6793

6794

6795

6796

6797

6798

6799

6800

6801

6802

6803

6804

6805

6806

6807

6808

6809

6810

6811

6812

6813

6814

6815

6816

6817

6818

6819

6820

6821

6822

6823

6824

6825

6826

6827

6828

6829

6830

6831

6832

6833

6834

6835

6836

6837

6838

6839

6840

6841

6842

6843

6844

6845

6846

6847

6848

6849

6850

6851

6852

6853

6854

6855

6856

6857

6858

6859

6860

6861

6862

6863

6864

6865

6866

6867

6868

6869

6870

6871

6872

6873

6874

6875

6876

6877

6878

6879

6880

6881

6882

6883

6884

6885

6886

6887

6888

6889

6890

6891

6892

6893

6894

6895

6896

6897

6898

6899

6900

6901

6902

6903

6904

6905

6906

6907

6908

6909

6910

6911

6912

6913

6914

6915

6916

6917

6918

6919

6920

6921

6922

6923

6924

6925

6926

6927

6928

6929

6930

6931

6932

6933

6934

6935

6936

6937

6938

6939

6940

6941

6942

6943

6944

6945

6946

6947

6948

6949

6950

6951

6952

6953

6954

6955

6956

6957

6958

6959

6960

6961

6962

6963

6964

6965

6966

6967

6968

6969

6970

6971

6972

6973

6974

6975

6976

6977

6978

6979

6980

6981

6982

6983

6984

6985

6986

6987

6988

6989

6990

6991

6992

6993

6994

6995

6996

6997

6998

6999

7000

7001

7002

7003

7004

7005

7006

7007

7008

7009

7010

7011

7012

7013

7014

7015

7016

7017

7018

7019

7020

7021

7022

7023

7024

7025

7026

7027

7028

7029

7030

7031

7032

7033

7034

7035

7036

7037

7038

7039

7040

7041

7042

7043

7044

7045

7046

7047

7048

7049

7050

7051

7052

7053

7054

7055

7056

7057

7058

7059

7060

7061

7062

7063

7064

7065

7066

7067

7068

7069

7070

7071

7072

7073

7074

7075

7076

7077

7078

7079

7080

7081

7082

7083

7084

7085

7086

7087

7088

7089

7090

7091

7092

7093

7094

7095

7096

7097

7098

7099

7100

7101

7102

7103

7104

7105

7106

7107

7108

7109

7110

7111

7112

7113

7114

7115

7116

7117

7118

7119

7120

7121

7122

7123

7124

7125

7126

7127

7128

7129

7130

7131

7132

7133

7134

7135

7136

7137

7138

7139

7140

7141

7142

7143

7144

7145

7146

7147

7148

7149

7150

7151

7152

7153

7154

7155

7156

7157

7158

7159

7160

7161

7162

7163

7164

7165

7166

7167

7168

7169

7170

7171

7172

7173

7174

7175

7176

7177

7178

7179

7180

7181

7182

7183

7184

7185

7186

7187

7188

7189

7190

7191

7192

7193

7194

7195

7196

7197

7198

7199

7200

7201

7202

7203

7204

7205

7206

7207

7208

7209

7210

7211

7212

7213

7214

7215

7216

7217

7218

7219

7220

7221

7222

7223

7224

7225

7226

7227

7228

7229

7230

7231

7232

7233

7234

7235

7236

7237

7238

7239

7240

7241

7242

7243

7244

7245

7246

7247

7248

7249

7250

7251

7252

7253

7254

7255

7256

7257

7258

7259

7260

7261

7262

7263

7264

7265

7266

7267

7268

7269

7270

7271

7272

7273

7274

7275

7276

7277

7278

7279

7280

7281

7282

7283

7284

7285

7286

7287

7288

7289

7290

7291

7292

7293

7294

7295

7296

7297

7298

7299

7300

7301

7302

7303

7304

7305

7306

7307

7308

7309

7310

7311

7312

7313

7314

7315

7316

7317

7318

7319

7320

7321

7322

7323

7324

7325

7326

7327

7328

7329

7330

7331

7332

7333

7334

7335

7336

7337

7338

7339

7340

7341

7342

7343

7344

7345

7346

7347

7348

7349

7350

7351

7352

7353

7354

7355

7356

7357

7358

7359

7360

7361

7362

7363

7364

7365

7366

7367

7368

7369

7370

7371

7372

7373

7374

7375

7376

7377

7378

7379

7380

7381

7382

7383

7384

7385

7386

7387

7388

7389

7390

7391

7392

7393

7394

7395

7396

7397

7398

7399

7400

7401

7402

7403

7404

7405

7406

7407

7408

7409

7410

7411

7412

7413

7414

7415

7416

7417

7418

7419

7420

7421

7422

7423

7424

7425

7426

7427

7428

7429

7430

7431

7432

7433

7434

7435

7436

7437

7438

7439

7440

7441

7442

7443

7444

7445

7446

7447

7448

7449

7450

7451

7452

7453

7454

7455

7456

7457

7458

7459

7460

7461

7462

7463

7464

7465

7466

7467

7468

7469

7470

7471

7472

7473

7474

7475

7476

7477

7478

7479

7480

7481

7482

7483

7484

7485

7486

7487

7488

7489

7490

7491

7492

r""" 

Elements of the ring `\ZZ` of integers 

  

Sage has highly optimized and extensive functionality about arithmetic with integers 

and the ring of integers. 

  

- Vincent Delecroix (2017-05-03): faster integer-rational comparisons 

  

EXAMPLES: 

  

Add 2 integers:: 

  

sage: a = Integer(3) ; b = Integer(4) 

sage: a + b == 7 

True 

  

Add an integer and a real number:: 

  

sage: a + 4.0 

7.00000000000000 

  

Add an integer and a rational number:: 

  

sage: a + Rational(2)/5 

17/5 

  

Add an integer and a complex number:: 

  

sage: b = ComplexField().0 + 1.5 

sage: loads((a+b).dumps()) == a+b 

True 

  

sage: z = 32 

sage: -z 

-32 

sage: z = 0; -z 

0 

sage: z = -0; -z 

0 

sage: z = -1; -z 

1 

  

Multiplication:: 

  

sage: a = Integer(3) ; b = Integer(4) 

sage: a * b == 12 

True 

sage: loads((a * 4.0).dumps()) == a*b 

True 

sage: a * Rational(2)/5 

6/5 

  

:: 

  

sage: list([2,3]) * 4 

[2, 3, 2, 3, 2, 3, 2, 3] 

  

:: 

  

sage: 'sage'*Integer(3) 

'sagesagesage' 

  

COERCIONS: 

  

Returns version of this integer in the multi-precision floating 

real field R:: 

  

sage: n = 9390823 

sage: RR = RealField(200) 

sage: RR(n) 

9.3908230000000000000000000000000000000000000000000000000000e6 

  

AUTHORS: 

  

- William Stein (2005): initial version 

  

- Gonzalo Tornaria (2006-03-02): vastly improved python/GMP 

conversion; hashing 

  

- Didier Deshommes (2006-03-06): numerous examples 

and docstrings 

  

- William Stein (2006-03-31): changes to reflect GMP bug fixes 

  

- William Stein (2006-04-14): added GMP factorial method (since it's 

now very fast). 

  

- David Harvey (2006-09-15): added nth_root, exact_log 

  

- David Harvey (2006-09-16): attempt to optimise Integer constructor 

  

- Rishikesh (2007-02-25): changed quo_rem so that the rem is positive 

  

- David Harvey, Martin Albrecht, Robert Bradshaw (2007-03-01): 

optimized Integer constructor and pool 

  

- Pablo De Napoli (2007-04-01): multiplicative_order should return 

+infinity for non zero numbers 

  

- Robert Bradshaw (2007-04-12): is_perfect_power, Jacobi symbol (with 

Kronecker extension). Convert some methods to use GMP directly 

rather than PARI, Integer(), PY_NEW(Integer) 

  

- David Roe (2007-03-21): sped up valuation and is_square, added 

val_unit, is_power, is_power_of and divide_knowing_divisible_by 

  

- Robert Bradshaw (2008-03-26): gamma function, multifactorials 

  

- Robert Bradshaw (2008-10-02): bounded squarefree part 

  

- David Loeffler (2011-01-15): fixed bug #10625 (inverse_mod should accept an ideal as argument) 

  

- Vincent Delecroix (2010-12-28): added unicode in Integer.__init__ 

  

- David Roe (2012-03): deprecate :meth:`~sage.rings.integer.Integer.is_power` 

in favour of :meth:`~sage.rings.integer.Integer.is_perfect_power` (see 

:trac:`12116`) 

  

- Vincent Klein (2017-05-11): add __mpz__() to class Integer 

  

- Vincent Klein (2017-05-22): Integer constructor support gmpy2.mpz parameter 

""" 

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

# Copyright (C) 2004,2006 William Stein <wstein@gmail.com> 

# Copyright (C) 2006 Gonzalo Tornaria <tornaria@math.utexas.edu> 

# Copyright (C) 2006 Didier Deshommes <dfdeshom@gmail.com> 

# Copyright (C) 2007 David Harvey <dmharvey@math.harvard.edu> 

# Copyright (C) 2007 Martin Albrecht <malb@informatik.uni-bremen.de> 

# Copyright (C) 2007,2008 Robert Bradshaw <robertwb@math.washington.edu> 

# Copyright (C) 2007 David Roe <roed314@gmail.com> 

# Copyright (C) 2017 Vincent Delecroix <20100.delecroix@gmail.com> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# 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, print_function 

  

# Do not create any Integer, especially non cdef'ed ones, before the hooked 

# creation and deletion are setup by the call to hook_fast_tp_functions 

  

cimport cython 

from libc.math cimport (ldexp, sqrt as sqrt_double, log as log_c, 

ceil as ceil_c, isnan) 

from libc.string cimport memcpy 

cdef extern from "<limits.h>": 

const long LONG_MAX # Work around https://github.com/cython/cython/pull/2016 

  

from cysignals.memory cimport check_allocarray, check_malloc, sig_free 

from cysignals.signals cimport sig_on, sig_off 

  

import operator 

import sys 

  

from sage.ext.stdsage cimport PY_NEW 

from sage.cpython.python_debug cimport if_Py_TRACE_REFS_then_PyObject_INIT 

  

from sage.libs.gmp.mpz cimport * 

from sage.libs.gmp.mpq cimport * 

from sage.misc.superseded import deprecated_function_alias 

from sage.cpython.string cimport char_to_str, str_to_bytes 

from sage.arith.long cimport (pyobject_to_long, integer_check_long, 

integer_check_long_py) 

  

from cpython.list cimport * 

from cpython.number cimport * 

from cpython.int cimport * 

from cpython.object cimport * 

from libc.stdint cimport uint64_t 

cimport sage.structure.element 

from sage.structure.element cimport (Element, EuclideanDomainElement, 

parent, coercion_model) 

from sage.structure.parent cimport Parent 

from cypari2.paridecl cimport * 

from sage.rings.rational cimport Rational 

from sage.arith.rational_reconstruction cimport mpq_rational_reconstruction 

from sage.libs.gmp.pylong cimport * 

from sage.libs.ntl.convert cimport mpz_to_ZZ 

from sage.libs.gmp.mpq cimport mpq_neg 

  

from cypari2.gen cimport objtogen, Gen as pari_gen 

from sage.libs.pari.convert_gmp cimport INT_to_mpz, new_gen_from_mpz_t 

from cypari2.stack cimport new_gen 

from sage.libs.flint.ulong_extras cimport * 

  

import sage.rings.infinity 

  

from sage.structure.coerce cimport is_numpy_type 

from sage.structure.element import coerce_binop 

  

from sage.libs.gmp.binop cimport mpq_add_z, mpq_mul_z, mpq_div_zz 

  

IF HAVE_GMPY2: 

cimport gmpy2 

gmpy2.import_gmpy2() 

  

  

cdef extern from *: 

int unlikely(int) nogil # Defined by Cython 

  

cdef object numpy_long_interface = {'typestr': '=i4' if sizeof(long) == 4 else '=i8' } 

cdef object numpy_int64_interface = {'typestr': '=i8'} 

cdef object numpy_object_interface = {'typestr': '|O'} 

  

cdef set_from_Integer(Integer self, Integer other): 

mpz_set(self.value, other.value) 

  

cdef set_from_pari_gen(Integer self, pari_gen x): 

r""" 

EXAMPLES:: 

  

sage: [Integer(pari(x)) for x in [1, 2^60, 2., GF(3)(1), GF(9,'a')(2)]] 

[1, 1152921504606846976, 2, 1, 2] 

sage: Integer(pari(2.1)) # indirect doctest 

Traceback (most recent call last): 

... 

TypeError: Attempt to coerce non-integral real number to an Integer 

""" 

# Simplify and lift until we get an integer 

while typ((<pari_gen>x).g) != t_INT: 

x = x.simplify() 

paritype = typ((<pari_gen>x).g) 

if paritype == t_INT: 

break 

elif paritype == t_REAL: 

# Check that the fractional part is zero 

if not x.frac().gequal0(): 

raise TypeError("Attempt to coerce non-integral real number to an Integer") 

# floor yields an integer 

x = x.floor() 

break 

elif paritype == t_PADIC: 

if x._valp() < 0: 

raise TypeError("Cannot convert p-adic with negative valuation to an integer") 

# Lifting a PADIC yields an integer 

x = x.lift() 

break 

elif paritype == t_INTMOD: 

# Lifting an INTMOD yields an integer 

x = x.lift() 

break 

elif paritype == t_POLMOD: 

x = x.lift() 

elif paritype == t_FFELT: 

# x = (f modulo defining polynomial of finite field); 

# we extract f. 

sig_on() 

x = new_gen(FF_to_FpXQ_i((<pari_gen>x).g)) 

else: 

raise TypeError("Unable to coerce PARI %s to an Integer"%x) 

  

# Now we have a true PARI integer, convert it to Sage 

INT_to_mpz(self.value, (<pari_gen>x).g) 

  

  

cdef _digits_naive(mpz_t v,l,int offset,Integer base,digits): 

""" 

This method fills in digit entries in the list, l, using the most 

basic digit algorithm -- repeat division by base. 

  

INPUT: 

  

- ``v`` - the value whose digits we want to put into the list 

  

- ``l`` - the list to file 

  

- ``offset`` - offset from the beginning of the list that we want 

to fill at 

  

- ``base`` -- the base to which we finding digits 

  

- ``digits`` - a python sequence type with objects to use for digits 

note that python negative index semantics are relied upon 

  

AUTHORS: 

  

- Joel B. Mohler (2009-01-16) 

""" 

cdef mpz_t mpz_value 

cdef mpz_t mpz_res # used on one side of the 'if' 

cdef Integer z # used on the other side of the 'if' 

  

mpz_init(mpz_value) 

mpz_set(mpz_value, v) 

  

# we aim to avoid sage Integer creation if possible 

if digits is None: 

while mpz_cmp_si(mpz_value,0): 

z = PY_NEW(Integer) 

mpz_tdiv_qr(mpz_value, z.value, mpz_value, base.value) 

l[offset] = z 

offset += 1 

else: 

mpz_init(mpz_res) 

while mpz_cmp_si(mpz_value,0): 

mpz_tdiv_qr(mpz_value, mpz_res, mpz_value, base.value) 

l[offset] = digits[mpz_get_si(mpz_res)] 

offset += 1 

mpz_clear(mpz_res) 

  

mpz_clear(mpz_value) 

  

cdef _digits_internal(mpz_t v,l,int offset,int power_index,power_list,digits): 

""" 

INPUT: 

  

- ``v`` - the value whose digits we want to put into the list 

  

- ``l`` - the list to file 

  

- ``offset`` - offset from the beginning of the list that we want 

to fill at 

  

- ``power_index`` - a measure of size to fill and index to 

power_list we're filling 1 << (power_index+1) digits 

  

- ``power_list`` - a list of powers of the base, precomputed in 

method digits digits - a python sequence type with objects to 

use for digits note that python negative index semantics are 

relied upon 

  

AUTHORS: 

  

- Joel B. Mohler (2008-03-13) 

""" 

cdef mpz_t mpz_res 

cdef mpz_t mpz_quot 

cdef Integer temp 

cdef int v_int 

if power_index < 5: 

# It turns out that simple repeated division is very fast for 

# relatively few digits. I don't think this is a real algorithmic 

# statement, it's an annoyance introduced by memory allocation. 

# I think that manual memory management with mpn_* would make the 

# divide & conquer approach even faster, but the code would be much 

# more complicated. 

_digits_naive(v,l,offset,power_list[0],digits) 

else: 

mpz_init(mpz_quot) 

mpz_init(mpz_res) 

temp = power_list[power_index] 

mpz_tdiv_qr(mpz_quot, mpz_res, v, temp.value) 

if mpz_sgn(mpz_res) != 0: 

_digits_internal(mpz_res,l,offset,power_index-1,power_list,digits) 

if mpz_sgn(mpz_quot) != 0: 

_digits_internal(mpz_quot,l,offset+(1<<power_index),power_index-1,power_list,digits) 

mpz_clear(mpz_quot) 

mpz_clear(mpz_res) 

  

from sage.structure.sage_object cimport SageObject 

from sage.structure.richcmp cimport rich_to_bool_sgn 

  

from sage.structure.element cimport EuclideanDomainElement, ModuleElement, Element 

from sage.structure.element import bin_op 

from sage.structure.coerce_exceptions import CoercionException 

  

from . import integer_ring 

cdef Parent the_integer_ring = integer_ring.ZZ 

  

# The documentation for the ispseudoprime() function in the PARI 

# manual states that its result is always prime up to this 2^64. 

cdef mpz_t PARI_PSEUDOPRIME_LIMIT 

mpz_init(PARI_PSEUDOPRIME_LIMIT) 

mpz_ui_pow_ui(PARI_PSEUDOPRIME_LIMIT, 2, 64) 

  

def is_Integer(x): 

""" 

Return true if x is of the Sage integer type. 

  

EXAMPLES:: 

  

sage: from sage.rings.integer import is_Integer 

sage: is_Integer(2) 

True 

sage: is_Integer(2/1) 

False 

sage: is_Integer(int(2)) 

False 

sage: is_Integer(long(2)) 

False 

sage: is_Integer('5') 

False 

""" 

return isinstance(x, Integer) 

  

cdef inline Integer as_Integer(x): 

if isinstance(x, Integer): 

return <Integer>x 

else: 

return Integer(x) 

  

cdef class IntegerWrapper(Integer): 

r""" 

Rationale for the ``IntegerWrapper`` class: 

  

With ``Integers``, the allocation/deallocation function slots are 

hijacked with custom functions that stick already allocated 

``Integers`` (with initialized ``parent`` and ``mpz_t`` fields) 

into a pool on "deallocation" and then pull them out whenever a 

new one is needed. Because ``Integers`` are so common, this is 

actually a significant savings. However , this does cause issues 

with subclassing a Python class directly from ``Integer`` (but 

that's ok for a Cython class). 

  

As a workaround, one can instead derive a class from the 

intermediate class ``IntegerWrapper``, which sets statically its 

alloc/dealloc methods to the *original* ``Integer`` alloc/dealloc 

methods, before they are swapped manually for the custom ones. 

  

The constructor of ``IntegerWrapper`` further allows for 

specifying an alternative parent to ``IntegerRing()``. 

""" 

  

def __init__(self, parent=None, x=None, unsigned int base=0): 

""" 

We illustrate how to create integers with parents different 

from ``IntegerRing()``:: 

  

sage: from sage.rings.integer import IntegerWrapper 

  

sage: n = IntegerWrapper(Primes(), 3) # indirect doctest 

sage: n 

3 

sage: n.parent() 

Set of all prime numbers: 2, 3, 5, 7, ... 

  

Pickling seems to work now (as of :trac:`10314`):: 

  

sage: nn = loads(dumps(n)) 

sage: nn 

3 

sage: nn.parent() 

Integer Ring 

  

sage: TestSuite(n).run() 

""" 

if parent is not None: 

Element.__init__(self, parent=parent) 

Integer.__init__(self, x, base=base) 

  

cdef class Integer(sage.structure.element.EuclideanDomainElement): 

r""" 

The ``Integer`` class represents arbitrary precision 

integers. It derives from the ``Element`` class, so 

integers can be used as ring elements anywhere in Sage. 

  

Integer() interprets strings that begin with ``0o`` as octal numbers, 

strings that begin with ``0x`` as hexadecimal numbers and strings 

that begin with ``0b`` as binary numbers. 

  

The class ``Integer`` is implemented in Cython, as a wrapper of the 

GMP ``mpz_t`` integer type. 

  

EXAMPLES:: 

  

sage: Integer(123) 

123 

sage: Integer("123") 

123 

  

Sage Integers support :pep:`3127` literals:: 

  

sage: Integer('0x12') 

18 

sage: Integer('-0o12') 

-10 

sage: Integer('+0b101010') 

42 

  

Conversion from PARI:: 

  

sage: Integer(pari('-10380104371593008048799446356441519384')) 

-10380104371593008048799446356441519384 

sage: Integer(pari('Pol([-3])')) 

-3 

  

Conversion from gmpy2:: 

  

sage: from gmpy2 import mpz # optional - gmpy2 

sage: Integer(mpz(3)) # optional - gmpy2 

3 

  

.. automethod:: __pow__ 

""" 

  

def __cinit__(self): 

global the_integer_ring 

mpz_init(self.value) 

self._parent = the_integer_ring 

  

def __init__(self, x=None, base=0): 

""" 

EXAMPLES:: 

  

sage: a = long(-901824309821093821093812093810928309183091832091) 

sage: b = ZZ(a); b 

-901824309821093821093812093810928309183091832091 

sage: ZZ(b) 

-901824309821093821093812093810928309183091832091 

sage: ZZ('-901824309821093821093812093810928309183091832091') 

-901824309821093821093812093810928309183091832091 

sage: ZZ(int(-93820984323)) 

-93820984323 

sage: ZZ(ZZ(-901824309821093821093812093810928309183091832091)) 

-901824309821093821093812093810928309183091832091 

sage: ZZ(QQ(-901824309821093821093812093810928309183091832091)) 

-901824309821093821093812093810928309183091832091 

sage: ZZ(RR(2.0)^80) 

1208925819614629174706176 

sage: ZZ(QQbar(sqrt(28-10*sqrt(3)) + sqrt(3))) 

5 

sage: ZZ(AA(32).nth_root(5)) 

2 

sage: ZZ(pari('Mod(-3,7)')) 

4 

sage: ZZ('sage') 

Traceback (most recent call last): 

... 

TypeError: unable to convert 'sage' to an integer 

sage: Integer('zz',36).str(36) 

'zz' 

sage: ZZ('0x3b').str(16) 

'3b' 

sage: ZZ( ZZ(5).digits(3) , 3) 

5 

sage: import numpy 

sage: ZZ(numpy.int64(7^7)) 

823543 

sage: ZZ(numpy.ubyte(-7)) 

249 

sage: ZZ(True) 

1 

sage: ZZ(False) 

0 

sage: ZZ(1==0) 

0 

sage: ZZ('+10') 

10 

sage: from gmpy2 import mpz # optional - gmpy2 

sage: ZZ(mpz(42)) # optional - gmpy2 

42 

  

:: 

  

sage: k = GF(2) 

sage: ZZ( (k(0),k(1)), 2) 

2 

  

:: 

  

sage: ZZ(float(2.0)) 

2 

sage: ZZ(float(1.0/0.0)) 

Traceback (most recent call last): 

... 

OverflowError: cannot convert float infinity to integer 

sage: ZZ(float(0.0/0.0)) 

Traceback (most recent call last): 

... 

ValueError: cannot convert float NaN to integer 

  

:: 

  

sage: class MyInt(int): 

....: pass 

sage: class MyLong(long): 

....: pass 

sage: class MyFloat(float): 

....: pass 

sage: ZZ(MyInt(3)) 

3 

sage: ZZ(MyLong(4)) 

4 

sage: ZZ(MyFloat(5)) 

5 

  

:: 

  

sage: Integer(u'0') 

0 

sage: Integer(u'0X2AEEF') 

175855 

  

Test conversion from PARI (:trac:`11685`):: 

  

sage: ZZ(pari(-3)) 

-3 

sage: ZZ(pari("-3.0")) 

-3 

sage: ZZ(pari("-3.5")) 

Traceback (most recent call last): 

... 

TypeError: Attempt to coerce non-integral real number to an Integer 

sage: ZZ(pari("1e100")) 

Traceback (most recent call last): 

... 

PariError: precision too low in truncr (precision loss in truncation) 

sage: ZZ(pari("10^50")) 

100000000000000000000000000000000000000000000000000 

sage: ZZ(pari("Pol(3)")) 

3 

sage: ZZ(GF(3^20,'t')(1)) 

1 

sage: ZZ(pari(GF(3^20,'t')(1))) 

1 

sage: x = polygen(QQ) 

sage: K.<a> = NumberField(x^2+3) 

sage: ZZ(a^2) 

-3 

sage: ZZ(pari(a)^2) 

-3 

sage: ZZ(pari("Mod(x, x^3+x+1)")) # Note error message refers to lifted element 

Traceback (most recent call last): 

... 

TypeError: Unable to coerce PARI x to an Integer 

  

Test coercion of p-adic with negative valuation:: 

  

sage: ZZ(pari(Qp(11)(11^-7))) 

Traceback (most recent call last): 

... 

TypeError: Cannot convert p-adic with negative valuation to an integer 

  

Test converting a list with a very large base:: 

  

sage: a=ZZ(randint(0,2^128-1)) 

sage: L = a.digits(2^64) 

sage: a == sum([x * 2^(64*i) for i,x in enumerate(L)]) 

True 

sage: a == ZZ(L,base=2^64) 

True 

  

Test comparisons with numpy types (see :trac:`13386` and :trac:`18076`):: 

  

sage: import numpy 

sage: numpy.int8('12') == 12 

True 

sage: 12 == numpy.int8('12') 

True 

  

sage: numpy.float('15') == 15 

True 

sage: 15 == numpy.float('15') 

True 

""" 

# TODO: All the code below should somehow be in an external 

# cdef'd function. Then e.g., if a matrix or vector or 

# polynomial is getting filled by mpz_t's, it can use the 

# rules below to do the fill construction of mpz_t's, but 

# without the overhead of creating any Python objects at all. 

# The cdef's function should be of the form 

# mpz_init_set_sage(mpz_t y, object x) 

# Then this function becomes the one liner: 

# mpz_init_set_sage(self.value, x) 

  

cdef Integer tmp 

cdef char* xs 

cdef int paritype 

cdef Py_ssize_t j 

cdef object otmp 

  

cdef Element lift 

  

if x is None: 

if mpz_sgn(self.value) != 0: 

mpz_set_si(self.value, 0) 

  

else: 

# First do all the type-check versions (these are fast to test), 

# except those for which the conversion itself will be slow. 

  

if isinstance(x, Integer): 

set_from_Integer(self, <Integer>x) 

  

elif isinstance(x, long): 

mpz_set_pylong(self.value, x) 

  

elif isinstance(x, int): 

mpz_set_si(self.value, PyInt_AS_LONG(x)) 

  

elif isinstance(x, float): 

n = long(x) 

if n == x: 

mpz_set_pylong(self.value, n) 

else: 

raise TypeError("Cannot convert non-integral float to integer") 

  

elif isinstance(x, pari_gen): 

set_from_pari_gen(self, x) 

  

else: 

  

otmp = getattr(x, "_integer_", None) 

if otmp is not None: 

set_from_Integer(self, otmp(the_integer_ring)) 

return 

  

if isinstance(x, Element): 

try: 

lift = x.lift() 

if lift._parent is the_integer_ring: 

set_from_Integer(self, lift) 

return 

except AttributeError: 

pass 

  

elif isinstance(x, bytes): 

mpz_set_str_python(self.value, x, base) 

return 

elif isinstance(x, unicode): 

mpz_set_str_python(self.value, str_to_bytes(x), base) 

return 

  

elif (isinstance(x, list) or isinstance(x, tuple)) and base > 1: 

b = the_integer_ring(base) 

if b == 2: # we use a faster method 

for j from 0 <= j < len(x): 

otmp = x[j] 

if not isinstance(otmp, Integer): 

# should probably also have fast code for Python ints... 

otmp = Integer(otmp) 

if mpz_cmp_si((<Integer>otmp).value, 1) == 0: 

mpz_setbit(self.value, j) 

elif mpz_sgn((<Integer>otmp).value) != 0: 

# one of the entries was something other than 0 or 1. 

break 

else: 

return 

tmp = the_integer_ring(0) 

for i in range(len(x)): 

tmp += the_integer_ring(x[i])*b**i 

mpz_set(self.value, tmp.value) 

return 

  

elif is_numpy_type(type(x)): 

import numpy 

if isinstance(x, numpy.integer): 

mpz_set_pylong(self.value, long(x)) 

return 

  

elif HAVE_GMPY2 and type(x) is gmpy2.mpz: 

mpz_set(self.value, (<gmpy2.mpz>x).z) 

return 

  

raise TypeError("unable to coerce %s to an integer" % type(x)) 

  

def __reduce__(self): 

""" 

This is used when pickling integers. 

  

EXAMPLES:: 

  

sage: n = 5 

sage: t = n.__reduce__(); t 

(<built-in function make_integer>, ('5',)) 

sage: t[0](*t[1]) 

5 

sage: loads(dumps(n)) == n 

True 

""" 

# This single line below took me HOURS to figure out. 

# It is the *trick* needed to pickle Cython extension types. 

# The trick is that you must put a pure Python function 

# as the first argument, and that function must return 

# the result of unpickling with the argument in the second 

# tuple as input. All kinds of problems happen 

# if we don't do this. 

return sage.rings.integer.make_integer, (self.str(32),) 

  

cdef _reduce_set(self, s): 

""" 

Set this integer from a string in base 32. 

  

.. NOTE:: 

  

Integers are supposed to be immutable, so you should not 

use this function. 

""" 

mpz_set_str(self.value, str_to_bytes(s), 32) 

  

def __index__(self): 

""" 

Needed so integers can be used as list indices. 

  

EXAMPLES:: 

  

sage: v = [1,2,3,4,5] 

sage: v[Integer(3)] 

4 

sage: v[Integer(2):Integer(4)] 

[3, 4] 

  

See :trac:`20750`:: 

  

sage: import re 

sage: p = re.compile('(a)b') 

sage: m = p.match('ab') 

sage: m.group(Integer(0)) 

'ab' 

sage: m.group(Integer(1)) 

'a' 

""" 

return mpz_get_pyintlong(self.value) 

  

def _im_gens_(self, codomain, im_gens): 

""" 

Return the image of self under the map that sends the generators of 

the parent to im_gens. Since ZZ maps canonically in the category 

of rings, this is just the natural coercion. 

  

EXAMPLES:: 

  

sage: n = -10 

sage: R = GF(17) 

sage: n._im_gens_(R, [R(1)]) 

7 

""" 

return codomain._coerce_(self) 

  

cdef _xor(Integer self, Integer other): 

cdef Integer x 

x = PY_NEW(Integer) 

mpz_xor(x.value, self.value, other.value) 

return x 

  

def __xor__(x, y): 

""" 

Compute the exclusive or of x and y. 

  

EXAMPLES:: 

  

sage: n = ZZ(2); m = ZZ(3) 

sage: n.__xor__(m) 

1 

""" 

if isinstance(x, Integer) and isinstance(y, Integer): 

return (<Integer>x)._xor(y) 

return bin_op(x, y, operator.xor) 

  

def __richcmp__(left, right, int op): 

""" 

cmp for integers 

  

EXAMPLES:: 

  

sage: 2 < 3 

True 

sage: 2 > 3 

False 

sage: 2 == 3 

False 

sage: 3 > 2 

True 

sage: 3 < 2 

False 

  

sage: 1000000000000000000000000000000000000000000000000000.0r==1000000000000000000000000000000000000000000000000000 

False 

sage: 1000000000000000000000000000000000000000000000000000.1r==1000000000000000000000000000000000000000000000000000 

False 

  

Canonical coercions are used but non-canonical ones are not. 

  

:: 

  

sage: 4 == 4/1 

True 

sage: 4 == '4' 

False 

  

TESTS:: 

  

sage: 3 < 4r 

True 

sage: 3r < 4 

True 

sage: 3 >= 4r 

False 

sage: 4r <= 3 

False 

sage: 12345678901234567890123456789r == 12345678901234567890123456789 

True 

sage: 12345678901234567890123456788 < 12345678901234567890123456789r 

True 

sage: 2 < 2.7r 

True 

sage: 4 < 3.1r 

False 

sage: -1r < 1 

True 

sage: -1.5r < 3 

True 

sage: Ilist = [-2,-1,0,1,2,12345678901234567890123456788] 

sage: ilist = [-4r,-1r,0r,1r,2r,5r] 

sage: llist = [-12345678901234567890123456788r, 12345678901234567890123456788r, 12345678901234567890123456900r] 

sage: flist = [-21.8r, -1.2r, -.000005r, 0.0r, .999999r, 1000000000000.0r] 

sage: all([(a < b) == (RR(a) < RR(b)) for (a, b) in zip(Ilist, ilist)]) 

True 

sage: all([(a > b) == (RR(a) > RR(b)) for (a, b) in zip(Ilist, ilist)]) 

True 

sage: all([(a == b) == (RR(a) == RR(b)) for (a, b) in zip(Ilist, ilist)]) 

True 

sage: all([(a <= b) == (RR(a) <= RR(b)) for (a, b) in zip(Ilist, ilist)]) 

True 

sage: all([(a >= b) == (RR(a) >= RR(b)) for (a, b) in zip(Ilist, ilist)]) 

True 

sage: all([(a != b) == (RR(a) != RR(b)) for (a, b) in zip(Ilist, ilist)]) 

True 

sage: all([(a < b) == (RR(a) < RR(b)) for (a, b) in zip(Ilist, llist)]) 

True 

sage: all([(a > b) == (RR(a) > RR(b)) for (a, b) in zip(Ilist, llist)]) 

True 

sage: all([(a < b) == (RR(a) < RR(b)) for (a, b) in zip(Ilist, flist)]) 

True 

sage: all([(a > b) == (RR(a) > RR(b)) for (a, b) in zip(Ilist, flist)]) 

True 

  

Verify that :trac:`12149` was fixed (and the fix is consistent 

with Python ints):: 

  

sage: a = int(1); b = 1; n = float('nan') 

sage: a == n 

False 

sage: a == n, b == n 

(False, False) 

sage: a != n, b != n, n != b 

(True, True, True) 

sage: a < n, b < n, n > b 

(False, False, False) 

sage: a > n, b > n, n < b 

(False, False, False) 

sage: a <= n, b <= n, n >= b 

(False, False, False) 

sage: a >= n, b >= n, n <= b 

(False, False, False) 

""" 

cdef int c 

cdef double d 

cdef mpz_t mpz_tmp 

  

assert isinstance(left, Integer) 

  

if isinstance(right, Integer): 

c = mpz_cmp((<Integer>left).value, (<Integer>right).value) 

elif isinstance(right, Rational): 

c = -mpq_cmp_z((<Rational>right).value, (<Integer>left).value) 

elif isinstance(right, long): 

mpz_init(mpz_tmp) 

mpz_set_pylong(mpz_tmp, right) 

c = mpz_cmp((<Integer>left).value, mpz_tmp) 

mpz_clear(mpz_tmp) 

elif isinstance(right, int): 

# this case should only occur in python 2 

c = mpz_cmp_si((<Integer>left).value, PyInt_AS_LONG(right)) 

elif isinstance(right, float): 

d = right 

if isnan(d): 

return op == Py_NE 

c = mpz_cmp_d((<Integer>left).value, d) 

else: 

return coercion_model.richcmp(left, right, op) 

  

return rich_to_bool_sgn(op, c) 

  

cpdef int _cmp_(left, right) except -2: 

r""" 

EXAMPLES:: 

  

sage: 1._cmp_(2) 

-1 

sage: 0._cmp_(0) 

0 

sage: (-3**10 + 1)._cmp_(-3**10) 

1 

""" 

cdef int c 

c = mpz_cmp((<Integer>left).value, (<Integer>right).value) 

return (c > 0) - (c < 0) 

  

def __copy__(self): 

""" 

Return a copy of the integer. 

  

EXAMPLES:: 

  

sage: n = 2 

sage: copy(n) 

2 

sage: copy(n) is n 

False 

""" 

cdef Integer z 

z = PY_NEW(Integer) 

mpz_set(z.value, self.value) 

return z 

  

def list(self): 

""" 

Return a list with this integer in it, to be compatible with the 

method for number fields. 

  

EXAMPLES:: 

  

sage: m = 5 

sage: m.list() 

[5] 

""" 

return [ self ] 

  

def __dealloc__(self): 

mpz_clear(self.value) 

  

def __repr__(self): 

""" 

Return string representation of this integer. 

  

EXAMPLES:: 

  

sage: n = -5; n.__repr__() 

'-5' 

""" 

return self.str() 

  

def _latex_(self): 

""" 

Return latex representation of this integer. This is just the 

underlying string representation and nothing more. This is called 

by the latex function. 

  

EXAMPLES:: 

  

sage: n = -5; n._latex_() 

'-5' 

sage: latex(n) 

-5 

""" 

return self.str() 

  

def _sympy_(self): 

""" 

Convert Sage Integer() to SymPy Integer. 

  

EXAMPLES:: 

  

sage: n = 5; n._sympy_() 

5 

sage: n = -5; n._sympy_() 

-5 

""" 

import sympy 

return sympy.sympify(int(self)) 

  

def _mathml_(self): 

""" 

Return mathml representation of this integer. 

  

EXAMPLES:: 

  

sage: mathml(-45) 

<mn>-45</mn> 

sage: (-45)._mathml_() 

'<mn>-45</mn>' 

""" 

return '<mn>%s</mn>'%self 

  

def __mpz__(self): 

""" 

Return a gmpy2 integer 

  

EXAMPLES:: 

  

sage: a = 5 

sage: a.__mpz__() # optional - gmpy2 

mpz(5) 

sage: from gmpy2 import mpz # optional - gmpy2 

sage: mpz(a) # optional - gmpy2 

mpz(5) 

  

TESTS:: 

  

sage: a.__mpz__(); raise NotImplementedError("gmpy2 is not installed") 

Traceback (most recent call last): 

... 

NotImplementedError: gmpy2 is not installed 

""" 

IF HAVE_GMPY2: 

return gmpy2.GMPy_MPZ_From_mpz(self.value) 

ELSE: 

raise NotImplementedError("gmpy2 is not installed") 

  

def str(self, int base=10): 

r""" 

Return the string representation of ``self`` in the 

given base. 

  

EXAMPLES:: 

  

sage: Integer(2^10).str(2) 

'10000000000' 

sage: Integer(2^10).str(17) 

'394' 

  

:: 

  

sage: two=Integer(2) 

sage: two.str(1) 

Traceback (most recent call last): 

... 

ValueError: base (=1) must be between 2 and 36 

  

:: 

  

sage: two.str(37) 

Traceback (most recent call last): 

... 

ValueError: base (=37) must be between 2 and 36 

  

:: 

  

sage: big = 10^5000000 

sage: s = big.str() # long time (2s on sage.math, 2014) 

sage: len(s) # long time (depends on above defn of s) 

5000001 

sage: s[:10] # long time (depends on above defn of s) 

'1000000000' 

""" 

if base < 2 or base > 36: 

raise ValueError("base (=%s) must be between 2 and 36" % base) 

cdef size_t n 

cdef char *s 

n = mpz_sizeinbase(self.value, base) + 2 

s = <char*>check_malloc(n) 

sig_on() 

mpz_get_str(s, base, self.value) 

sig_off() 

k = char_to_str(s) 

sig_free(s) 

return k 

  

def __format__(self, *args, **kwargs): 

""" 

Returns a string representation using Python's Format protocol. 

Valid format descriptions are exactly those for Python integers. 

  

EXAMPLES:: 

  

sage: "{0:#x}; {0:#b}; {0:+05d}".format(ZZ(17)) 

'0x11; 0b10001; +0017' 

  

""" 

return int(self).__format__(*args,**kwargs) 

  

def ordinal_str(self): 

""" 

Returns a string representation of the ordinal associated to self. 

  

EXAMPLES:: 

  

sage: [ZZ(n).ordinal_str() for n in range(25)] 

['0th', 

'1st', 

'2nd', 

'3rd', 

'4th', 

... 

'10th', 

'11th', 

'12th', 

'13th', 

'14th', 

... 

'20th', 

'21st', 

'22nd', 

'23rd', 

'24th'] 

  

sage: ZZ(1001).ordinal_str() 

'1001st' 

  

sage: ZZ(113).ordinal_str() 

'113th' 

sage: ZZ(112).ordinal_str() 

'112th' 

sage: ZZ(111).ordinal_str() 

'111th' 

  

""" 

if self<0: 

raise ValueError("Negative integers are not ordinals.") 

n = self.abs() 

if ((n%100)!=11 and n%10==1): 

th = 'st' 

elif ((n%100)!=12 and n%10==2): 

th = 'nd' 

elif ((n%100)!=13 and n%10==3): 

th = 'rd' 

else: 

th = 'th' 

return n.str()+th 

  

def __hex__(self): 

r""" 

Return the hexadecimal digits of self in lower case. 

  

.. NOTE:: 

  

'0x' is *not* prepended to the result like is done by the 

corresponding Python function on int or long. This is for 

efficiency sake--adding and stripping the string wastes 

time; since this function is used for conversions from 

integers to other C-library structures, it is important 

that it be fast. 

  

EXAMPLES:: 

  

sage: print(hex(Integer(15))) 

f 

sage: print(hex(Integer(16))) 

10 

sage: print(hex(Integer(16938402384092843092843098243))) 

36bb1e3929d1a8fe2802f083 

sage: print(hex(long(16938402384092843092843098243))) 

0x36bb1e3929d1a8fe2802f083L 

""" 

return self.str(16) 

  

def __oct__(self): 

r""" 

Return the digits of self in base 8. 

  

.. NOTE:: 

  

'0' is *not* prepended to the result like is done by the 

corresponding Python function on int or long. This is for 

efficiency sake--adding and stripping the string wastes 

time; since this function is used for conversions from 

integers to other C-library structures, it is important 

that it be fast. 

  

EXAMPLES:: 

  

sage: print(oct(Integer(800))) 

1440 

sage: print(oct(Integer(8))) 

10 

sage: print(oct(Integer(-50))) 

-62 

sage: print(oct(Integer(-899))) 

-1603 

sage: print(oct(Integer(16938402384092843092843098243))) 

15535436162247215217705000570203 

  

Behavior of Sage integers vs. Python integers:: 

  

sage: oct(Integer(10)) 

'12' 

sage: oct(int(10)) 

'012' 

sage: oct(Integer(-23)) 

'-27' 

sage: oct(int(-23)) 

'-027' 

""" 

return self.str(8) 

  

def binary(self): 

""" 

Return the binary digits of self as a string. 

  

EXAMPLES:: 

  

sage: print(Integer(15).binary()) 

1111 

sage: print(Integer(16).binary()) 

10000 

sage: print(Integer(16938402384092843092843098243).binary()) 

1101101011101100011110001110010010100111010001101010001111111000101000000000101111000010000011 

""" 

return self.str(2) 

  

def bits(self): 

""" 

Return the bits in self as a list, least significant first. The 

result satisfies the identity 

  

:: 

  

x == sum(b*2^e for e, b in enumerate(x.bits())) 

  

Negative numbers will have negative "bits". (So, strictly 

speaking, the entries of the returned list are not really 

members of `\ZZ/2\ZZ`.) 

  

This method just calls :func:`digits` with ``base=2``. 

  

.. SEEALSO:: 

  

:func:`nbits` (number of bits; a faster way to compute 

``len(x.bits())``; and :func:`binary`, which returns a string in 

more-familiar notation. 

  

EXAMPLES:: 

  

sage: 500.bits() 

[0, 0, 1, 0, 1, 1, 1, 1, 1] 

sage: 11.bits() 

[1, 1, 0, 1] 

sage: (-99).bits() 

[-1, -1, 0, 0, 0, -1, -1] 

""" 

return self.digits(base=2) 

  

def nbits(self): 

""" 

Return the number of bits in self. 

  

EXAMPLES:: 

  

sage: 500.nbits() 

9 

sage: 5.nbits() 

3 

sage: 0.nbits() == len(0.bits()) == 0.ndigits(base=2) 

True 

sage: 12345.nbits() == len(12345.binary()) 

True 

""" 

# mpz_sizeinbase(0,2) always returns 1 

if mpz_cmp_si(self.value,0) == 0: 

return int(0) 

else: 

return int(mpz_sizeinbase(self.value, 2)) 

  

def trailing_zero_bits(self): 

""" 

Return the number of trailing zero bits in self, i.e. 

the exponent of the largest power of 2 dividing self. 

  

EXAMPLES:: 

  

sage: 11.trailing_zero_bits() 

0 

sage: (-11).trailing_zero_bits() 

0 

sage: (11<<5).trailing_zero_bits() 

5 

sage: (-11<<5).trailing_zero_bits() 

5 

sage: 0.trailing_zero_bits() 

0 

  

""" 

if mpz_sgn(self.value) == 0: 

return int(0) 

return int(mpz_scan1(self.value, 0)) 

  

def digits(self, base=10, digits=None, padto=0): 

r""" 

Return a list of digits for ``self`` in the given base in little 

endian order. 

  

The returned value is unspecified if self is a negative number 

and the digits are given. 

  

INPUT: 

  

- ``base`` - integer (default: 10) 

  

- ``digits`` - optional indexable object as source for 

the digits 

  

- ``padto`` - the minimal length of the returned list, 

sufficient number of zeros are added to make the list minimum that 

length (default: 0) 

  

As a shorthand for ``digits(2)``, you can use :meth:`.bits`. 

  

Also see :meth:`ndigits`. 

  

EXAMPLES:: 

  

sage: 17.digits() 

[7, 1] 

sage: 5.digits(base=2, digits=["zero","one"]) 

['one', 'zero', 'one'] 

sage: 5.digits(3) 

[2, 1] 

sage: 0.digits(base=10) # 0 has 0 digits 

[] 

sage: 0.digits(base=2) # 0 has 0 digits 

[] 

sage: 10.digits(16,'0123456789abcdef') 

['a'] 

sage: 0.digits(16,'0123456789abcdef') 

[] 

sage: 0.digits(16,'0123456789abcdef',padto=1) 

['0'] 

sage: 123.digits(base=10,padto=5) 

[3, 2, 1, 0, 0] 

sage: 123.digits(base=2,padto=3) # padto is the minimal length 

[1, 1, 0, 1, 1, 1, 1] 

sage: 123.digits(base=2,padto=10,digits=(1,-1)) 

[-1, -1, 1, -1, -1, -1, -1, 1, 1, 1] 

sage: a=9939082340; a.digits(10) 

[0, 4, 3, 2, 8, 0, 9, 3, 9, 9] 

sage: a.digits(512) 

[100, 302, 26, 74] 

sage: (-12).digits(10) 

[-2, -1] 

sage: (-12).digits(2) 

[0, 0, -1, -1] 

  

We support large bases. 

  

:: 

  

sage: n=2^6000 

sage: n.digits(2^3000) 

[0, 0, 1] 

  

:: 

  

sage: base=3; n=25 

sage: l=n.digits(base) 

sage: # the next relationship should hold for all n,base 

sage: sum(base^i*l[i] for i in range(len(l)))==n 

True 

sage: base=3; n=-30; l=n.digits(base); sum(base^i*l[i] for i in range(len(l)))==n 

True 

  

The inverse of this method -- constructing an integer from a 

list of digits and a base -- can be done using the above method 

or by simply using :class:`ZZ() 

<sage.rings.integer_ring.IntegerRing_class>` with a base:: 

  

sage: x = 123; ZZ(x.digits(), 10) 

123 

sage: x == ZZ(x.digits(6), 6) 

True 

sage: x == ZZ(x.digits(25), 25) 

True 

  

Using :func:`sum` and :func:`enumerate` to do the same thing is 

slightly faster in many cases (and 

:func:`~sage.misc.misc_c.balanced_sum` may be faster yet). Of 

course it gives the same result:: 

  

sage: base = 4 

sage: sum(digit * base^i for i, digit in enumerate(x.digits(base))) == ZZ(x.digits(base), base) 

True 

  

Note: In some cases it is faster to give a digits collection. This 

would be particularly true for computing the digits of a series of 

small numbers. In these cases, the code is careful to allocate as 

few python objects as reasonably possible. 

  

:: 

  

sage: digits = list(range(15)) 

sage: l = [ZZ(i).digits(15,digits) for i in range(100)] 

sage: l[16] 

[1, 1] 

  

This function is comparable to ``str`` for speed. 

  

:: 

  

sage: n=3^100000 

sage: n.digits(base=10)[-1] # slightly slower than str 

1 

sage: n=10^10000 

sage: n.digits(base=10)[-1] # slightly faster than str 

1 

  

AUTHORS: 

  

- Joel B. Mohler (2008-03-02): significantly rewrote this entire function 

""" 

cdef Integer _base 

cdef Integer self_abs = self 

cdef int power_index = 0 

cdef list power_list 

cdef list l 

cdef int i 

cdef size_t s 

  

if isinstance(base, Integer): 

_base = <Integer>base 

else: 

_base = Integer(base) 

  

if mpz_cmp_si(_base.value,2) < 0: 

raise ValueError("base must be >= 2") 

  

if mpz_sgn(self.value) < 0: 

self_abs = -self 

  

cdef bint do_sig_on 

if mpz_sgn(self.value) == 0: 

l = [zero if digits is None else digits[0]]*padto 

elif mpz_cmp_si(_base.value,2) == 0: 

s = mpz_sizeinbase(self.value, 2) 

if digits: 

o = digits[1] 

z = digits[0] 

else: 

if mpz_sgn(self.value) == 1: 

o = one 

else: 

o = -one 

z = zero 

l = [z]*(s if s >= padto else padto) 

for i from 0<= i < s: 

# mpz_tstbit seems to return 0 for the high-order bit of 

# negative numbers?! 

if mpz_tstbit(self_abs.value,i): 

l[i] = o 

else: 

s = mpz_sizeinbase(self.value, 2) 

do_sig_on = (s > 256) 

if do_sig_on: sig_on() 

  

# We use a divide and conquer approach (suggested by the prior 

# author, malb?, of the digits method) here: for base b, compute 

# b^2, b^4, b^8, ... (repeated squaring) until you get larger 

# than your number; then compute (n // b^256, n % b^256) 

# (if b^512 > number) to split the number in half and recurse 

  

# Pre-computing the exact number of digits up-front is actually 

# faster (especially for large values of self) than trimming off 

# trailing zeros after the fact. It also seems that it would 

# avoid duplicating the list in memory with a list-slice. 

z = zero if digits is None else digits[0] 

s = self_abs.exact_log(_base) 

l = [z]*(s+1 if s+1 >= padto else padto) 

  

# set up digits for optimal access once we get inside the worker 

# functions 

if not digits is None: 

# list objects have fastest access in the innermost loop 

if type(digits) is not list: 

digits = [digits[i] for i in range(_base)] 

elif mpz_cmp_ui(_base.value,s) < 0 and mpz_cmp_ui(_base.value,10000): 

# We can get a speed boost by pre-allocating digit values in 

# big cases. 

# We do this we have more digits than the base and the base 

# is not too extremely large (currently, "extremely" means 

# larger than 10000 -- that's very arbitrary.) 

if mpz_sgn(self.value) > 0: 

digits = [Integer(i) for i in range(_base)] 

else: 

# All the digits will be negated in the recursive function. 

# we'll just compensate for python index semantics 

digits = [Integer(i) for i in range(-_base,0)] 

digits[0] = the_integer_ring._zero_element 

  

if s < 40: 

_digits_naive(self.value,l,0,_base,digits) 

else: 

# count the bits of s 

i = 0 

while s != 0: 

s >>= 1 

i += 1 

  

power_list = [_base]*i 

for power_index from 1 <= power_index < i: 

power_list[power_index] = power_list[power_index-1]**2 

  

# Note that it may appear that the recursive calls to 

# _digit_internal would be assigning list elements i in l for 

# anywhere from 0<=i<(1<<power_index). However, this is not 

# the case due to the optimization of skipping assigns 

# assigning zero. 

_digits_internal(self.value,l,0,i-1,power_list,digits) 

  

if do_sig_on: sig_off() 

  

# padding should be taken care of with-in the function 

# all we need to do is return 

return l 

  

def ndigits(self, base=10): 

""" 

Return the number of digits of self expressed in the given base. 

  

INPUT: 

  

- ``base`` - integer (default: 10) 

  

EXAMPLES:: 

  

sage: n = 52 

sage: n.ndigits() 

2 

sage: n = -10003 

sage: n.ndigits() 

5 

sage: n = 15 

sage: n.ndigits(2) 

4 

sage: n = 1000**1000000+1 

sage: n.ndigits() 

3000001 

sage: n = 1000**1000000-1 

sage: n.ndigits() 

3000000 

sage: n = 10**10000000-10**9999990 

sage: n.ndigits() 

10000000 

""" 

cdef Integer temp 

  

if mpz_sgn(self.value) == 0: 

temp = PY_NEW(Integer) 

mpz_set_ui(temp.value, 0) 

return temp 

  

if mpz_sgn(self.value) > 0: 

temp = self.exact_log(base) 

mpz_add_ui(temp.value, temp.value, 1) 

return temp 

else: 

return self.abs().exact_log(base) + 1 

  

cdef void set_from_mpz(Integer self, mpz_t value): 

mpz_set(self.value, value) 

  

cdef int _to_ZZ(self, ZZ_c *z) except -1: 

sig_on() 

mpz_to_ZZ(z, self.value) 

sig_off() 

  

def __add__(left, right): 

r""" 

TESTS:: 

  

sage: 1 + 2 

3 

sage: sum(Integer(i) for i in [1..100]) 

5050 

sage: 1 + 2/3 

5/3 

sage: 1 + (-2/3) 

1/3 

""" 

cdef Integer x 

cdef Rational y 

if type(left) is type(right): 

x = <Integer>PY_NEW(Integer) 

mpz_add(x.value, (<Integer>left).value, (<Integer>right).value) 

return x 

elif type(right) is Rational: 

y = <Rational> Rational.__new__(Rational) 

mpq_add_z(y.value, (<Rational>right).value, (<Integer>left).value) 

return y 

  

return coercion_model.bin_op(left, right, operator.add) 

  

cpdef _add_(self, right): 

""" 

Integer addition. 

  

TESTS:: 

  

sage: 32._add_(23) 

55 

sage: a = ZZ.random_element(10^50000) 

sage: b = ZZ.random_element(10^50000) 

sage: a._add_(b) == b._add_(a) 

True 

""" 

# self and right are guaranteed to be Integers 

cdef Integer x = <Integer>PY_NEW(Integer) 

mpz_add(x.value, self.value, (<Integer>right).value) 

return x 

  

cdef _add_long(self, long n): 

""" 

Fast path for adding a C long. 

  

TESTS:: 

  

sage: int(10) + Integer(100) 

110 

sage: Integer(100) + int(10) 

110 

sage: Integer(10^100) + int(10) 

10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010 

  

Also called for subtraction:: 

  

sage: Integer(100) - int(10) 

90 

sage: Integer(10^100) - int(10) 

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999990 

  

Make sure it works when -<long>n would overflow:: 

  

sage: most_neg_long = int(-sys.maxsize - 1) 

sage: type(most_neg_long), type(-most_neg_long) 

(<... 'int'>, <type 'long'>) 

sage: 0 + most_neg_long == most_neg_long 

True 

sage: 0 - most_neg_long == -most_neg_long 

True 

""" 

cdef Integer x = <Integer>PY_NEW(Integer) 

if n > 0: 

mpz_add_ui(x.value, self.value, n) 

else: 

# Note that 0-<unsigned long>n is always -n as an unsigned 

# long (whereas -n may overflow). 

mpz_sub_ui(x.value, self.value, 0 - <unsigned long>n) 

return x 

  

def __sub__(left, right): 

r""" 

TESTS:: 

  

sage: 1 - 2 

-1 

sage: 1 - 2/3 

1/3 

sage: 1 - (-2/3) 

5/3 

sage: (-1) - (-5/4) 

1/4 

""" 

cdef Integer x 

cdef Rational y 

if type(left) is type(right): 

x = <Integer>PY_NEW(Integer) 

mpz_sub(x.value, (<Integer>left).value, (<Integer>right).value) 

return x 

elif type(right) is Rational: 

y = <Rational> Rational.__new__(Rational) 

mpz_mul(mpq_numref(y.value), (<Integer>left).value, 

mpq_denref((<Rational>right).value)) 

mpz_sub(mpq_numref(y.value), mpq_numref(y.value), 

mpq_numref((<Rational>right).value)) 

mpz_set(mpq_denref(y.value), mpq_denref((<Rational>right).value)) 

return y 

  

return coercion_model.bin_op(left, right, operator.sub) 

  

cpdef _sub_(self, right): 

""" 

Integer subtraction. 

  

TESTS:: 

  

sage: Integer(32) - Integer(23) 

9 

sage: Integer(10^100) - Integer(1) 

9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 

sage: Integer(1) - Integer(10^100) 

-9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999 

sage: a = ZZ.random_element(10^50000) 

sage: b = ZZ.random_element(10^50000) 

sage: a-b == -(b-a) == a + -b 

True 

""" 

# self and right are guaranteed to be Integers 

cdef Integer x = <Integer>PY_NEW(Integer) 

mpz_sub(x.value, self.value, (<Integer>right).value) 

return x 

  

def __neg__(self): 

""" 

TESTS:: 

  

sage: a = Integer(3) 

sage: -a 

-3 

sage: a = Integer(3^100); a 

515377520732011331036461129765621272702107522001 

sage: -a 

-515377520732011331036461129765621272702107522001 

""" 

cdef Integer x = <Integer>PY_NEW(Integer) 

mpz_neg(x.value, self.value) 

return x 

  

cpdef _neg_(self): 

cdef Integer x = <Integer>PY_NEW(Integer) 

mpz_neg(x.value, self.value) 

return x 

  

cpdef _act_on_(self, s, bint self_on_left): 

""" 

EXAMPLES:: 

  

sage: 8 * [0] #indirect doctest 

[0, 0, 0, 0, 0, 0, 0, 0] 

sage: 'hi' * 8 

'hihihihihihihihi' 

""" 

if isinstance(s, (list, tuple, basestring)): 

if mpz_fits_slong_p(self.value): 

return s * mpz_get_si(self.value) 

else: 

return s * int(self) # will raise the appropriate exception 

  

cdef _mul_long(self, long n): 

""" 

Fast path for multiplying a C long. 

  

TESTS:: 

  

sage: Integer(25) * int(4) 

100 

sage: int(4) * Integer(25) 

100 

sage: Integer(10^100) * int(4) 

40000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 

""" 

cdef Integer x = <Integer>PY_NEW(Integer) 

if mpz_size(self.value) > 100000: 

sig_on() 

mpz_mul_si(x.value, self.value, n) 

sig_off() 

else: 

mpz_mul_si(x.value, self.value, n) 

return x 

  

def __mul__(left, right): 

r""" 

TESTS:: 

  

sage: 3 * 2 

6 

sage: 5 * QQ((2,3)) 

10/3 

sage: 3 * (-5/6) 

-5/2 

sage: (-2) * (-5/4) 

5/2 

""" 

cdef Integer x 

cdef Rational y 

if type(left) is type(right): 

x = <Integer>PY_NEW(Integer) 

mpz_mul(x.value, (<Integer>left).value, (<Integer>right).value) 

return x 

elif type(right) is Rational: 

y = <Rational> Rational.__new__(Rational) 

mpq_mul_z(y.value, (<Rational>right).value, (<Integer>left).value) 

return y 

  

return coercion_model.bin_op(left, right, operator.mul) 

  

cpdef _mul_(self, right): 

""" 

Integer multiplication. 

  

sage: 25._mul_(4) 

100 

sage: (5^100)._mul_(2^100) 

10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 

sage: a = ZZ.random_element(10^50000) 

sage: b = ZZ.random_element(10^50000) 

sage: a._mul_(b) == b._mul_(a) 

True 

""" 

# self and right are guaranteed to be Integers 

cdef Integer x = <Integer>PY_NEW(Integer) 

if mpz_size(self.value) + mpz_size((<Integer>right).value) > 100000: 

# We only use the signal handler (to enable ctrl-c out) when the 

# product might take a while to compute 

sig_on() 

mpz_mul(x.value, self.value, (<Integer>right).value) 

sig_off() 

else: 

mpz_mul(x.value, self.value, (<Integer>right).value) 

return x 

  

def __div__(left, right): 

r""" 

TESTS:: 

  

sage: 3 / 2 

3/2 

sage: 5 / QQ((10,3)) 

3/2 

sage: 3 / (-5/6) 

-18/5 

sage: (-2) / (-5/4) 

8/5 

sage: 3 / polygen(ZZ) 

3/x 

  

sage: 3 / 0 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

sage: 3 / QQ.zero() 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

sage: 3 / QQbar.zero() 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

""" 

cdef Rational x 

if type(left) is type(right): 

if mpz_sgn((<Integer>right).value) == 0: 

raise ZeroDivisionError("rational division by zero") 

x = <Rational> Rational.__new__(Rational) 

mpq_div_zz(x.value, (<Integer>left).value, (<Integer>right).value) 

return x 

elif type(right) is Rational: 

if mpq_sgn((<Rational>right).value) == 0: 

raise ZeroDivisionError("rational division by zero") 

# left * den(right) / num(right) 

y = <Rational> Rational.__new__(Rational) 

mpq_div_zz(y.value, (<Integer>left).value, 

mpq_numref((<Rational>right).value)) 

mpz_mul(mpq_numref(y.value), mpq_numref(y.value), 

mpq_denref((<Rational>right).value)) 

return y 

  

return coercion_model.bin_op(left, right, operator.div) 

  

cpdef _div_(self, right): 

r""" 

Computes `\frac{a}{b}` 

  

EXAMPLES:: 

  

sage: 3._div_(4) 

3/4 

sage: (-32)._div_(-32) 

1 

""" 

if mpz_sgn((<Integer>right).value) == 0: 

raise ZeroDivisionError("rational division by zero") 

x = <Rational> Rational.__new__(Rational) 

mpq_div_zz(x.value, self.value, (<Integer>right).value) 

return x 

  

cpdef _floordiv_(self, right): 

r""" 

Computes the whole part of `\frac{x}{y}`. 

  

EXAMPLES:: 

  

sage: a = Integer(321) ; b = Integer(10) 

sage: a // b 

32 

sage: z = Integer(-231) 

sage: z // 2 

-116 

sage: z = Integer(231) 

sage: z // 2 

115 

sage: z // -2 

-116 

sage: z // 0 

Traceback (most recent call last): 

... 

ZeroDivisionError: Integer division by zero 

sage: 101 // int(5) 

20 

sage: 100 // int(-3) 

-34 

  

TESTS:: 

  

sage: signs = [(11,5), (11,-5), (-11,5), (-11,-5)] 

sage: control = [int(a) // int(b) for a, b in signs] 

sage: [a // b for a,b in signs] == control 

True 

sage: [a // int(b) for a,b in signs] == control 

True 

sage: [int(a) // b for a,b in signs] == control 

True 

""" 

if not mpz_sgn((<Integer>right).value): 

raise ZeroDivisionError("Integer division by zero") 

  

cdef Integer z = <Integer>PY_NEW(Integer) 

if mpz_size(self.value) > 1000: 

sig_on() 

mpz_fdiv_q(z.value, self.value, (<Integer>right).value) 

sig_off() 

else: 

mpz_fdiv_q(z.value, self.value, (<Integer>right).value) 

return z 

  

def __pow__(left, right, modulus): 

r""" 

Return ``(left ^ right) % modulus``. 

  

EXAMPLES:: 

  

sage: 2^-6 

1/64 

sage: 2^6 

64 

sage: 2^0 

1 

sage: 2^-0 

1 

sage: (-1)^(1/3) 

(-1)^(1/3) 

  

For consistency with Python and MPFR, 0^0 is defined to be 1 in 

Sage:: 

  

sage: 0^0 

1 

  

See also `<http://www.faqs.org/faqs/sci-math-faq/0to0/>`_ and 

`<https://math.stackexchange.com/questions/11150/zero-to-the-zero-power-is-00-1>`_. 

  

The base need not be a Sage integer. If it is a Python type, the 

result is a Python type too:: 

  

sage: r = int(2) ^ 10; r; type(r) 

1024 

<... 'int'> 

sage: r = int(3) ^ -3; r; type(r) 

0.037037037037037035 

<... 'float'> 

sage: r = float(2.5) ^ 10; r; type(r) 

9536.7431640625 

<... 'float'> 

  

We raise 2 to various interesting exponents:: 

  

sage: 2^x # symbolic x 

2^x 

sage: 2^1.5 # real number 

2.82842712474619 

sage: 2^float(1.5) # python float abs tol 3e-16 

2.8284271247461903 

sage: 2^I # complex number 

2^I 

sage: r = 2 ^ int(-3); r; type(r) 

1/8 

<type 'sage.rings.rational.Rational'> 

sage: f = 2^(sin(x)-cos(x)); f 

2^(-cos(x) + sin(x)) 

sage: f(x=3) 

2^(-cos(3) + sin(3)) 

  

A symbolic sum:: 

  

sage: x,y,z = var('x,y,z') 

sage: 2^(x+y+z) 

2^(x + y + z) 

sage: 2^(1/2) 

sqrt(2) 

sage: 2^(-1/2) 

1/2*sqrt(2) 

  

TESTS:: 

  

sage: R.<t> = QQ[] 

sage: 2^t 

Traceback (most recent call last): 

... 

TypeError: no canonical coercion from Univariate Polynomial 

Ring in t over Rational Field to Rational Field 

sage: 'sage' ^ 3 

doctest:...: 

DeprecationWarning: raising a string to an integer power is deprecated 

See http://trac.sagemath.org/24260 for details. 

'sagesagesage' 

""" 

if modulus is not None: 

from sage.rings.finite_rings.integer_mod import Mod 

return Mod(left, modulus) ** right 

  

if type(left) is type(right): 

return (<Integer>left)._pow_(right) 

elif isinstance(left, Element): 

return coercion_model.bin_op(left, right, operator.pow) 

elif isinstance(left, str): 

from sage.misc.superseded import deprecation 

deprecation(24260, "raising a string to an integer power is deprecated") 

return left * int(right) 

# left is a non-Element: do the powering with a Python int 

return left ** int(right) 

  

cpdef _pow_(self, other): 

""" 

Integer powering. 

  

TESTS:: 

  

sage: 2._pow_(3) 

8 

sage: (-2)._pow_(3) 

-8 

sage: 2._pow_(-3) 

1/8 

sage: (-2)._pow_(-3) 

-1/8 

sage: 2._pow_(4) 

16 

sage: (-2)._pow_(4) 

16 

sage: 2._pow_(-4) 

1/16 

sage: (-2)._pow_(-4) 

1/16 

sage: 0._pow_(3) 

0 

sage: 0._pow_(-3) 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

  

The exponent must fit in a long unless the base is -1, 0, or 1:: 

  

sage: 2 ^ 100000000000000000000000 

Traceback (most recent call last): 

... 

OverflowError: exponent must be at most 2147483647 # 32-bit 

OverflowError: exponent must be at most 9223372036854775807 # 64-bit 

sage: 1 ^ 100000000000000000000000 

1 

sage: 1 ^ -100000000000000000000000 

1 

sage: 0 ^ 100000000000000000000000 

0 

sage: 0 ^ -100000000000000000000000 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

sage: (-1) ^ 100000000000000000000000 

1 

sage: (-1) ^ 100000000000000000000001 

-1 

sage: (-1) ^ -100000000000000000000000 

1 

sage: (-1) ^ -100000000000000000000001 

-1 

""" 

cdef mpz_ptr exp = (<Integer>other).value 

  

if mpz_fits_slong_p(exp): 

return self._pow_long(mpz_get_si(exp)) 

  

# Raising to an exponent which doesn't fit in a long overflows 

# except if the base is -1, 0 or 1. 

cdef long s = LONG_MAX 

if mpz_fits_slong_p(self.value): 

s = mpz_get_si(self.value) 

  

if s == 0 or s == 1: 

r = self 

elif s == -1: 

if mpz_odd_p(exp): 

r = self 

else: 

r = smallInteger(1) 

else: 

raise OverflowError(f"exponent must be at most {LONG_MAX}") 

if mpz_sgn(exp) >= 0: 

return r 

else: 

return ~r 

  

cdef _pow_long(self, long n): 

if n == 0: 

return smallInteger(1) 

elif n == 1: 

return self 

  

cdef Integer x 

cdef Rational q 

if n > 0: 

x = PY_NEW(Integer) 

sig_on() 

mpz_pow_ui(x.value, self.value, n) 

sig_off() 

return x 

else: 

if mpz_sgn(self.value) == 0: 

raise ZeroDivisionError("rational division by zero") 

q = Rational.__new__(Rational) 

sig_on() 

mpz_pow_ui(mpq_denref(q.value), self.value, -n) 

if mpz_sgn(mpq_denref(q.value)) > 0: 

mpz_set_ui(mpq_numref(q.value), 1) 

else: 

# If the denominator was negative, change sign and set 

# numerator to -1 

mpz_set_si(mpq_numref(q.value), -1) 

mpz_abs(mpq_denref(q.value), mpq_denref(q.value)) 

sig_off() 

return q 

  

cpdef _pow_int(self, n): 

""" 

Integer powering to an integer exponent. 

  

TESTS:: 

  

sage: 2._pow_int(int(20)) 

1048576 

sage: 1._pow_int(int(2^100)) 

1 

""" 

return self._pow_(Integer(n)) 

  

def nth_root(self, int n, bint truncate_mode=0): 

r""" 

Returns the (possibly truncated) n'th root of self. 

  

INPUT: 

  

- ``n`` - integer >= 1 (must fit in C int type). 

  

- ``truncate_mode`` - boolean, whether to allow truncation if 

self is not an n'th power. 

  

OUTPUT: 

  

If truncate_mode is 0 (default), then returns the exact n'th root 

if self is an n'th power, or raises a ValueError if it is not. 

  

If truncate_mode is 1, then if either n is odd or self is 

positive, returns a pair (root, exact_flag) where root is the 

truncated nth root (rounded towards zero) and exact_flag is a 

boolean indicating whether the root extraction was exact; 

otherwise raises a ValueError. 

  

AUTHORS: 

  

- David Harvey (2006-09-15) 

- Interface changed by John Cremona (2009-04-04) 

  

EXAMPLES:: 

  

sage: Integer(125).nth_root(3) 

5 

sage: Integer(124).nth_root(3) 

Traceback (most recent call last): 

... 

ValueError: 124 is not a 3rd power 

sage: Integer(124).nth_root(3, truncate_mode=1) 

(4, False) 

sage: Integer(125).nth_root(3, truncate_mode=1) 

(5, True) 

sage: Integer(126).nth_root(3, truncate_mode=1) 

(5, False) 

  

:: 

  

sage: Integer(-125).nth_root(3) 

-5 

sage: Integer(-125).nth_root(3,truncate_mode=1) 

(-5, True) 

sage: Integer(-124).nth_root(3,truncate_mode=1) 

(-4, False) 

sage: Integer(-126).nth_root(3,truncate_mode=1) 

(-5, False) 

  

:: 

  

sage: Integer(125).nth_root(2, True) 

(11, False) 

sage: Integer(125).nth_root(3, True) 

(5, True) 

  

:: 

  

sage: Integer(125).nth_root(-5) 

Traceback (most recent call last): 

... 

ValueError: n (=-5) must be positive 

  

:: 

  

sage: Integer(-25).nth_root(2) 

Traceback (most recent call last): 

... 

ValueError: cannot take even root of negative number 

  

:: 

  

sage: a=9 

sage: a.nth_root(3) 

Traceback (most recent call last): 

... 

ValueError: 9 is not a 3rd power 

  

sage: a.nth_root(22) 

Traceback (most recent call last): 

... 

ValueError: 9 is not a 22nd power 

  

sage: ZZ(2^20).nth_root(21) 

Traceback (most recent call last): 

... 

ValueError: 1048576 is not a 21st power 

  

sage: ZZ(2^20).nth_root(21, truncate_mode=1) 

(1, False) 

  

""" 

if n < 1: 

raise ValueError("n (=%s) must be positive" % n) 

if (mpz_sgn(self.value) < 0) and not (n & 1): 

raise ValueError("cannot take even root of negative number") 

cdef Integer x 

cdef bint is_exact 

x = PY_NEW(Integer) 

sig_on() 

is_exact = mpz_root(x.value, self.value, n) 

sig_off() 

  

if truncate_mode: 

return x, is_exact 

else: 

if is_exact: 

return x 

else: 

raise ValueError("%s is not a %s power" % (self, 

integer_ring.ZZ(n).ordinal_str())) 

  

cpdef size_t _exact_log_log2_iter(self,Integer m): 

""" 

This is only for internal use only. You should expect it to crash 

and burn for negative or other malformed input. In particular, if 

the base `2 \leq m < 4` the log2 approximation of m is 1 and certain 

input causes endless loops. Along these lines, it is clear that 

this function is most useful for m with a relatively large number 

of bits. 

  

For ``small`` values (which I'll leave quite ambiguous), this function 

is a fast path for exact log computations. Any integer division with 

such input tends to dominate the runtime. Thus we avoid division 

entirely in this function. 

  

AUTHOR:: 

  

- Joel B. Mohler (2009-04-10) 

  

EXAMPLES:: 

  

sage: Integer(125)._exact_log_log2_iter(4) 

3 

sage: Integer(5^150)._exact_log_log2_iter(5) 

150 

""" 

cdef size_t n_log2 

cdef size_t m_log2 

cdef size_t l_min 

cdef size_t l_max 

cdef size_t l 

cdef Integer result 

cdef mpz_t accum 

cdef mpz_t temp_exp 

  

if mpz_cmp_si(m.value,4) < 0: 

raise ValueError("This is undefined or possibly non-convergent with this algorithm.") 

  

n_log2=mpz_sizeinbase(self.value,2)-1 

m_log2=mpz_sizeinbase(m.value,2)-1 

l_min=n_log2/(m_log2+1) 

l_max=n_log2/m_log2 

if l_min != l_max: 

sig_on() 

mpz_init(accum) 

mpz_init(temp_exp) 

mpz_set_ui(accum,1) 

l = 0 

while l_min != l_max: 

if l_min + 1 == l_max: 

mpz_pow_ui(temp_exp,m.value,l_min+1-l) 

# This might over-shoot and make accum > self, but 

# we'll know that it's only over by a factor of m^1. 

mpz_mul(accum,accum,temp_exp) 

if mpz_cmp(self.value,accum) >= 0: 

l_min += 1 

break 

mpz_pow_ui(temp_exp,m.value,l_min-l) 

mpz_mul(accum,accum,temp_exp) 

l = l_min 

  

# Let x=n_log2-(mpz_sizeinbase(accum,2)-1) and y=m_log2. 

# Now, with x>0 and y>0, we have the following observation. 

# If floor((x-1)/(y+1))=0, then x-1<y+1 which implies that 

# x/y<1+2/y. 

# So long as y>=2, this means that floor(x/y)<=1. This shows 

# that this iteration is forced to converge for input m >= 4. 

# If m=3, we can find input so that floor((x-1)/(y+1))=0 and 

# floor(x/y)=2 which results in non-convergence. 

  

# We need the additional '-1' in the l_min computation 

# because mpz_sizeinbase(accum,2)-1 is smaller than the 

# true log_2(accum) 

l_min=l+(n_log2-(mpz_sizeinbase(accum,2)-1)-1)/(m_log2+1) 

l_max=l+(n_log2-(mpz_sizeinbase(accum,2)-1))/m_log2 

mpz_clear(temp_exp) 

mpz_clear(accum) 

sig_off() 

return l_min 

  

cpdef size_t _exact_log_mpfi_log(self,m): 

""" 

This is only for internal use only. You should expect it to crash 

and burn for negative or other malformed input. 

  

I avoid using this function until the input is large. The overhead 

associated with computing the floating point log entirely dominates 

the runtime for small values. Note that this is most definitely not 

an artifact of format conversion. Tricks with log2 approximations 

and using exact integer arithmetic are much better for small input. 

  

AUTHOR:: 

  

- Joel B. Mohler (2009-04-10) 

  

EXAMPLES:: 

  

sage: Integer(125)._exact_log_mpfi_log(3) 

4 

sage: Integer(5^150)._exact_log_mpfi_log(5) 

150 

""" 

cdef int i 

cdef list pow_2_things 

cdef int pow_2 

cdef size_t upper,lower,middle 

  

from .real_mpfi import RIF as R 

  

rif_self = R(self) 

  

sig_on() 

rif_m = R(m) 

rif_log = rif_self.log()/rif_m.log() 

# upper is *greater* than the answer 

try: 

upper = rif_log.upper().ceiling() 

except Exception: 

# ceiling is probably Infinity 

# I'm not sure what to do now 

upper = 0 

lower = rif_log.lower().floor() 

# since the log function is monotonic increasing, lower 

# and upper bracket our desired answer 

  

# if upper - lower == 1: "we are done" 

if upper - lower == 2: 

# You could test it by checking rif_m**(lower+1), but I think 

# that's a waste of time since it won't be conclusive. 

# We must test with exact integer arithmetic which takes all 

# the bits of self into account. 

sig_off() 

if self >= m**(lower+1): 

return lower + 1 

else: 

return lower 

elif upper - lower > 2: 

# this case would only happen in cases with extremely large 'self' 

rif_m = R(m) 

min_power = rif_m**lower 

middle = upper-lower 

pow_2 = 0 

while middle != 0: 

middle >>= 1 

pow_2 += 1 

# if middle was an exact power of 2, adjust down 

if (1 << (pow_2-1)) == upper-lower: 

pow_2 -= 1 

pow_2_things = [rif_m]*pow_2 

for i from 1<=i<pow_2: 

pow_2_things[i] = pow_2_things[i-1]**2 

for i from pow_2>i>=0: 

middle = lower + int(2)**i 

exp = min_power*pow_2_things[i] 

if exp > rif_self: 

upper = middle 

elif exp < rif_self: 

lower = middle 

min_power = exp 

else: 

sig_off() 

if m**middle <= self: 

return middle 

else: 

return lower 

sig_off() 

  

if upper == 0: 

raise ValueError("The input for exact_log is too large and support is not implemented.") 

  

return lower 

  

def exact_log(self, m): 

r""" 

Returns the largest integer `k` such that `m^k \leq \text{self}`, 

i.e., the floor of `\log_m(\text{self})`. 

  

This is guaranteed to return the correct answer even when the usual 

log function doesn't have sufficient precision. 

  

INPUT: 

  

- ``m`` - integer >= 2 

  

AUTHORS: 

  

- David Harvey (2006-09-15) 

- Joel B. Mohler (2009-04-08) -- rewrote this to handle small cases 

and/or easy cases up to 100x faster.. 

  

EXAMPLES:: 

  

sage: Integer(125).exact_log(5) 

3 

sage: Integer(124).exact_log(5) 

2 

sage: Integer(126).exact_log(5) 

3 

sage: Integer(3).exact_log(5) 

0 

sage: Integer(1).exact_log(5) 

0 

sage: Integer(178^1700).exact_log(178) 

1700 

sage: Integer(178^1700-1).exact_log(178) 

1699 

sage: Integer(178^1700+1).exact_log(178) 

1700 

sage: # we need to exercise the large base code path too 

sage: Integer(1780^1700-1).exact_log(1780) 

1699 

  

sage: # The following are very very fast. 

sage: # Note that for base m a perfect power of 2, we get the exact log by counting bits. 

sage: n=2983579823750185701375109835; m=32 

sage: n.exact_log(m) 

18 

sage: # The next is a favorite of mine. The log2 approximate is exact and immediately provable. 

sage: n=90153710570912709517902579010793251709257901270941709247901209742124;m=213509721309572 

sage: n.exact_log(m) 

4 

  

:: 

  

sage: x = 3^100000 

sage: RR(log(RR(x), 3)) 

100000.000000000 

sage: RR(log(RR(x + 100000), 3)) 

100000.000000000 

  

:: 

  

sage: x.exact_log(3) 

100000 

sage: (x+1).exact_log(3) 

100000 

sage: (x-1).exact_log(3) 

99999 

  

:: 

  

sage: x.exact_log(2.5) 

Traceback (most recent call last): 

... 

TypeError: Attempt to coerce non-integral RealNumber to Integer 

""" 

cdef Integer _m 

cdef Integer result 

cdef size_t n_log2 

cdef size_t m_log2 

cdef size_t guess # this will contain the final answer 

cdef bint guess_filled = 0 # this variable is only used in one branch below 

cdef mpz_t z 

if isinstance(m, Integer): 

_m=<Integer>m 

else: 

_m=<Integer>Integer(m) 

  

if mpz_sgn(self.value) <= 0 or mpz_sgn(_m.value) <= 0: 

raise ValueError("both self and m must be positive") 

if mpz_cmp_si(_m.value,2) < 0: 

raise ValueError("m must be at least 2") 

  

n_log2=mpz_sizeinbase(self.value,2)-1 

m_log2=mpz_sizeinbase(_m.value,2)-1 

if mpz_divisible_2exp_p(_m.value,m_log2): 

# Here, m is a power of 2 and the correct answer is found 

# by a log 2 approximation. 

guess = n_log2/m_log2 # truncating division 

elif n_log2/(m_log2+1) == n_log2/m_log2: 

# In this case, we have an upper bound and lower bound which 

# give the same answer, thus, the correct answer. 

guess = n_log2/m_log2 

elif m_log2 < 8: # i.e. m<256 

# if the base m is at most 256, we can use mpz_sizeinbase 

# to get the following guess which is either the exact 

# log, or 1+ the exact log 

guess = mpz_sizeinbase(self.value, mpz_get_si(_m.value)) - 1 

  

# we've already excluded the case when m is an exact power of 2 

  

if n_log2/m_log2 > 8000: 

# If we have a very large number of digits, it can be a nice 

# shortcut to test the guess using interval arithmetic. 

# (suggested by David Harvey and Carl Witty) 

# "for randomly distributed integers, the chance of this 

# interval-based comparison failing is absurdly low" 

from .real_mpfi import RIF 

approx_compare = RIF(m)**guess 

if self > approx_compare: 

guess_filled = 1 

elif self < approx_compare: 

guess_filled = 1 

guess = guess - 1 

if not guess_filled: 

# At this point, either 

# 1) self is close enough to a perfect power of m that we 

# need an exact comparison, or 

# 2) the numbers are small enough that converting to the 

# interval field is more work than the exact comparison. 

compare = _m**guess 

if self < compare: 

guess = guess - 1 

elif n_log2 < 5000: 

# for input with small exact log, it's very fast to work in exact 

# integer arithmetic starting from log2 approximations 

guess = self._exact_log_log2_iter(_m) 

else: 

# finally, we are out of easy cases this subroutine uses interval 

# arithmetic to guess and check the exact log. 

guess = self._exact_log_mpfi_log(_m) 

  

result = PY_NEW(Integer) 

mpz_set_ui(result.value,guess) 

return result 

  

def log(self, m=None, prec=None): 

r""" 

Returns symbolic log by default, unless the logarithm is exact (for 

an integer argument). When precision is given, the RealField 

approximation to that bit precision is used. 

  

This function is provided primarily so that Sage integers may be 

treated in the same manner as real numbers when convenient. Direct 

use of exact_log is probably best for arithmetic log computation. 

  

INPUT: 

  

- ``m`` - default: natural log base e 

  

- ``prec`` - integer (default: None): if None, returns 

symbolic, else to given bits of precision as in RealField 

  

EXAMPLES:: 

  

sage: Integer(124).log(5) 

log(124)/log(5) 

sage: Integer(124).log(5,100) 

2.9950093311241087454822446806 

sage: Integer(125).log(5) 

3 

sage: Integer(125).log(5,prec=53) 

3.00000000000000 

sage: log(Integer(125)) 

3*log(5) 

  

For extremely large numbers, this works:: 

  

sage: x = 3^100000 

sage: log(x,3) 

100000 

  

With the new Pynac symbolic backend, log(x) also 

works in a reasonable amount of time for this x:: 

  

sage: x = 3^100000 

sage: log(x) 

log(1334971414230...5522000001) 

  

But approximations are probably more useful in this 

case, and work to as high a precision as we desire:: 

  

sage: x.log(3,53) # default precision for RealField 

100000.000000000 

sage: (x+1).log(3,53) 

100000.000000000 

sage: (x+1).log(3,1000) 

100000.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 

  

We can use non-integer bases, with default e:: 

  

sage: x.log(2.5,prec=53) 

119897.784671579 

  

We also get logarithms of negative integers, via the 

symbolic ring, using the branch from `-pi` to `pi`:: 

  

sage: log(-1) 

I*pi 

  

The logarithm of zero is done likewise:: 

  

sage: log(0) 

-Infinity 

  

Some rational bases yield integer logarithms (:trac:`21517`):: 

  

sage: ZZ(8).log(1/2) 

-3 

  

Check that Python ints are accepted (:trac:`21518`):: 

  

sage: ZZ(8).log(int(2)) 

3 

""" 

if mpz_sgn(self.value) <= 0: 

from sage.symbolic.all import SR 

return SR(self).log() 

if m is not None and m <= 0: 

raise ValueError("m must be positive") 

if prec: 

from sage.rings.real_mpfr import RealField 

if m is None: 

return RealField(prec)(self).log() 

return RealField(prec)(self).log(m) 

  

if m is None: 

from sage.functions.log import function_log 

return function_log(self,dont_call_method_on_arg=True) 

try: 

m = Integer(m) 

except (ValueError, TypeError): 

pass 

  

if type(m) == Integer and type(self) == Integer: 

elog = self.exact_log(m) 

if m**elog == self: 

return elog 

  

if (type(m) == Rational and type(self) == Integer 

and m.numer() == 1): 

elog = -self.exact_log(m.denom()) 

if m**elog == self: 

return elog 

  

from sage.functions.log import function_log 

return function_log(self,dont_call_method_on_arg=True)/\ 

function_log(m,dont_call_method_on_arg=True) 

  

def exp(self, prec=None): 

r""" 

Returns the exponential function of self as a real number. 

  

This function is provided only so that Sage integers may be treated 

in the same manner as real numbers when convenient. 

  

INPUT: 

  

  

- ``prec`` - integer (default: None): if None, returns 

symbolic, else to given bits of precision as in RealField 

  

  

EXAMPLES:: 

  

sage: Integer(8).exp() 

e^8 

sage: Integer(8).exp(prec=100) 

2980.9579870417282747435920995 

sage: exp(Integer(8)) 

e^8 

  

For even fairly large numbers, this may not be useful. 

  

:: 

  

sage: y=Integer(145^145) 

sage: y.exp() 

e^25024207011349079210459585279553675697932183658421565260323592409432707306554163224876110094014450895759296242775250476115682350821522931225499163750010280453185147546962559031653355159703678703793369785727108337766011928747055351280379806937944746847277089168867282654496776717056860661614337004721164703369140625 

sage: y.exp(prec=53) # default RealField precision 

+infinity 

""" 

from sage.functions.all import exp 

res = exp(self, dont_call_method_on_arg=True) 

if prec: 

return res.n(prec=prec) 

return res 

  

def prime_to_m_part(self, m): 

""" 

Returns the prime-to-m part of self, i.e., the largest divisor of 

``self`` that is coprime to ``m``. 

  

INPUT: 

  

- ``m`` - Integer 

  

OUTPUT: Integer 

  

EXAMPLES:: 

  

sage: 43434.prime_to_m_part(20) 

21717 

sage: 2048.prime_to_m_part(2) 

1 

sage: 2048.prime_to_m_part(3) 

2048 

  

sage: 0.prime_to_m_part(2) 

Traceback (most recent call last): 

... 

ArithmeticError: self must be nonzero 

""" 

cdef Integer mm = Integer(m) 

  

if not self: 

raise ArithmeticError("self must be nonzero") 

if not mm: 

return one 

  

cdef Integer n = Integer(self) # need a copy as it is modified below 

  

sig_on() 

while mpz_cmp_ui(mm.value, 1): 

mpz_gcd(mm.value, n.value, mm.value) 

mpz_divexact(n.value, n.value, mm.value) 

sig_off() 

  

return n 

  

def prime_divisors(self): 

""" 

The prime divisors of self, sorted in increasing order. If n is 

negative, we do *not* include -1 among the prime divisors, since 

-1 is not a prime number. 

  

EXAMPLES:: 

  

sage: a = 1; a.prime_divisors() 

[] 

sage: a = 100; a.prime_divisors() 

[2, 5] 

sage: a = -100; a.prime_divisors() 

[2, 5] 

sage: a = 2004; a.prime_divisors() 

[2, 3, 167] 

""" 

return [r[0] for r in self.factor()] 

  

prime_factors = prime_divisors 

  

  

cpdef list _pari_divisors_small(self): 

r""" 

Return the list of divisors of this number using PARI ``divisorsu``. 

  

.. SEEALSO:: 

  

This method is better used through :meth:`divisors`. 

  

EXAMPLES:: 

  

sage: 4._pari_divisors_small() 

[1, 2, 4] 

  

The integer must fit into an unsigned long:: 

  

sage: (-4)._pari_divisors_small() 

Traceback (most recent call last): 

... 

AssertionError 

sage: (2**65)._pari_divisors_small() 

Traceback (most recent call last): 

... 

AssertionError 

""" 

# we need n to fit into a long and not a unsigned long in order to use 

# smallInteger 

assert mpz_fits_slong_p(self.value) and mpz_sgn(self.value) > 0 

  

cdef unsigned long n = mpz_get_ui(self.value) 

  

global avma 

cdef pari_sp ltop = avma 

cdef GEN d 

cdef list output 

  

try: 

sig_on() 

d = divisorsu(n) 

sig_off() 

output = [smallInteger(d[i]) for i in range(1,lg(d))] 

return output 

finally: 

avma = ltop 

  

@cython.boundscheck(False) 

@cython.wraparound(False) 

def divisors(self, method=None): 

""" 

Returns a list of all positive integer divisors of the integer 

self. 

  

EXAMPLES:: 

  

sage: (-3).divisors() 

[1, 3] 

sage: 6.divisors() 

[1, 2, 3, 6] 

sage: 28.divisors() 

[1, 2, 4, 7, 14, 28] 

sage: (2^5).divisors() 

[1, 2, 4, 8, 16, 32] 

sage: 100.divisors() 

[1, 2, 4, 5, 10, 20, 25, 50, 100] 

sage: 1.divisors() 

[1] 

sage: 0.divisors() 

Traceback (most recent call last): 

... 

ValueError: n must be nonzero 

sage: (2^3 * 3^2 * 17).divisors() 

[1, 2, 3, 4, 6, 8, 9, 12, 17, 18, 24, 34, 36, 51, 68, 72, 102, 136, 153, 204, 306, 408, 612, 1224] 

sage: a = odd_part(factorial(31)) 

sage: v = a.divisors(); len(v) 

172800 

sage: prod(e+1 for p,e in factor(a)) 

172800 

sage: all([t.divides(a) for t in v]) 

True 

  

:: 

  

sage: n = 2^551 - 1 

sage: L = n.divisors() 

sage: len(L) 

256 

sage: L[-1] == n 

True 

  

TESTS:: 

  

sage: prod(primes_first_n(64)).divisors() 

Traceback (most recent call last): 

... 

OverflowError: value too large 

sage: prod(primes_first_n(58)).divisors() 

Traceback (most recent call last): 

... 

OverflowError: value too large # 32-bit 

MemoryError: failed to allocate 288230376151711744 * 24 bytes # 64-bit 

  

Check for memory leaks and ability to interrupt 

(the ``divisors`` call below allocates about 800 MB every time, 

so a memory leak will not go unnoticed):: 

  

sage: n = prod(primes_first_n(25)) 

sage: for i in range(20): # long time 

....: try: 

....: alarm(RDF.random_element(1e-3, 0.5)) 

....: _ = n.divisors() 

....: cancel_alarm() # we never get here 

....: except AlarmInterrupt: 

....: pass 

  

Test a strange method:: 

  

sage: 100.divisors(method='hey') 

Traceback (most recent call last): 

... 

ValueError: method must be 'pari' or 'sage' 

  

  

.. NOTE:: 

  

If one first computes all the divisors and then sorts it, 

the sorting step can easily dominate the runtime. Note, 

however, that (non-negative) multiplication on the left 

preserves relative order. One can leverage this fact to 

keep the list in order as one computes it using a process 

similar to that of the merge sort algorithm. 

""" 

if mpz_cmp_ui(self.value, 0) == 0: 

raise ValueError("n must be nonzero") 

  

if (method is None or method == 'pari') and mpz_fits_slong_p(self.value): 

if mpz_sgn(self.value) > 0: 

return self._pari_divisors_small() 

else: 

return (-self)._pari_divisors_small() 

elif method is not None and method != 'sage': 

raise ValueError("method must be 'pari' or 'sage'") 

  

cdef list all, prev, sorted 

cdef Py_ssize_t tip, top 

cdef Py_ssize_t i, j, e, ee 

cdef Integer apn, p, pn, z, all_tip 

  

f = self.factor() 

  

# All of the declarations below are for optimizing the unsigned long-sized 

# case. Operations are performed in C as far as possible without 

# overflow before moving to Python objects. 

cdef unsigned long p_c, pn_c, apn_c 

cdef Py_ssize_t all_len, sorted_len, prev_len 

cdef unsigned long* ptr 

cdef unsigned long* empty_c 

cdef unsigned long* swap_tmp 

cdef unsigned long* all_c 

cdef unsigned long* sorted_c 

cdef unsigned long* prev_c 

  

# These are used to keep track of whether or not we are able to 

# perform the operations in machine words. A factor of 0.999 

# safety margin is added to cover any floating-point rounding 

# issues. 

cdef bint fits_c = True 

cdef double cur_max = 1 

cdef double fits_max = 0.999 * 2.0 ** (8*sizeof(unsigned long)) 

  

cdef Py_ssize_t divisor_count = 1 

with cython.overflowcheck(True): 

for p, e in f: 

# Using *= does not work, see 

# https://github.com/cython/cython/issues/1381 

divisor_count = divisor_count * (1 + e) 

  

ptr = <unsigned long*>check_allocarray(divisor_count, 3 * sizeof(unsigned long)) 

all_c = ptr 

sorted_c = ptr + divisor_count 

prev_c = sorted_c + divisor_count 

  

try: 

sorted_c[0] = 1 

sorted_len = 1 

  

for p, e in f: 

cur_max *= (<double>p)**e 

if fits_c and cur_max > fits_max: 

sorted = [] 

for i in range(sorted_len): 

z = <Integer>PY_NEW(Integer) 

mpz_set_ui(z.value, sorted_c[i]) 

sorted.append(z) 

fits_c = False 

sig_free(ptr) 

ptr = NULL 

  

# The two cases below are essentially the same algorithm, one 

# operating on Integers in Python lists, the other on unsigned long's. 

if fits_c: 

sig_on() 

  

pn_c = p_c = p 

  

swap_tmp = sorted_c 

sorted_c = prev_c 

prev_c = swap_tmp 

prev_len = sorted_len 

sorted_len = 0 

  

tip = 0 

prev_c[prev_len] = prev_c[prev_len-1] * pn_c 

for i in range(prev_len): 

apn_c = prev_c[i] * pn_c 

while prev_c[tip] < apn_c: 

sorted_c[sorted_len] = prev_c[tip] 

sorted_len += 1 

tip += 1 

sorted_c[sorted_len] = apn_c 

sorted_len += 1 

  

for ee in range(1, e): 

  

swap_tmp = all_c 

all_c = sorted_c 

sorted_c = swap_tmp 

all_len = sorted_len 

sorted_len = 0 

  

pn_c *= p_c 

tip = 0 

all_c[all_len] = prev_c[prev_len-1] * pn_c 

for i in range(prev_len): 

apn_c = prev_c[i] * pn_c 

while all_c[tip] < apn_c: 

sorted_c[sorted_len] = all_c[tip] 

sorted_len += 1 

tip += 1 

sorted_c[sorted_len] = apn_c 

sorted_len += 1 

  

sig_off() 

  

else: 

# fits_c is False: use mpz integers 

prev = sorted 

pn = <Integer>PY_NEW(Integer) 

mpz_set_ui(pn.value, 1) 

for ee in range(e): 

all = sorted 

sorted = [] 

tip = 0 

top = len(all) 

mpz_mul(pn.value, pn.value, p.value) # pn *= p 

for a in prev: 

# apn = a*pn 

apn = <Integer>PY_NEW(Integer) 

mpz_mul(apn.value, (<Integer>a).value, pn.value) 

while tip < top: 

all_tip = <Integer>all[tip] 

if mpz_cmp(all_tip.value, apn.value) > 0: 

break 

sorted.append(all_tip) 

tip += 1 

sorted.append(apn) 

  

if fits_c: 

# all the data is in sorted_c 

sorted = [] 

for i in range(sorted_len): 

z = <Integer>PY_NEW(Integer) 

mpz_set_ui(z.value, sorted_c[i]) 

sorted.append(z) 

finally: 

sig_free(ptr) 

  

return sorted 

  

  

def __pos__(self): 

""" 

EXAMPLES:: 

  

sage: z=43434 

sage: z.__pos__() 

43434 

""" 

return self 

  

def __abs__(self): 

""" 

Computes `|self|` 

  

EXAMPLES:: 

  

sage: z = -1 

sage: abs(z) 

1 

sage: abs(z) == abs(1) 

True 

""" 

cdef Integer x = PY_NEW(Integer) 

mpz_abs(x.value, self.value) 

return x 

  

def euclidean_degree(self): 

r""" 

Return the degree of this element as an element of an Euclidean domain. 

  

If this is an element in the ring of integers, this is simply its 

absolute value. 

  

EXAMPLES:: 

  

sage: ZZ(1).euclidean_degree() 

1 

  

""" 

from sage.rings.all import ZZ 

if self.parent() is ZZ: 

return abs(self) 

raise NotImplementedError 

  

def sign(self): 

""" 

Returns the sign of this integer, which is -1, 0, or 1 

depending on whether this number is negative, zero, or positive 

respectively. 

  

OUTPUT: Integer 

  

EXAMPLES:: 

  

sage: 500.sign() 

1 

sage: 0.sign() 

0 

sage: (-10^43).sign() 

-1 

""" 

return smallInteger(mpz_sgn(self.value)) 

  

def __mod__(x, y): 

r""" 

Return x modulo y. 

  

EXAMPLES:: 

  

sage: z = 43 

sage: z % 2 

1 

sage: z % 0 

Traceback (most recent call last): 

... 

ZeroDivisionError: Integer modulo by zero 

sage: -5 % 7 

2 

sage: -5 % -7 

-5 

sage: 5 % -7 

-2 

sage: 5 % int(-7) 

-2 

sage: int(5) % -7 

-2 

sage: int(5) % int(-7) 

-2 

  

TESTS:: 

  

sage: signs = [(11,5), (11,-5), (-11,5), (-11,-5)] 

sage: control = [int(a) % int(b) for a, b in signs] 

sage: [a % b for a,b in signs] == control 

True 

sage: [a % int(b) for a,b in signs] == control 

True 

sage: [int(a) % b for a,b in signs] == control 

True 

  

This example caused trouble in :trac:`6083`:: 

  

sage: a = next_prime(2**31) 

sage: b = Integers(a)(100) 

sage: a % b 

Traceback (most recent call last): 

... 

ArithmeticError: reduction modulo 100 not defined 

""" 

cdef Integer z 

  

# First case: Integer % Integer 

if type(x) is type(y): 

if not mpz_sgn((<Integer>y).value): 

raise ZeroDivisionError("Integer modulo by zero") 

z = <Integer>PY_NEW(Integer) 

if mpz_size((<Integer>x).value) > 100000: 

sig_on() 

mpz_fdiv_r(z.value, (<Integer>x).value, (<Integer>y).value) 

sig_off() 

else: 

mpz_fdiv_r(z.value, (<Integer>x).value, (<Integer>y).value) 

return z 

  

# Next: Integer % C long 

cdef long yy = 0 

cdef int err = 0 

if not isinstance(y, Element): 

# x must be an Integer in this case 

if not integer_check_long(y, &yy, &err): 

# y cannot be converted to an integer 

return NotImplemented 

if err: 

# y is some kind of integer, 

# but too large for a C long 

return x % Integer(y) 

  

if yy == 0: 

raise ZeroDivisionError("Integer modulo by zero") 

z = <Integer>PY_NEW(Integer) 

if yy > 0: 

mpz_fdiv_r_ui(z.value, (<Integer>x).value, yy) 

else: 

mpz_cdiv_r_ui(z.value, (<Integer>x).value, -<unsigned long>yy) 

return z 

  

# Use the coercion model 

return coercion_model.bin_op(x, y, operator.mod) 

  

def quo_rem(Integer self, other): 

""" 

Returns the quotient and the remainder of self divided by other. 

Note that the remainder returned is always either zero or of the 

same sign as other. 

  

INPUT: 

  

- ``other`` - the divisor 

  

OUTPUT: 

  

- ``q`` - the quotient of self/other 

  

- ``r`` - the remainder of self/other 

  

EXAMPLES:: 

  

sage: z = Integer(231) 

sage: z.quo_rem(2) 

(115, 1) 

sage: z.quo_rem(-2) 

(-116, -1) 

sage: z.quo_rem(0) 

Traceback (most recent call last): 

... 

ZeroDivisionError: Integer division by zero 

  

sage: a = ZZ.random_element(10**50) 

sage: b = ZZ.random_element(10**15) 

sage: q, r = a.quo_rem(b) 

sage: q*b + r == a 

True 

  

sage: 3.quo_rem(ZZ['x'].0) 

(0, 3) 

  

TESTS: 

  

The divisor can be rational as well, although the remainder 

will always be zero (:trac:`7965`):: 

  

sage: 5.quo_rem(QQ(2)) 

(5/2, 0) 

sage: 5.quo_rem(2/3) 

(15/2, 0) 

  

""" 

cdef Integer q = PY_NEW(Integer) 

cdef Integer r = PY_NEW(Integer) 

cdef long d, res 

  

if type(other) is int: 

d = PyInt_AS_LONG(other) 

if d > 0: 

mpz_fdiv_qr_ui(q.value, r.value, self.value, d) 

elif d == 0: 

raise ZeroDivisionError("Integer division by zero") 

else: 

res = mpz_fdiv_qr_ui(q.value, r.value, self.value, -d) 

mpz_neg(q.value, q.value) 

if res: 

mpz_sub_ui(q.value, q.value, 1) 

mpz_sub_ui(r.value, r.value, -d) 

  

elif type(other) is Integer: 

if mpz_sgn((<Integer>other).value) == 0: 

raise ZeroDivisionError("Integer division by zero") 

if mpz_size(self.value) > 100000: 

sig_on() 

mpz_fdiv_qr(q.value, r.value, self.value, (<Integer>other).value) 

sig_off() 

else: 

mpz_fdiv_qr(q.value, r.value, self.value, (<Integer>other).value) 

  

else: 

left, right = coercion_model.canonical_coercion(self, other) 

return left.quo_rem(right) 

  

return q, r 

  

def powermod(self, exp, mod): 

""" 

Compute self\*\*exp modulo mod. 

  

EXAMPLES:: 

  

sage: z = 2 

sage: z.powermod(31,31) 

2 

sage: z.powermod(0,31) 

1 

sage: z.powermod(-31,31) == 2^-31 % 31 

True 

  

As expected, the following is invalid:: 

  

sage: z.powermod(31,0) 

Traceback (most recent call last): 

... 

ZeroDivisionError: cannot raise to a power modulo 0 

""" 

cdef Integer x, _exp, _mod 

_exp = Integer(exp); _mod = Integer(mod) 

if mpz_cmp_si(_mod.value,0) == 0: 

raise ZeroDivisionError("cannot raise to a power modulo 0") 

  

x = PY_NEW(Integer) 

  

sig_on() 

mpz_powm(x.value, self.value, _exp.value, _mod.value) 

sig_off() 

  

return x 

  

def rational_reconstruction(self, Integer m): 

""" 

Return the rational reconstruction of this integer modulo m, i.e., 

the unique (if it exists) rational number that reduces to self 

modulo m and whose numerator and denominator is bounded by 

sqrt(m/2). 

  

INPUT: 

  

- ``self`` -- Integer 

  

- ``m`` -- Integer 

  

OUTPUT: 

  

- a :class:`Rational` 

  

EXAMPLES:: 

  

sage: (3/7)%100 

29 

sage: (29).rational_reconstruction(100) 

3/7 

  

TESTS: 

  

Check that :trac:`9345` is fixed:: 

  

sage: 0.rational_reconstruction(0) 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational reconstruction with zero modulus 

sage: ZZ.random_element(-10^6, 10^6).rational_reconstruction(0) 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational reconstruction with zero modulus 

""" 

cdef Integer a 

cdef Rational x = <Rational>Rational.__new__(Rational) 

try: 

mpq_rational_reconstruction(x.value, self.value, m.value) 

except ValueError: 

a = self % m 

raise ArithmeticError("rational reconstruction of %s (mod %s) does not exist" % (a, m)) 

return x 

  

powermodm_ui = deprecated_function_alias(17852, powermod) 

  

def __int__(self): 

""" 

Return the Python int (or long) corresponding to this Sage 

integer. 

  

EXAMPLES:: 

  

sage: n = 920938 

sage: int(n) 

920938 

sage: int(-n) 

-920938 

sage: type(n.__int__()) 

<... 'int'> 

sage: n = 99028390823409823904823098490238409823490820938 

sage: int(n) 

99028390823409823904823098490238409823490820938L 

sage: int(-n) 

-99028390823409823904823098490238409823490820938L 

sage: type(n.__int__()) 

<type 'long'> 

sage: int(-1), int(0), int(1) 

(-1, 0, 1) 

""" 

return mpz_get_pyintlong(self.value) 

  

def __long__(self): 

""" 

Return the Python long corresponding to this Sage integer. 

  

EXAMPLES:: 

  

sage: n = 9023408290348092849023849820934820938490234290 

sage: long(n) 

9023408290348092849023849820934820938490234290L 

sage: long(-n) 

-9023408290348092849023849820934820938490234290L 

sage: n = 920938 

sage: long(n) 

920938L 

sage: n.__long__() 

920938L 

sage: long(-1), long(0), long(1) 

(-1L, 0L, 1L) 

""" 

return mpz_get_pylong(self.value) 

  

def __float__(self): 

""" 

Return double precision floating point representation of this 

integer. 

  

EXAMPLES:: 

  

sage: n = Integer(17); float(n) 

17.0 

sage: n = Integer(902834098234908209348209834092834098); float(n) 

9.028340982349083e+35 

sage: n = Integer(-57); float(n) 

-57.0 

sage: n.__float__() 

-57.0 

sage: type(n.__float__()) 

<... 'float'> 

""" 

return mpz_get_d_nearest(self.value) 

  

def _rpy_(self): 

""" 

Returns int(self) so that rpy can convert self into an object it 

knows how to work with. 

  

EXAMPLES:: 

  

sage: n = 100 

sage: n._rpy_() 

100 

sage: type(n._rpy_()) 

<... 'int'> 

""" 

return self.__int__() 

  

def __hash__(self): 

""" 

Return the hash of this integer. 

  

This agrees with the Python hash of the corresponding Python int or 

long. 

  

EXAMPLES:: 

  

sage: n = -920384; n.__hash__() 

-920384 

sage: hash(int(n)) 

-920384 

sage: n = -920390823904823094890238490238484; n.__hash__() 

-873977844 # 32-bit 

6874330978542788722 # 64-bit 

sage: hash(long(n)) 

-873977844 # 32-bit 

6874330978542788722 # 64-bit 

  

TESTS:: 

  

sage: hash(-1), hash(0), hash(1) 

(-2, 0, 1) 

sage: n = 2^31 + 2^63 + 2^95 + 2^127 + 2^128*(2^32-2) 

sage: hash(n) == hash(long(n)) 

True 

sage: hash(n-1) == hash(long(n-1)) 

True 

sage: hash(-n) == hash(long(-n)) 

True 

sage: hash(1-n) == hash(long(1-n)) 

True 

sage: n = 2^63 + 2^127 + 2^191 + 2^255 + 2^256*(2^64-2) 

sage: hash(n) == hash(long(n)) 

True 

sage: hash(n-1) == hash(long(n-1)) 

True 

sage: hash(-n) == hash(long(-n)) 

True 

sage: hash(1-n) == hash(long(1-n)) 

True 

  

These tests come from :trac:`4957`:: 

  

sage: n = 2^31 + 2^13 

sage: hash(n) 

-2147475456 # 32-bit 

2147491840 # 64-bit 

sage: hash(n) == hash(int(n)) 

True 

sage: n = 2^63 + 2^13 

sage: hash(n) 

-2147475456 # 32-bit 

-9223372036854767616 # 64-bit 

sage: hash(n) == hash(int(n)) 

True 

""" 

return mpz_pythonhash(self.value) 

  

cdef hash_c(self): 

""" 

A C version of the __hash__ function. 

""" 

return mpz_pythonhash(self.value) 

  

def trial_division(self, long bound=LONG_MAX, long start=2): 

""" 

Return smallest prime divisor of self up to bound, beginning 

checking at start, or abs(self) if no such divisor is found. 

  

INPUT: 

  

- ``bound`` -- a positive integer that fits in a C signed long 

- ``start`` -- a positive integer that fits in a C signed long 

  

OUTPUT: 

  

- a positive integer 

  

EXAMPLES:: 

  

sage: n = next_prime(10^6)*next_prime(10^7); n.trial_division() 

1000003 

sage: (-n).trial_division() 

1000003 

sage: n.trial_division(bound=100) 

10000049000057 

sage: n.trial_division(bound=-10) 

Traceback (most recent call last): 

... 

ValueError: bound must be positive 

sage: n.trial_division(bound=0) 

Traceback (most recent call last): 

... 

ValueError: bound must be positive 

sage: ZZ(0).trial_division() 

Traceback (most recent call last): 

... 

ValueError: self must be nonzero 

  

sage: n = next_prime(10^5) * next_prime(10^40); n.trial_division() 

100003 

sage: n.trial_division(bound=10^4) 

1000030000000000000000000000000000000012100363 

sage: (-n).trial_division(bound=10^4) 

1000030000000000000000000000000000000012100363 

sage: (-n).trial_division() 

100003 

sage: n = 2 * next_prime(10^40); n.trial_division() 

2 

sage: n = 3 * next_prime(10^40); n.trial_division() 

3 

sage: n = 5 * next_prime(10^40); n.trial_division() 

5 

sage: n = 2 * next_prime(10^4); n.trial_division() 

2 

sage: n = 3 * next_prime(10^4); n.trial_division() 

3 

sage: n = 5 * next_prime(10^4); n.trial_division() 

5 

  

You can specify a starting point:: 

  

sage: n = 3*5*101*103 

sage: n.trial_division(start=50) 

101 

""" 

if bound <= 0: 

raise ValueError("bound must be positive") 

if mpz_sgn(self.value) == 0: 

raise ValueError("self must be nonzero") 

cdef unsigned long n, m=7, i=1, limit 

cdef unsigned long dif[8] 

if start > 7: 

# We need to find i. 

m = start % 30 

if 0 <= m <= 1: 

i = 0; m = start + (1-m) 

elif 1 < m <= 7: 

i = 1; m = start + (7-m) 

elif 7 < m <= 11: 

i = 2; m = start + (11-m) 

elif 11 < m <= 13: 

i = 3; m = start + (13-m) 

elif 13 < m <= 17: 

i = 4; m = start + (17-m) 

elif 17 < m <= 19: 

i = 5; m = start + (19-m) 

elif 19 < m <= 23: 

i = 6; m = start + (23-m) 

elif 23 < m <= 29: 

i = 7; m = start + (29-m) 

dif[0]=6;dif[1]=4;dif[2]=2;dif[3]=4;dif[4]=2;dif[5]=4;dif[6]=6;dif[7]=2 

cdef Integer x = PY_NEW(Integer) 

if mpz_fits_ulong_p(self.value): 

n = mpz_get_ui(self.value) # ignores the sign automatically 

if n == 1: return one 

if start <= 2 and n%2==0: 

mpz_set_ui(x.value,2); return x 

if start <= 3 and n%3==0: 

mpz_set_ui(x.value,3); return x 

if start <= 5 and n%5==0: 

mpz_set_ui(x.value,5); return x 

limit = <unsigned long> sqrt_double(<double> n) 

if bound < limit: limit = bound 

# Algorithm: only trial divide by numbers that 

# are congruent to 1,7,11,13,17,19,23,29 mod 30=2*3*5. 

while m <= limit: 

if n%m == 0: 

mpz_set_ui(x.value, m); return x 

m += dif[i%8] 

i += 1 

mpz_abs(x.value, self.value) 

return x 

else: 

# self is big -- it doesn't fit in unsigned long. 

if start <= 2 and mpz_even_p(self.value): 

mpz_set_ui(x.value,2); return x 

if start <= 3 and mpz_divisible_ui_p(self.value,3): 

mpz_set_ui(x.value,3); return x 

if start <= 5 and mpz_divisible_ui_p(self.value,5): 

mpz_set_ui(x.value,5); return x 

  

# x.value = floor(sqrt(self.value)) 

sig_on() 

mpz_abs(x.value, self.value) 

mpz_sqrt(x.value, x.value) 

if mpz_cmp_si(x.value, bound) < 0: 

limit = mpz_get_ui(x.value) 

else: 

limit = bound 

while m <= limit: 

if mpz_divisible_ui_p(self.value, m): 

mpz_set_ui(x.value, m) 

sig_off() 

return x 

m += dif[i%8] 

i += 1 

mpz_abs(x.value, self.value) 

sig_off() 

return x 

  

def factor(self, algorithm='pari', proof=None, limit=None, int_=False, 

verbose=0): 

""" 

Return the prime factorization of this integer as a 

formal Factorization object. 

  

INPUT: 

  

- ``algorithm`` - string 

  

- ``'pari'`` - (default) use the PARI library 

  

- ``'kash'`` - use the KASH computer algebra system (requires 

the optional kash package) 

  

- ``'magma'`` - use the MAGMA computer algebra system (requires 

an installation of MAGMA) 

  

- ``'qsieve'`` - use Bill Hart's quadratic sieve code; 

WARNING: this may not work as expected, see qsieve? for 

more information 

  

- ``'ecm'`` - use ECM-GMP, an implementation of Hendrik 

Lenstra's elliptic curve method. 

  

- ``proof`` - bool (default: True) whether or not to prove 

primality of each factor (only applicable for ``'pari'`` 

and ``'ecm'``). 

  

- ``limit`` - int or None (default: None) if limit is 

given it must fit in a signed int, and the factorization is done 

using trial division and primes up to limit. 

  

OUTPUT: 

  

- a Factorization object containing the prime factors and 

their multiplicities 

  

EXAMPLES:: 

  

sage: n = 2^100 - 1; n.factor() 

3 * 5^3 * 11 * 31 * 41 * 101 * 251 * 601 * 1801 * 4051 * 8101 * 268501 

  

This factorization can be converted into a list of pairs `(p, 

e)`, where `p` is prime and `e` is a positive integer. Each 

pair can also be accessed directly by its index (ordered by 

increasing size of the prime):: 

  

sage: f = 60.factor() 

sage: list(f) 

[(2, 2), (3, 1), (5, 1)] 

sage: f[2] 

(5, 1) 

  

Similarly, the factorization can be converted to a dictionary 

so the exponent can be extracted for each prime:: 

  

sage: f = (3^6).factor() 

sage: dict(f) 

{3: 6} 

sage: dict(f)[3] 

6 

  

We use proof=False, which doesn't prove correctness of the primes 

that appear in the factorization:: 

  

sage: n = 920384092842390423848290348203948092384082349082 

sage: n.factor(proof=False) 

2 * 11 * 1531 * 4402903 * 10023679 * 619162955472170540533894518173 

sage: n.factor(proof=True) 

2 * 11 * 1531 * 4402903 * 10023679 * 619162955472170540533894518173 

  

We factor using trial division only:: 

  

sage: n.factor(limit=1000) 

2 * 11 * 41835640583745019265831379463815822381094652231 

  

We factor using a quadratic sieve algorithm:: 

  

sage: p = next_prime(10^20) 

sage: q = next_prime(10^21) 

sage: n = p*q 

sage: n.factor(algorithm='qsieve') 

doctest:... RuntimeWarning: the factorization returned 

by qsieve may be incomplete (the factors may not be prime) 

or even wrong; see qsieve? for details 

100000000000000000039 * 1000000000000000000117 

  

We factor using the elliptic curve method:: 

  

sage: p = next_prime(10^15) 

sage: q = next_prime(10^21) 

sage: n = p*q 

sage: n.factor(algorithm='ecm') 

1000000000000037 * 1000000000000000000117 

  

TESTS:: 

  

sage: n = 42 

sage: n.factor(algorithm='foobar') 

Traceback (most recent call last): 

... 

ValueError: Algorithm is not known 

""" 

from sage.structure.factorization import Factorization 

from sage.structure.factorization_integer import IntegerFactorization 

  

if algorithm not in ['pari', 'kash', 'magma', 'qsieve', 'ecm']: 

raise ValueError("Algorithm is not known") 

  

cdef Integer n, p, unit 

cdef int i 

cdef n_factor_t f 

  

if mpz_sgn(self.value) == 0: 

raise ArithmeticError("factorization of 0 is not defined") 

  

if mpz_sgn(self.value) > 0: 

n = self 

unit = one 

else: 

n = PY_NEW(Integer) 

unit = PY_NEW(Integer) 

mpz_neg(n.value, self.value) 

mpz_set_si(unit.value, -1) 

  

if mpz_cmpabs_ui(n.value, 1) == 0: 

return IntegerFactorization([], unit=unit, unsafe=True, 

sort=False, simplify=False) 

  

if limit is not None: 

from sage.rings.factorint import factor_trial_division 

return factor_trial_division(self, limit) 

  

if mpz_fits_slong_p(n.value): 

if proof is None: 

from sage.structure.proof.proof import get_flag 

proof = get_flag(proof, "arithmetic") 

n_factor_init(&f) 

n_factor(&f, mpz_get_ui(n.value), proof) 

F = [(Integer(f.p[i]), int(f.exp[i])) for i from 0 <= i < f.num] 

F.sort() 

return IntegerFactorization(F, unit=unit, unsafe=True, 

sort=False, simplify=False) 

  

if mpz_sizeinbase(n.value, 2) < 40: 

from sage.rings.factorint import factor_trial_division 

return factor_trial_division(self) 

  

if algorithm == 'pari': 

from sage.rings.factorint import factor_using_pari 

F = factor_using_pari(n, int_=int_, debug_level=verbose, proof=proof) 

F.sort() 

return IntegerFactorization(F, unit=unit, unsafe=True, 

sort=False, simplify=False) 

elif algorithm in ['kash', 'magma']: 

if algorithm == 'kash': 

from sage.interfaces.all import kash as I 

else: 

from sage.interfaces.all import magma as I 

str_res = I.eval('Factorization(%s)'%n) 

# The result looks like "[ <n1, p1>, <p2, e2>, ... ] 

str_res = str_res.replace(']', '').replace('[', '').replace('>', '').replace('<', '').split(',') 

res = [int(s.strip()) for s in str_res] 

exp_type = int if int_ else Integer 

F = [(Integer(p), exp_type(e)) for p,e in zip(res[0::2], res[1::2])] 

return Factorization(F, unit) 

elif algorithm == 'qsieve': 

message = "the factorization returned by qsieve may be incomplete (the factors may not be prime) or even wrong; see qsieve? for details" 

from warnings import warn 

warn(message, RuntimeWarning, stacklevel=5) 

from sage.interfaces.qsieve import qsieve 

res = [(p, 1) for p in qsieve(n)[0]] 

F = IntegerFactorization(res, unit) 

return F 

else: 

from sage.interfaces.ecm import ecm 

res = [(p, 1) for p in ecm.factor(n, proof=proof)] 

F = IntegerFactorization(res, unit) 

return F 

  

def support(self): 

""" 

Return a sorted list of the primes dividing this integer. 

  

OUTPUT: The sorted list of primes appearing in the factorization of 

this rational with positive exponent. 

  

EXAMPLES:: 

  

sage: factorial(10).support() 

[2, 3, 5, 7] 

sage: (-999).support() 

[3, 37] 

  

Trying to find the support of 0 gives an arithmetic error:: 

  

sage: 0.support() 

Traceback (most recent call last): 

... 

ArithmeticError: Support of 0 not defined. 

""" 

if self.is_zero(): 

raise ArithmeticError("Support of 0 not defined.") 

return sage.arith.all.prime_factors(self) 

  

def coprime_integers(self, m): 

""" 

Return the positive integers `< m` that are coprime to 

this integer. 

  

EXAMPLES:: 

  

sage: n = 8 

sage: n.coprime_integers(8) 

[1, 3, 5, 7] 

sage: n.coprime_integers(11) 

[1, 3, 5, 7, 9] 

sage: n = 5; n.coprime_integers(10) 

[1, 2, 3, 4, 6, 7, 8, 9] 

sage: n.coprime_integers(5) 

[1, 2, 3, 4] 

sage: n = 99; n.coprime_integers(99) 

[1, 2, 4, 5, 7, 8, 10, 13, 14, 16, 17, 19, 20, 23, 25, 26, 28, 29, 31, 32, 34, 35, 37, 38, 40, 41, 43, 46, 47, 49, 50, 52, 53, 56, 58, 59, 61, 62, 64, 65, 67, 68, 70, 71, 73, 74, 76, 79, 80, 82, 83, 85, 86, 89, 91, 92, 94, 95, 97, 98] 

  

TESTS:: 

  

sage: for n in srange(-6,7): 

....: for m in range(1,abs(n)+3): 

....: assert n.coprime_integers(m) == [k for k in srange(1,m) if gcd(k,n) == 1] 

  

AUTHORS: 

  

- Naqi Jaffery (2006-01-24): examples 

  

- David Roe (2017-10-02): Now uses sieving for larger inputs 

  

ALGORITHM: 

  

Create an integer with `m` bits and set bits at every multiple 

of a prime `p` that divides this integer and is less than `m`. 

Then return a list of integers corresponding to the unset bits. 

""" 

cdef Integer sieve, p, slf, mInteger = Integer(m) 

if mpz_cmp_ui(mInteger.value, 1) <= 0: 

return [] 

if mpz_sgn(self.value) == 0: 

return [one] 

if mpz_fits_slong_p(mInteger.value) == 0: 

raise ValueError("m is too large") 

cdef long mlong = mpz_get_si(mInteger.value) 

cdef unsigned long ilong, plong 

if mpz_cmpabs_ui(self.value, 1) == 0: 

return [Integer(ilong) for ilong in range(1, mlong)] 

if (mpz_cmpabs(self.value, mInteger.value) >= 0 and 

(mpz_sgn(self.value) > 0 and self.is_prime() or 

mpz_sgn(self.value) < 0 and (-self).is_prime())): 

return [Integer(ilong) for ilong in range(1, mlong)] 

sieve = PY_NEW(Integer) 

p = one 

slf = PY_NEW(Integer) 

mpz_set(slf.value, self.value) 

while True: 

p = slf.trial_division(mlong, mpz_get_si(p.value)+1) 

if mpz_cmp_si(p.value, mlong) >= 0: 

# p is larger than m, so no more primes are needed. 

break 

sig_on() 

ilong = plong = mpz_get_ui(p.value) 

while ilong < mlong: 

# Set bits in sieve at each multiple of p 

mpz_setbit(sieve.value, ilong) 

ilong += plong 

# Now divide by p until no ps remain 

mpz_divexact_ui(slf.value, slf.value, plong) 

while mpz_divisible_ui_p(slf.value, plong): 

mpz_divexact_ui(slf.value, slf.value, plong) 

sig_off() 

# If we have found all factors, we break 

if mpz_cmpabs_ui(slf.value, 1) == 0: 

break 

return [Integer(ilong) for ilong in range(1, mlong) 

if mpz_tstbit(sieve.value, ilong) == 0] 

  

def divides(self, n): 

""" 

Return True if self divides n. 

  

EXAMPLES:: 

  

sage: Z = IntegerRing() 

sage: Z(5).divides(Z(10)) 

True 

sage: Z(0).divides(Z(5)) 

False 

sage: Z(10).divides(Z(5)) 

False 

""" 

cdef bint t 

cdef Integer _n 

_n = Integer(n) 

if mpz_sgn(self.value) == 0: 

return mpz_sgn(_n.value) == 0 

sig_on() 

t = mpz_divisible_p(_n.value, self.value) 

sig_off() 

return t 

  

cpdef RingElement _valuation(Integer self, Integer p): 

r""" 

Return the p-adic valuation of self. 

  

We do not require that p be prime, but it must be at least 2. For 

more documentation see ``valuation`` 

  

AUTHORS: 

  

- David Roe (3/31/07) 

""" 

if mpz_sgn(self.value) == 0: 

return sage.rings.infinity.infinity 

if mpz_cmp_ui(p.value, 2) < 0: 

raise ValueError("You can only compute the valuation with respect to a integer larger than 1.") 

  

cdef Integer v = PY_NEW(Integer) 

cdef mpz_t u 

mpz_init(u) 

sig_on() 

mpz_set_ui(v.value, mpz_remove(u, self.value, p.value)) 

sig_off() 

mpz_clear(u) 

return v 

  

cdef object _val_unit(Integer self, Integer p): 

r""" 

Returns a pair: the p-adic valuation of self, and the p-adic unit 

of self. 

  

We do not require the p be prime, but it must be at least 2. For 

more documentation see ``val_unit`` 

  

AUTHORS: 

  

- David Roe (2007-03-31) 

""" 

cdef Integer v, u 

if mpz_cmp_ui(p.value, 2) < 0: 

raise ValueError("You can only compute the valuation with respect to a integer larger than 1.") 

if self == 0: 

u = one 

return (sage.rings.infinity.infinity, u) 

v = PY_NEW(Integer) 

u = PY_NEW(Integer) 

sig_on() 

mpz_set_ui(v.value, mpz_remove(u.value, self.value, p.value)) 

sig_off() 

return (v, u) 

  

def valuation(self, p): 

""" 

Return the p-adic valuation of self. 

  

INPUT: 

  

- ``p`` - an integer at least 2. 

  

EXAMPLES:: 

  

sage: n = 60 

sage: n.valuation(2) 

2 

sage: n.valuation(3) 

1 

sage: n.valuation(7) 

0 

sage: n.valuation(1) 

Traceback (most recent call last): 

... 

ValueError: You can only compute the valuation with respect to a integer larger than 1. 

  

We do not require that p is a prime:: 

  

sage: (2^11).valuation(4) 

5 

""" 

return self._valuation(Integer(p)) 

  

# Alias for valuation 

ord = valuation 

  

def val_unit(self, p): 

r""" 

Returns a pair: the p-adic valuation of self, and the p-adic unit 

of self. 

  

INPUT: 

  

- ``p`` - an integer at least 2. 

  

OUTPUT: 

  

- ``v_p(self)`` - the p-adic valuation of ``self`` 

  

- ``u_p(self)`` - ``self`` / `p^{v_p(\mathrm{self})}` 

  

EXAMPLES:: 

  

sage: n = 60 

sage: n.val_unit(2) 

(2, 15) 

sage: n.val_unit(3) 

(1, 20) 

sage: n.val_unit(7) 

(0, 60) 

sage: (2^11).val_unit(4) 

(5, 2) 

sage: 0.val_unit(2) 

(+Infinity, 1) 

""" 

return self._val_unit(Integer(p)) 

  

def odd_part(self): 

r""" 

The odd part of the integer `n`. This is `n / 2^v`, 

where `v = \mathrm{valuation}(n,2)`. 

  

IMPLEMENTATION: 

  

Currently returns 0 when self is 0. This behaviour is fairly arbitrary, 

and in Sage 4.6 this special case was not handled at all, eventually 

propagating a TypeError. The caller should not rely on the behaviour 

in case self is 0. 

  

EXAMPLES:: 

  

sage: odd_part(5) 

5 

sage: odd_part(4) 

1 

sage: odd_part(factorial(31)) 

122529844256906551386796875 

""" 

cdef Integer odd 

cdef unsigned long bits 

  

if mpz_cmpabs_ui(self.value, 1) <= 0: 

return self 

  

odd = PY_NEW(Integer) 

bits = mpz_scan1(self.value, 0) 

mpz_tdiv_q_2exp(odd.value, self.value, bits) 

return odd 

  

cdef Integer _divide_knowing_divisible_by(Integer self, Integer right): 

r""" 

Returns the integer self / right when self is divisible by right. 

  

If self is not divisible by right, the return value is undefined, 

and may not even be close to self/right. For more documentation see 

``divide_knowing_divisible_by`` 

  

AUTHORS: 

  

- David Roe (2007-03-31) 

""" 

if mpz_cmp_ui(right.value, 0) == 0: 

raise ZeroDivisionError 

cdef Integer x 

x = PY_NEW(Integer) 

if mpz_size(self.value) + mpz_size((<Integer>right).value) > 100000: 

# Only use the signal handler (to enable ctrl-c out) when the 

# quotient might take a while to compute 

sig_on() 

mpz_divexact(x.value, self.value, right.value) 

sig_off() 

else: 

mpz_divexact(x.value, self.value, right.value) 

return x 

  

def divide_knowing_divisible_by(self, right): 

r""" 

Returns the integer self / right when self is divisible by right. 

  

If self is not divisible by right, the return value is undefined, 

and may not even be close to self/right for multi-word integers. 

  

EXAMPLES:: 

  

sage: a = 8; b = 4 

sage: a.divide_knowing_divisible_by(b) 

2 

sage: (100000).divide_knowing_divisible_by(25) 

4000 

sage: (100000).divide_knowing_divisible_by(26) # close (random) 

3846 

  

However, often it's way off. 

  

:: 

  

sage: a = 2^70; a 

1180591620717411303424 

sage: a // 11 # floor divide 

107326510974310118493 

sage: a.divide_knowing_divisible_by(11) # way off and possibly random 

43215361478743422388970455040 

""" 

return self._divide_knowing_divisible_by(right) 

  

def _lcm(self, Integer n): 

""" 

Returns the least common multiple of self and `n`. 

  

EXAMPLES:: 

  

sage: n = 60 

sage: n._lcm(150) 

300 

""" 

cdef Integer z = PY_NEW(Integer) 

sig_on() 

mpz_lcm(z.value, self.value, n.value) 

sig_off() 

return z 

  

def denominator(self): 

""" 

Return the denominator of this integer, which of course is 

always 1. 

  

EXAMPLES:: 

  

sage: x = 5 

sage: x.denominator() 

1 

sage: x = 0 

sage: x.denominator() 

1 

""" 

return one 

  

def numerator(self): 

""" 

Return the numerator of this integer. 

  

EXAMPLES:: 

  

sage: x = 5 

sage: x.numerator() 

5 

  

:: 

  

sage: x = 0 

sage: x.numerator() 

0 

""" 

return self 

  

def factorial(self): 

r""" 

Return the factorial `n! = 1 \cdot 2 \cdot 3 \cdots n`. 

  

If the input does not fit in an ``unsigned long int`` a symbolic 

expression is returned. 

  

EXAMPLES:: 

  

sage: for n in srange(7): 

....: print("{} {}".format(n, n.factorial())) 

0 1 

1 1 

2 2 

3 6 

4 24 

5 120 

6 720 

sage: 234234209384023842034.factorial() 

factorial(234234209384023842034) 

""" 

if mpz_sgn(self.value) < 0: 

raise ValueError("factorial -- self = (%s) must be nonnegative"%self) 

  

if not mpz_fits_uint_p(self.value): 

from sage.functions.all import factorial 

return factorial(self, hold=True) 

  

cdef Integer z = PY_NEW(Integer) 

  

sig_on() 

mpz_fac_ui(z.value, mpz_get_ui(self.value)) 

sig_off() 

  

return z 

  

@cython.cdivision(True) 

def multifactorial(self, int k): 

r""" 

Compute the k-th factorial `n!^{(k)}` of self. 

  

For k=1 this is the standard factorial, and for k greater than 

one it is the product of every k-th terms down from self to 

k. The recursive definition is used to extend this function to 

the negative integers. 

  

EXAMPLES:: 

  

sage: 5.multifactorial(1) 

120 

sage: 5.multifactorial(2) 

15 

sage: 5.multifactorial(3) 

10 

sage: 23.multifactorial(2) 

316234143225 

sage: prod([1..23, step=2]) 

316234143225 

sage: (-29).multifactorial(7) 

1/2640 

  

TESTS:: 

  

sage: for a in range(1,20): 

....: for b in range(1,20): 

....: assert ZZ(a).multifactorial(b) == prod(range(a,0,-b)) 

""" 

if k <= 0: 

raise ValueError("multifactorial only defined for positive values of k") 

  

if not mpz_fits_sint_p(self.value): 

raise ValueError("multifactorial not implemented for n >= 2^32.\nThis is probably OK, since the answer would have billions of digits.") 

  

cdef int n = mpz_get_si(self.value) 

  

# base case 

if 0 < n <= k: 

return n 

  

# easy to calculate 

elif n % k == 0: 

factorial = Integer(n/k).factorial() 

if k == 2: 

return factorial << (n/k) 

else: 

return factorial * Integer(k)**(n/k) 

  

# negative base case 

elif -k < n < 0: 

return one / (self+k) 

  

# reflection case 

elif n < -k: 

if (n/k) % 2: 

sign = -one 

else: 

sign = one 

return sign / Integer(-k-n).multifactorial(k) 

  

# compute the actual product, optimizing the number of large 

# multiplications 

cdef int i,j 

  

# we need (at most) log_2(#factors) concurrent sub-products 

cdef int prod_count = <int>ceil_c(log_c(n/k+1)/log_c(2)) + 1 

cdef mpz_t* sub_prods = <mpz_t*>check_allocarray(prod_count, sizeof(mpz_t)) 

for i from 0 <= i < prod_count: 

mpz_init(sub_prods[i]) 

  

sig_on() 

  

cdef residue = n % k 

mpz_set_ui(sub_prods[0], residue) 

cdef int tip = 1 

for i from 1 <= i <= n//k: 

mpz_set_ui(sub_prods[tip], k*i + residue) 

# for the i-th terms we use the bits of i to calculate how many 

# times we need to multiply "up" the stack of sub-products 

for j from 0 <= j < 32: 

if not (i & (1 << j)): 

break 

tip -= 1 

mpz_mul(sub_prods[tip], sub_prods[tip], sub_prods[tip+1]) 

tip += 1 

cdef int last = tip-1 

for tip from last > tip >= 0: 

mpz_mul(sub_prods[tip], sub_prods[tip], sub_prods[tip+1]) 

  

sig_off() 

  

cdef Integer z = PY_NEW(Integer) 

mpz_swap(z.value, sub_prods[0]) 

  

for i from 0 <= i < prod_count: 

mpz_clear(sub_prods[i]) 

sig_free(sub_prods) 

  

return z 

  

def gamma(self): 

r""" 

The gamma function on integers is the factorial function (shifted by 

one) on positive integers, and `\pm \infty` on non-positive integers. 

  

EXAMPLES:: 

  

sage: gamma(5) 

24 

sage: gamma(0) 

Infinity 

sage: gamma(-1) 

Infinity 

sage: gamma(-2^150) 

Infinity 

""" 

if mpz_sgn(self.value) > 0: 

return (self-one).factorial() 

else: 

return sage.rings.infinity.unsigned_infinity 

  

def floor(self): 

""" 

Return the floor of self, which is just self since self is an 

integer. 

  

EXAMPLES:: 

  

sage: n = 6 

sage: n.floor() 

6 

""" 

return self 

  

def ceil(self): 

""" 

Return the ceiling of self, which is self since self is an 

integer. 

  

EXAMPLES:: 

  

sage: n = 6 

sage: n.ceil() 

6 

""" 

return self 

  

def trunc(self): 

""" 

Round this number to the nearest integer, which is self since 

self is an integer. 

  

EXAMPLES:: 

  

sage: n = 6 

sage: n.trunc() 

6 

""" 

return self 

  

def round(Integer self, mode="away"): 

""" 

Returns the nearest integer to ``self``, which is self since 

self is an integer. 

  

EXAMPLES: 

  

This example addresses :trac:`23502`:: 

  

sage: n = 6 

sage: n.round() 

6 

""" 

return self 

  

def real(self): 

""" 

Returns the real part of self, which is self. 

  

EXAMPLES:: 

  

sage: Integer(-4).real() 

-4 

""" 

return self 

  

def imag(self): 

""" 

Returns the imaginary part of self, which is zero. 

  

EXAMPLES:: 

  

sage: Integer(9).imag() 

0 

""" 

return zero 

  

def is_one(self): 

r""" 

Returns ``True`` if the integer is `1`, otherwise ``False``. 

  

EXAMPLES:: 

  

sage: Integer(1).is_one() 

True 

sage: Integer(0).is_one() 

False 

""" 

return mpz_cmp_si(self.value, 1) == 0 

  

def __nonzero__(self): 

r""" 

Returns ``True`` if the integer is not `0`, otherwise ``False``. 

  

EXAMPLES:: 

  

sage: Integer(1).is_zero() 

False 

sage: Integer(0).is_zero() 

True 

""" 

return mpz_sgn(self.value) != 0 

  

def is_integral(self): 

""" 

Return ``True`` since integers are integral, i.e., 

satisfy a monic polynomial with integer coefficients. 

  

EXAMPLES:: 

  

sage: Integer(3).is_integral() 

True 

""" 

return True 

  

def is_rational(self): 

r""" 

Return ``True`` as an integer is a rational number. 

  

EXAMPLES:: 

  

sage: 5.is_rational() 

True 

""" 

return True 

  

def is_integer(self): 

""" 

Returns ``True`` as they are integers 

  

EXAMPLES:: 

  

sage: sqrt(4).is_integer() 

True 

""" 

return True 

  

def is_unit(self): 

r""" 

Returns ``true`` if this integer is a unit, i.e., 1 or `-1`. 

  

EXAMPLES:: 

  

sage: for n in srange(-2,3): 

....: print("{} {}".format(n, n.is_unit())) 

-2 False 

-1 True 

0 False 

1 True 

2 False 

""" 

return mpz_cmpabs_ui(self.value, 1) == 0 

  

def is_square(self): 

r""" 

Returns ``True`` if self is a perfect square. 

  

EXAMPLES:: 

  

sage: Integer(4).is_square() 

True 

sage: Integer(41).is_square() 

False 

""" 

return mpz_perfect_square_p(self.value) 

  

def perfect_power(self): 

r""" 

Returns ``(a, b)``, where this integer is `a^b` and `b` is maximal. 

  

If called on `-1`, `0` or `1`, `b` will be `1`, since there is no 

maximal value of `b`. 

  

.. SEEALSO:: 

  

- :meth:`is_perfect_power`: testing whether an integer is a perfect 

power is usually faster than finding `a` and `b`. 

- :meth:`is_prime_power`: checks whether the base is prime. 

- :meth:`is_power_of`: if you know the base already, this method is 

the fastest option. 

  

EXAMPLES:: 

  

sage: 144.perfect_power() 

(12, 2) 

sage: 1.perfect_power() 

(1, 1) 

sage: 0.perfect_power() 

(0, 1) 

sage: (-1).perfect_power() 

(-1, 1) 

sage: (-8).perfect_power() 

(-2, 3) 

sage: (-4).perfect_power() 

(-4, 1) 

sage: (101^29).perfect_power() 

(101, 29) 

sage: (-243).perfect_power() 

(-3, 5) 

sage: (-64).perfect_power() 

(-4, 3) 

""" 

parians = self.__pari__().ispower() 

return Integer(parians[1]), Integer(parians[0]) 

  

def global_height(self, prec=None): 

r""" 

Returns the absolute logarithmic height of this rational integer. 

  

INPUT: 

  

- ``prec`` (int) -- desired floating point precision (default: 

default RealField precision). 

  

OUTPUT: 

  

(real) The absolute logarithmic height of this rational integer. 

  

ALGORITHM: 

  

The height of the integer `n` is `\log |n|`. 

  

EXAMPLES:: 

  

sage: ZZ(5).global_height() 

1.60943791243410 

sage: ZZ(-2).global_height(prec=100) 

0.69314718055994530941723212146 

sage: exp(_) 

2.0000000000000000000000000000 

""" 

from sage.rings.real_mpfr import RealField 

if prec is None: 

R = RealField() 

else: 

R = RealField(prec) 

if self.is_zero(): 

return R.zero() 

return R(self).abs().log() 

  

cdef bint _is_power_of(Integer self, Integer n): 

r""" 

Returns a non-zero int if there is an integer b with 

`\mathtt{self} = n^b`. 

  

For more documentation see ``is_power_of``. 

  

AUTHORS: 

  

- David Roe (2007-03-31) 

""" 

cdef int a 

cdef unsigned long b, c 

cdef mpz_t u, sabs, nabs 

a = mpz_cmp_ui(n.value, 2) 

if a <= 0: # n <= 2 

if a == 0: # n == 2 

if mpz_popcount(self.value) == 1: #number of bits set in self == 1 

return 1 

else: 

return 0 

a = mpz_cmp_si(n.value, -2) 

if a >= 0: # -2 <= n < 2: 

a = mpz_get_si(n.value) 

if a == 1: # n == 1 

if mpz_cmp_ui(self.value, 1) == 0: # Only 1 is a power of 1 

return 1 

else: 

return 0 

elif a == 0: # n == 0 

if mpz_cmp_ui(self.value, 0) == 0 or mpz_cmp_ui(self.value, 1) == 0: # 0^0 = 1, 0^x = 0 

return 1 

else: 

return 0 

elif a == -1: # n == -1 

if mpz_cmp_ui(self.value, 1) == 0 or mpz_cmp_si(self.value, -1) == 0: # 1 and -1 are powers of -1 

return 1 

else: 

return 0 

elif a == -2: # n == -2 

mpz_init(sabs) 

mpz_abs(sabs, self.value) 

if mpz_popcount(sabs) == 1: # number of bits set in |self| == 1 

b = mpz_scan1(sabs, 0) % 2 # b == 1 if |self| is an odd power of 2, 0 if |self| is an even power 

mpz_clear(sabs) 

if (b == 1 and mpz_cmp_ui(self.value, 0) < 0) or (b == 0 and mpz_cmp_ui(self.value, 0) > 0): 

# An odd power of -2 is negative, an even power must be positive. 

return 1 

else: # number of bits set in |self| is not 1, so self cannot be a power of -2 

return 0 

else: # |self| is not a power of 2, so self cannot be a power of -2 

return 0 

else: # n < -2 

mpz_init(nabs) 

mpz_neg(nabs, n.value) 

if mpz_popcount(nabs) == 1: # |n| = 2^k for k >= 2. We special case this for speed 

mpz_init(sabs) 

mpz_abs(sabs, self.value) 

if mpz_popcount(sabs) == 1: # |self| = 2^L for some L >= 0. 

b = mpz_scan1(sabs, 0) # the bit that self is set at 

c = mpz_scan1(nabs, 0) # the bit that n is set at 

# Having obtained b and c, we're done with nabs and sabs (on this branch anyway) 

mpz_clear(nabs) 

mpz_clear(sabs) 

if b % c == 0: # Now we know that |self| is a power of |n| 

b = (b // c) % 2 # Whether b // c is even or odd determines whether (-2^c)^(b // c) is positive or negative 

a = mpz_cmp_ui(self.value, 0) 

if b == 0 and a > 0 or b == 1 and a < 0: 

# These two cases are that b // c is even and self positive, or b // c is odd and self negative 

return 1 

else: # The sign of self is wrong 

return 0 

else: # Since |self| is not a power of |n|, self cannot be a power of n 

return 0 

else: # self is not a power of 2, and thus cannot be a power of n, which is a power of 2. 

mpz_clear(nabs) 

mpz_clear(sabs) 

return 0 

else: # |n| is not a power of 2, so we use mpz_remove 

mpz_init(u) 

sig_on() 

b = mpz_remove(u, self.value, nabs) 

sig_off() 

# Having obtained b and u, we're done with nabs 

mpz_clear(nabs) 

if mpz_cmp_ui(u, 1) == 0: # self is a power of |n| 

mpz_clear(u) 

if b % 2 == 0: # an even power of |n|, and since self > 0, this means that self is a power of n 

return 1 

else: 

return 0 

elif mpz_cmp_si(u, -1) == 0: # -self is a power of |n| 

mpz_clear(u) 

if b % 2 == 1: # an odd power of |n|, and thus self is a power of n 

return 1 

else: 

return 0 

else: # |self| is not a power of |n|, so self cannot be a power of n 

mpz_clear(u) 

return 0 

elif mpz_popcount(n.value) == 1: # n > 2 and in fact n = 2^k for k >= 2 

if mpz_popcount(self.value) == 1: # since n is a power of 2, so must self be. 

if mpz_scan1(self.value, 0) % mpz_scan1(n.value, 0) == 0: # log_2(self) is divisible by log_2(n) 

return 1 

else: 

return 0 

else: # self is not a power of 2, and thus not a power of n 

return 0 

else: # n > 2, but not a power of 2, so we use mpz_remove 

mpz_init(u) 

sig_on() 

mpz_remove(u, self.value, n.value) 

sig_off() 

a = mpz_cmp_ui(u, 1) 

mpz_clear(u) 

if a == 0: 

return 1 

else: 

return 0 

  

def is_power_of(Integer self, n): 

r""" 

Returns ``True`` if there is an integer b with 

`\mathtt{self} = n^b`. 

  

.. SEEALSO:: 

  

- :meth:`perfect_power`: Finds the minimal base for which this 

integer is a perfect power. 

- :meth:`is_perfect_power`: If you don't know the base but just 

want to know if this integer is a perfect power, use this 

function. 

- :meth:`is_prime_power`: Checks whether the base is prime. 

  

EXAMPLES:: 

  

sage: Integer(64).is_power_of(4) 

True 

sage: Integer(64).is_power_of(16) 

False 

  

TESTS:: 

  

sage: Integer(-64).is_power_of(-4) 

True 

sage: Integer(-32).is_power_of(-2) 

True 

sage: Integer(1).is_power_of(1) 

True 

sage: Integer(-1).is_power_of(-1) 

True 

sage: Integer(0).is_power_of(1) 

False 

sage: Integer(0).is_power_of(0) 

True 

sage: Integer(1).is_power_of(0) 

True 

sage: Integer(1).is_power_of(8) 

True 

sage: Integer(-8).is_power_of(2) 

False 

sage: Integer(-81).is_power_of(-3) 

False 

  

.. NOTE:: 

  

For large integers self, is_power_of() is faster than 

is_perfect_power(). The following examples gives some indication of 

how much faster. 

  

:: 

  

sage: b = lcm(range(1,10000)) 

sage: b.exact_log(2) 

14446 

sage: t=cputime() 

sage: for a in range(2, 1000): k = b.is_perfect_power() 

sage: cputime(t) # random 

0.53203299999999976 

sage: t=cputime() 

sage: for a in range(2, 1000): k = b.is_power_of(2) 

sage: cputime(t) # random 

0.0 

sage: t=cputime() 

sage: for a in range(2, 1000): k = b.is_power_of(3) 

sage: cputime(t) # random 

0.032002000000000308 

  

:: 

  

sage: b = lcm(range(1, 1000)) 

sage: b.exact_log(2) 

1437 

sage: t=cputime() 

sage: for a in range(2, 10000): k = b.is_perfect_power() # note that we change the range from the example above 

sage: cputime(t) # random 

0.17201100000000036 

sage: t=cputime(); TWO=int(2) 

sage: for a in range(2, 10000): k = b.is_power_of(TWO) 

sage: cputime(t) # random 

0.0040000000000000036 

sage: t=cputime() 

sage: for a in range(2, 10000): k = b.is_power_of(3) 

sage: cputime(t) # random 

0.040003000000000011 

sage: t=cputime() 

sage: for a in range(2, 10000): k = b.is_power_of(a) 

sage: cputime(t) # random 

0.02800199999999986 

""" 

if not isinstance(n, Integer): 

n = Integer(n) 

return self._is_power_of(n) 

  

def is_prime_power(self, *, proof=None, bint get_data=False): 

r""" 

Return ``True`` if this integer is a prime power, and ``False`` otherwise. 

  

A prime power is a prime number raised to a positive power. Hence `1` is 

not a prime power. 

  

For a method that uses a pseudoprimality test instead see 

:meth:`is_pseudoprime_power`. 

  

INPUT: 

  

- ``proof`` -- Boolean or ``None`` (default). If ``False``, use a strong 

pseudo-primality test (see :meth:`is_pseudoprime`). If ``True``, use 

a provable primality test. If unset, use the default arithmetic proof 

flag. 

  

- ``get_data`` -- (default ``False``), if ``True`` return a pair 

``(p,k)`` such that this integer equals ``p^k`` with ``p`` a prime 

and ``k`` a positive integer or the pair ``(self,0)`` otherwise. 

  

.. SEEALSO:: 

  

- :meth:`perfect_power`: Finds the minimal base for which integer 

is a perfect power. 

- :meth:`is_perfect_power`: Doesn't test whether the base is prime. 

- :meth:`is_power_of`: If you know the base already this method is 

the fastest option. 

- :meth:`is_pseudoprime_power`: If the entry is very large. 

  

EXAMPLES:: 

  

sage: 17.is_prime_power() 

True 

sage: 10.is_prime_power() 

False 

sage: 64.is_prime_power() 

True 

sage: (3^10000).is_prime_power() 

True 

sage: (10000).is_prime_power() 

False 

sage: (-3).is_prime_power() 

False 

sage: 0.is_prime_power() 

False 

sage: 1.is_prime_power() 

False 

sage: p = next_prime(10^20); p 

100000000000000000039 

sage: p.is_prime_power() 

True 

sage: (p^97).is_prime_power() 

True 

sage: (p+1).is_prime_power() 

False 

  

With the ``get_data`` keyword set to ``True``:: 

  

sage: (3^100).is_prime_power(get_data=True) 

(3, 100) 

sage: 12.is_prime_power(get_data=True) 

(12, 0) 

sage: (p^97).is_prime_power(get_data=True) 

(100000000000000000039, 97) 

sage: q = p.next_prime(); q 

100000000000000000129 

sage: (p*q).is_prime_power(get_data=True) 

(10000000000000000016800000000000000005031, 0) 

  

The method works for large entries when `proof=False`:: 

  

sage: proof.arithmetic(False) 

sage: ((10^500 + 961)^4).is_prime_power() 

True 

sage: proof.arithmetic(True) 

  

We check that :trac:`4777` is fixed:: 

  

sage: n = 150607571^14 

sage: n.is_prime_power() 

True 

""" 

if mpz_sgn(self.value) <= 0: 

return (self, zero) if get_data else False 

  

cdef long p, n 

if mpz_fits_slong_p(self.value): 

# Note that self.value fits in a long, so there is no 

# overflow possible because of mixing signed/unsigned longs. 

# We call the PARI function uisprimepower() 

n = uisprimepower(mpz_get_ui(self.value), <ulong*>(&p)) 

if n: 

return (smallInteger(p), smallInteger(n)) if get_data else True 

else: 

return (self, zero) if get_data else False 

else: 

if proof is None: 

from sage.structure.proof.proof import get_flag 

proof = get_flag(proof, "arithmetic") 

  

if proof: 

n, pari_p = self.__pari__().isprimepower() 

else: 

n, pari_p = self.__pari__().ispseudoprimepower() 

  

if n: 

return (Integer(pari_p), smallInteger(n)) if get_data else True 

else: 

return (self, zero) if get_data else False 

  

def is_prime(self, proof=None): 

r""" 

Test whether ``self`` is prime. 

  

INPUT: 

  

- ``proof`` -- Boolean or ``None`` (default). If False, use a 

strong pseudo-primality test (see :meth:`is_pseudoprime`). 

If True, use a provable primality test. If unset, use the 

:mod:`default arithmetic proof flag <sage.structure.proof.proof>`. 

  

.. NOTE:: 

  

Integer primes are by definition *positive*! This is 

different than Magma, but the same as in PARI. See also the 

:meth:`is_irreducible()` method. 

  

EXAMPLES:: 

  

sage: z = 2^31 - 1 

sage: z.is_prime() 

True 

sage: z = 2^31 

sage: z.is_prime() 

False 

sage: z = 7 

sage: z.is_prime() 

True 

sage: z = -7 

sage: z.is_prime() 

False 

sage: z.is_irreducible() 

True 

  

:: 

  

sage: z = 10^80 + 129 

sage: z.is_prime(proof=False) 

True 

sage: z.is_prime(proof=True) 

True 

  

When starting Sage the arithmetic proof flag is True. We can change 

it to False as follows:: 

  

sage: proof.arithmetic() 

True 

sage: n = 10^100 + 267 

sage: timeit("n.is_prime()") # not tested 

5 loops, best of 3: 163 ms per loop 

sage: proof.arithmetic(False) 

sage: proof.arithmetic() 

False 

sage: timeit("n.is_prime()") # not tested 

1000 loops, best of 3: 573 us per loop 

  

ALGORITHM: 

  

Calls the PARI ``isprime`` function. 

""" 

if mpz_sgn(self.value) <= 0: 

return False 

  

if mpz_fits_ulong_p(self.value): 

return bool(uisprime(mpz_get_ui(self.value))) 

  

if proof is None: 

from sage.structure.proof.proof import get_flag 

proof = get_flag(proof, "arithmetic") 

if proof: 

return self.__pari__().isprime() 

else: 

return self.__pari__().ispseudoprime() 

  

cdef bint _pseudoprime_is_prime(self, proof) except -1: 

""" 

Given a pseudoprime, return ``self.is_prime(proof)``. 

  

INPUT: 

  

- ``self`` -- A PARI pseudoprime 

  

- ``proof`` -- Mandatory proof flag (True, False or None) 

  

OUTPUT: 

  

- The result of ``self.is_prime(proof)`` but faster 

""" 

if mpz_cmp(self.value, PARI_PSEUDOPRIME_LIMIT) < 0: 

return True 

if proof is None: 

from sage.structure.proof.proof import get_flag 

proof = get_flag(proof, "arithmetic") 

if proof: 

return self.__pari__().isprime() 

else: 

return True 

  

def is_irreducible(self): 

r""" 

Returns ``True`` if self is irreducible, i.e. +/- 

prime 

  

EXAMPLES:: 

  

sage: z = 2^31 - 1 

sage: z.is_irreducible() 

True 

sage: z = 2^31 

sage: z.is_irreducible() 

False 

sage: z = 7 

sage: z.is_irreducible() 

True 

sage: z = -7 

sage: z.is_irreducible() 

True 

""" 

cdef Integer n = self if self >= 0 else -self 

return n.__pari__().isprime() 

  

def is_pseudoprime(self): 

r""" 

Test whether ``self`` is a pseudoprime. 

  

This uses PARI's Baillie-PSW probabilistic primality 

test. Currently, there are no known pseudoprimes for 

Baillie-PSW that are not actually prime. However it is 

conjectured that there are infinitely many. 

  

See :wikipedia:`Baillie-PSW_primality_test` 

  

EXAMPLES:: 

  

sage: z = 2^31 - 1 

sage: z.is_pseudoprime() 

True 

sage: z = 2^31 

sage: z.is_pseudoprime() 

False 

""" 

return self.__pari__().ispseudoprime() 

  

def is_pseudoprime_power(self, get_data=False): 

r""" 

Test if this number is a power of a pseudoprime number. 

  

For large numbers, this method might be faster than 

:meth:`is_prime_power`. 

  

INPUT: 

  

- ``get_data`` -- (default ``False``) if ``True`` return a pair `(p,k)` 

such that this number equals `p^k` with `p` a pseudoprime and `k` a 

positive integer or the pair ``(self,0)`` otherwise. 

  

EXAMPLES:: 

  

sage: x = 10^200 + 357 

sage: x.is_pseudoprime() 

True 

sage: (x^12).is_pseudoprime_power() 

True 

sage: (x^12).is_pseudoprime_power(get_data=True) 

(1000...000357, 12) 

sage: (997^100).is_pseudoprime_power() 

True 

sage: (998^100).is_pseudoprime_power() 

False 

sage: ((10^1000 + 453)^2).is_pseudoprime_power() 

True 

  

TESTS:: 

  

sage: 0.is_pseudoprime_power() 

False 

sage: (-1).is_pseudoprime_power() 

False 

sage: 1.is_pseudoprime_power() 

False 

""" 

return self.is_prime_power(proof=False, get_data=get_data) 

  

def is_perfect_power(self): 

r""" 

Returns ``True`` if ``self`` is a perfect power, ie if there exist integers 

`a` and `b`, `b > 1` with ``self`` `= a^b`. 

  

.. SEEALSO:: 

  

- :meth:`perfect_power`: Finds the minimal base for which this 

integer is a perfect power. 

- :meth:`is_power_of`: If you know the base already this method is 

the fastest option. 

- :meth:`is_prime_power`: Checks whether the base is prime. 

  

EXAMPLES:: 

  

sage: Integer(-27).is_perfect_power() 

True 

sage: Integer(12).is_perfect_power() 

False 

  

sage: z = 8 

sage: z.is_perfect_power() 

True 

sage: 144.is_perfect_power() 

True 

sage: 10.is_perfect_power() 

False 

sage: (-8).is_perfect_power() 

True 

sage: (-4).is_perfect_power() 

False 

  

TESTS: 

  

This is a test to make sure we work around a bug in GMP, see 

:trac:`4612`. 

  

:: 

  

sage: [ -a for a in srange(100) if not (-a^3).is_perfect_power() ] 

[] 

""" 

cdef mpz_t tmp 

cdef int res 

if mpz_sgn(self.value) < 0: 

if mpz_cmp_si(self.value, -1) == 0: 

return True 

mpz_init(tmp) 

mpz_neg(tmp, self.value) 

while mpz_perfect_square_p(tmp): 

mpz_sqrt(tmp, tmp) 

res = mpz_perfect_power_p(tmp) 

mpz_clear(tmp) 

return res != 0 

return mpz_perfect_power_p(self.value) 

  

def is_norm(self, K, element=False, proof=True): 

r""" 

See ``QQ(self).is_norm()``. 

  

EXAMPLES:: 

  

sage: K = NumberField(x^2 - 2, 'beta') 

sage: n = 4 

sage: n.is_norm(K) 

True 

sage: 5.is_norm(K) 

False 

sage: 7.is_norm(QQ) 

True 

sage: n.is_norm(K, element=True) 

(True, -4*beta + 6) 

sage: n.is_norm(K, element=True)[1].norm() 

4 

sage: n = 5 

sage: n.is_norm(K, element=True) 

(False, None) 

sage: n = 7 

sage: n.is_norm(QQ, element=True) 

(True, 7) 

  

""" 

from sage.rings.rational_field import QQ 

return QQ(self).is_norm(K, element=element, proof=proof) 

  

def _bnfisnorm(self, K, proof=True, extra_primes=0): 

r""" 

See ``QQ(self)._bnfisnorm()``. 

  

EXAMPLES:: 

  

sage: 3._bnfisnorm(QuadraticField(-1, 'i')) 

(1, 3) 

sage: 7._bnfisnorm(CyclotomicField(7)) 

(-zeta7^5 - zeta7^4 - 2*zeta7^3 - zeta7^2 - zeta7 - 1, 1) 

""" 

from sage.rings.rational_field import QQ 

return QQ(self)._bnfisnorm(K, proof=proof, extra_primes=extra_primes) 

  

  

def jacobi(self, b): 

r""" 

Calculate the Jacobi symbol `\left(\frac{self}{b}\right)`. 

  

EXAMPLES:: 

  

sage: z = -1 

sage: z.jacobi(17) 

1 

sage: z.jacobi(19) 

-1 

sage: z.jacobi(17*19) 

-1 

sage: (2).jacobi(17) 

1 

sage: (3).jacobi(19) 

-1 

sage: (6).jacobi(17*19) 

-1 

sage: (6).jacobi(33) 

0 

sage: a = 3; b = 7 

sage: a.jacobi(b) == -b.jacobi(a) 

True 

""" 

cdef long tmp 

if isinstance(b, int): 

tmp = b 

if (tmp & 1) == 0: 

raise ValueError("Jacobi symbol not defined for even b.") 

return mpz_kronecker_si(self.value, tmp) 

if not isinstance(b, Integer): 

b = Integer(b) 

if mpz_even_p((<Integer>b).value): 

raise ValueError("Jacobi symbol not defined for even b.") 

return mpz_jacobi(self.value, (<Integer>b).value) 

  

def kronecker(self, b): 

r""" 

Calculate the Kronecker symbol `\left(\frac{self}{b}\right)` 

with the Kronecker extension `(self/2)=(2/self)` when `self` is odd, 

or `(self/2)=0` when `self` is even. 

  

EXAMPLES:: 

  

sage: z = 5 

sage: z.kronecker(41) 

1 

sage: z.kronecker(43) 

-1 

sage: z.kronecker(8) 

-1 

sage: z.kronecker(15) 

0 

sage: a = 2; b = 5 

sage: a.kronecker(b) == b.kronecker(a) 

True 

""" 

if isinstance(b, int): 

return mpz_kronecker_si(self.value, b) 

if not isinstance(b, Integer): 

b = Integer(b) 

return mpz_kronecker(self.value, (<Integer>b).value) 

  

def class_number(self, proof=True): 

r""" 

Returns the class number of the quadratic order with this discriminant. 

  

INPUT: 

  

- ``self`` -- an integer congruent to `0` or `1\mod4` which is 

not a square 

  

- ``proof`` (boolean, default ``True``) -- if ``False`` then 

for negative disscriminants a faster algorithm is used by 

the PARI library which is known to give incorrect results 

when the class group has many cyclic factors. 

  

OUTPUT: 

  

(integer) the class number of the quadratic order with this 

discriminant. 

  

.. NOTE:: 

  

This is not always equal to the number of classes of 

primitive binary quadratic forms of discriminant `D`, which 

is equal to the narrow class number. The two notions are 

the same when `D<0`, or `D>0` and the fundamental unit of 

the order has negative norm; otherwise the number of 

classes of forms is twice this class number. 

  

EXAMPLES:: 

  

sage: (-163).class_number() 

1 

sage: (-104).class_number() 

6 

sage: [((4*n+1),(4*n+1).class_number()) for n in [21..29]] 

[(85, 2), 

(89, 1), 

(93, 1), 

(97, 1), 

(101, 1), 

(105, 2), 

(109, 1), 

(113, 1), 

(117, 1)] 

  

TESTS: 

  

The integer must not be a square or an error is raised:: 

  

sage: 100.class_number() 

Traceback (most recent call last): 

... 

ValueError: class_number not defined for square integers 

  

  

The integer must be 0 or 1 mod 4 or an error is raised:: 

  

sage: 10.class_number() 

Traceback (most recent call last): 

... 

ValueError: class_number only defined for integers congruent to 0 or 1 modulo 4 

sage: 3.class_number() 

Traceback (most recent call last): 

... 

ValueError: class_number only defined for integers congruent to 0 or 1 modulo 4 

  

  

""" 

if self.is_square(): 

raise ValueError("class_number not defined for square integers") 

if not self%4 in [0,1]: 

raise ValueError("class_number only defined for integers congruent to 0 or 1 modulo 4") 

flag = self < 0 and proof 

return objtogen(self).qfbclassno(flag).sage() 

  

def radical(self, *args, **kwds): 

r""" 

Return the product of the prime divisors of self. Computing 

the radical of zero gives an error. 

  

EXAMPLES:: 

  

sage: Integer(10).radical() 

10 

sage: Integer(20).radical() 

10 

sage: Integer(-100).radical() 

10 

sage: Integer(0).radical() 

Traceback (most recent call last): 

... 

ArithmeticError: Radical of 0 not defined. 

""" 

if self.is_zero(): 

raise ArithmeticError("Radical of 0 not defined.") 

return self.factor(*args, **kwds).radical_value() 

  

def squarefree_part(self, long bound=-1): 

r""" 

Return the square free part of `x` (=self), i.e., the unique integer 

`z` that `x = z y^2`, with `y^2` a perfect square and `z` square-free. 

  

Use ``self.radical()`` for the product of the primes that divide self. 

  

If self is 0, just returns 0. 

  

EXAMPLES:: 

  

sage: squarefree_part(100) 

1 

sage: squarefree_part(12) 

3 

sage: squarefree_part(17*37*37) 

17 

sage: squarefree_part(-17*32) 

-34 

sage: squarefree_part(1) 

1 

sage: squarefree_part(-1) 

-1 

sage: squarefree_part(-2) 

-2 

sage: squarefree_part(-4) 

-1 

  

:: 

  

sage: a = 8 * 5^6 * 101^2 

sage: a.squarefree_part(bound=2).factor() 

2 * 5^6 * 101^2 

sage: a.squarefree_part(bound=5).factor() 

2 * 101^2 

sage: a.squarefree_part(bound=1000) 

2 

sage: a.squarefree_part(bound=2**14) 

2 

sage: a = 7^3 * next_prime(2^100)^2 * next_prime(2^200) 

sage: a / a.squarefree_part(bound=1000) 

49 

""" 

cdef Integer z 

cdef long even_part, p, p2 

cdef char switch_p 

if mpz_sgn(self.value) == 0: 

return self 

if 0 <= bound < 2: 

return self 

elif 2 <= bound <= 10000: 

z = PY_NEW(Integer) 

even_part = mpz_scan1(self.value, 0) 

mpz_fdiv_q_2exp(z.value, self.value, even_part ^ (even_part&1)) 

sig_on() 

if bound >= 3: 

while mpz_divisible_ui_p(z.value, 9): 

mpz_divexact_ui(z.value, z.value, 9) 

if bound >= 5: 

while mpz_divisible_ui_p(z.value, 25): 

mpz_divexact_ui(z.value, z.value, 25) 

for p from 7 <= p <= bound by 2: 

switch_p = p % 30 

if switch_p in [1, 7, 11, 13, 17, 19, 23, 29]: 

p2 = p*p 

while mpz_divisible_ui_p(z.value, p2): 

mpz_divexact_ui(z.value, z.value, p2) 

sig_off() 

return z 

else: 

if bound == -1: 

F = self.factor() 

else: 

from sage.rings.factorint import factor_trial_division 

F = factor_trial_division(self,bound) 

n = one 

for pp, e in F: 

if e % 2 != 0: 

n = n * pp 

return n * F.unit() 

  

def next_probable_prime(self): 

""" 

Returns the next probable prime after self, as determined by PARI. 

  

EXAMPLES:: 

  

sage: (-37).next_probable_prime() 

2 

sage: (100).next_probable_prime() 

101 

sage: (2^512).next_probable_prime() 

13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084171 

sage: 0.next_probable_prime() 

2 

sage: 126.next_probable_prime() 

127 

sage: 144168.next_probable_prime() 

144169 

""" 

return Integer( self.__pari__().nextprime(True) ) 

  

def next_prime(self, proof=None): 

r""" 

Return the next prime after self. 

  

This method calls the PARI ``nextprime`` function. 

  

INPUT: 

  

- ``proof`` - bool or None (default: None, see 

proof.arithmetic or sage.structure.proof) Note that the global Sage 

default is proof=True 

  

EXAMPLES:: 

  

sage: 100.next_prime() 

101 

sage: (10^50).next_prime() 

100000000000000000000000000000000000000000000000151 

  

Use ``proof=False``, which is way faster since it does not need 

a primality proof:: 

  

sage: b = (2^1024).next_prime(proof=False) 

sage: b - 2^1024 

643 

  

:: 

  

sage: Integer(0).next_prime() 

2 

sage: Integer(1001).next_prime() 

1009 

""" 

# Use PARI to compute the next *pseudo*-prime 

p = Integer(self.__pari__().nextprime(True)) 

while not p._pseudoprime_is_prime(proof): 

p = Integer(p.__pari__().nextprime(True)) 

return p 

  

def previous_prime(self, proof=None): 

r""" 

Returns the previous prime before self. 

  

This method calls the PARI ``precprime`` function. 

  

INPUT: 

  

- ``proof`` - if ``True`` ensure that the returned value is the next 

prime power and if set to ``False`` uses probabilistic methods 

(i.e. the result is not guaranteed). By default it uses global 

configuration variables to determine which alternative to use (see 

:mod:`proof.arithmetic` or :mod:`sage.structure.proof`). 

  

.. SEEALSO:: 

  

- :meth:`next_prime` 

  

EXAMPLES:: 

  

sage: 10.previous_prime() 

7 

sage: 7.previous_prime() 

5 

sage: 14376485.previous_prime() 

14376463 

  

sage: 2.previous_prime() 

Traceback (most recent call last): 

... 

ValueError: no prime less than 2 

  

An example using ``proof=False``, which is way faster since it does not 

need a primality proof:: 

  

sage: b = (2^1024).previous_prime(proof=False) 

sage: 2^1024 - b 

105 

""" 

if mpz_cmp_ui(self.value, 2) <= 0: 

raise ValueError("no prime less than 2") 

cdef Integer p = self-1 

p = Integer(p.__pari__().precprime()) 

while not p._pseudoprime_is_prime(proof): 

mpz_sub_ui(p.value, p.value, 1) 

p = Integer(p.__pari__().precprime()) 

return p 

  

def next_prime_power(self, proof=None): 

r""" 

Return the next prime power after self. 

  

INPUT: 

  

- ``proof`` - if ``True`` ensure that the returned value is the next 

prime power and if set to ``False`` uses probabilistic methods 

(i.e. the result is not guaranteed). By default it uses global 

configuration variables to determine which alternative to use (see 

:mod:`proof.arithmetic` or :mod:`sage.structure.proof`). 

  

ALGORITHM: 

  

The algorithm is naive. It computes the next power of 2 and go through 

the odd numbers calling :meth:`is_prime_power`. 

  

.. SEEALSO:: 

  

- :meth:`previous_prime_power` 

- :meth:`is_prime_power` 

- :meth:`next_prime` 

- :meth:`previous_prime` 

  

EXAMPLES:: 

  

sage: (-1).next_prime_power() 

2 

sage: 2.next_prime_power() 

3 

sage: 103.next_prime_power() 

107 

sage: 107.next_prime_power() 

109 

sage: 2044.next_prime_power() 

2048 

  

TESTS:: 

  

sage: [(2**k-1).next_prime_power() for k in range(1,10)] 

[2, 4, 8, 16, 32, 64, 128, 256, 512] 

sage: [(2**k).next_prime_power() for k in range(10)] 

[2, 3, 5, 9, 17, 37, 67, 131, 257, 521] 

  

sage: for _ in range(10): 

....: n = ZZ.random_element(2**256).next_prime_power() 

....: m = n.next_prime_power().previous_prime_power() 

....: assert m == n, "problem with n = {}".format(n) 

""" 

if mpz_cmp_ui(self.value, 2) < 0: 

return smallInteger(2) 

  

cdef mp_bitcnt_t bit_index = mpz_sizeinbase(self.value,2) 

cdef Integer n = PY_NEW(Integer) 

  

mpz_add_ui(n.value, self.value, 1 if mpz_even_p(self.value) else 2) 

  

while not mpz_tstbit(n.value, bit_index): 

if n.is_prime_power(proof=proof): 

return n 

mpz_add_ui(n.value, n.value, 2) 

  

# return the power of 2 we just skipped 

mpz_sub_ui(n.value, n.value, 1) 

return n 

  

def previous_prime_power(self, proof=None): 

r""" 

Return the previous prime power before self. 

  

INPUT: 

  

- ``proof`` - if ``True`` ensure that the returned value is the next 

prime power and if set to ``False`` uses probabilistic methods 

(i.e. the result is not guaranteed). By default it uses global 

configuration variables to determine which alternative to use (see 

:mod:`proof.arithmetic` or :mod:`sage.structure.proof`). 

  

ALGORITHM: 

  

The algorithm is naive. It computes the previous power of 2 and go 

through the odd numbers calling the method :meth:`is_prime_power`. 

  

.. SEEALSO:: 

  

- :meth:`next_prime_power` 

- :meth:`is_prime_power` 

- :meth:`previous_prime` 

- :meth:`next_prime` 

  

EXAMPLES:: 

  

sage: 3.previous_prime_power() 

2 

sage: 103.previous_prime_power() 

101 

sage: 107.previous_prime_power() 

103 

sage: 2044.previous_prime_power() 

2039 

  

sage: 2.previous_prime_power() 

Traceback (most recent call last): 

... 

ValueError: no prime power less than 2 

  

TESTS:: 

  

sage: [(2**k+1).previous_prime_power() for k in range(1,10)] 

[2, 4, 8, 16, 32, 64, 128, 256, 512] 

sage: [(2**k).previous_prime_power() for k in range(2, 10)] 

[3, 7, 13, 31, 61, 127, 251, 509] 

  

sage: for _ in range(10): 

....: n = ZZ.random_element(3,2**256).previous_prime_power() 

....: m = n.previous_prime_power().next_prime_power() 

....: assert m == n, "problem with n = {}".format(n) 

""" 

if mpz_cmp_ui(self.value, 2) <= 0: 

raise ValueError("no prime power less than 2") 

  

cdef Integer n = PY_NEW(Integer) 

  

mpz_sub_ui(n.value, self.value, 1) 

cdef mp_bitcnt_t bit_index = mpz_sizeinbase(n.value,2)-1 

if mpz_even_p(n.value): 

mpz_sub_ui(n.value, n.value, 1) 

  

while mpz_tstbit(n.value, bit_index): 

if n.is_prime_power(proof=proof): 

return n 

mpz_sub_ui(n.value, n.value, 2) 

  

# return the power of 2 we just skipped 

mpz_add_ui(n.value, n.value, 1) 

return n 

  

def additive_order(self): 

""" 

Return the additive order of self. 

  

EXAMPLES:: 

  

sage: ZZ(0).additive_order() 

1 

sage: ZZ(1).additive_order() 

+Infinity 

""" 

if mpz_sgn(self.value) == 0: 

return one 

else: 

return sage.rings.infinity.infinity 

  

def multiplicative_order(self): 

r""" 

Return the multiplicative order of self. 

  

EXAMPLES:: 

  

sage: ZZ(1).multiplicative_order() 

1 

sage: ZZ(-1).multiplicative_order() 

2 

sage: ZZ(0).multiplicative_order() 

+Infinity 

sage: ZZ(2).multiplicative_order() 

+Infinity 

""" 

if mpz_cmp_si(self.value, 1) == 0: 

return one 

elif mpz_cmp_si(self.value, -1) == 0: 

return smallInteger(2) 

else: 

return sage.rings.infinity.infinity 

  

def is_squarefree(self): 

""" 

Returns True if this integer is not divisible by the square of any 

prime and False otherwise. 

  

EXAMPLES:: 

  

sage: 100.is_squarefree() 

False 

sage: 102.is_squarefree() 

True 

sage: 0.is_squarefree() 

False 

""" 

return self.__pari__().issquarefree() 

  

cpdef __pari__(self): 

""" 

Returns the PARI version of this integer. 

  

EXAMPLES:: 

  

sage: n = 9390823 

sage: m = n.__pari__(); m 

9390823 

sage: type(m) 

<type 'cypari2.gen.Gen'> 

  

TESTS:: 

  

sage: n = 10^10000000 

sage: m = n.__pari__() ## crash from trac 875 

sage: m % 1234567 

1041334 

  

""" 

return new_gen_from_mpz_t(self.value) 

  

def _interface_init_(self, I=None): 

""" 

Return canonical string to coerce this integer to any other math 

software, i.e., just the string representation of this integer in 

base 10. 

  

EXAMPLES:: 

  

sage: n = 9390823 

sage: n._interface_init_() 

'9390823' 

""" 

return str(self) 

  

@property 

def __array_interface__(self): 

""" 

Used for NumPy conversion. 

  

EXAMPLES:: 

  

sage: import numpy 

sage: numpy.array([1, 2, 3]) 

array([1, 2, 3]) 

sage: numpy.array([1, 2, 3]).dtype 

dtype('int32') # 32-bit 

dtype('int64') # 64-bit 

  

sage: numpy.array(2**40).dtype 

dtype('int64') 

sage: numpy.array(2**400).dtype 

dtype('O') 

  

sage: numpy.array([1,2,3,0.1]).dtype 

dtype('float64') 

""" 

if mpz_fits_slong_p(self.value): 

return numpy_long_interface 

elif sizeof(long) == 4 and mpz_sizeinbase(self.value, 2) <= 63: 

return numpy_int64_interface 

else: 

return numpy_object_interface 

  

def _magma_init_(self, magma): 

""" 

Return string that evaluates in Magma to this element. 

  

For small integers we just use base 10. For large integers we use 

base 16, but use Magma's StringToInteger command, which (for no 

good reason) is much faster than 0x[string literal]. We only use 

base 16 for integers with at least 10000 binary digits, since e.g., 

for a large list of small integers the overhead of calling 

StringToInteger can be a killer. 

  

EXAMPLES: 

sage: (117)._magma_init_(magma) # optional - magma 

'117' 

  

Large integers use hex: 

sage: m = 3^(2^20) # optional - magma 

sage: s = m._magma_init_(magma) # optional - magma 

sage: 'StringToInteger' in s # optional - magma 

True 

sage: magma(m).sage() == m # optional - magma 

True 

""" 

if self.ndigits(2) > 10000: 

return 'StringToInteger("%s",16)'%self.str(16) 

else: 

return str(self) 

  

def _sage_input_(self, sib, coerced): 

r""" 

Produce an expression which will reproduce this value when 

evaluated. 

  

EXAMPLES:: 

  

sage: sage_input(1, verify=True) 

# Verified 

1 

sage: sage_input(1, preparse=False) 

ZZ(1) 

sage: sage_input(-12435, verify=True) 

# Verified 

-12435 

sage: sage_input(0, verify=True) 

# Verified 

0 

sage: sage_input(-3^70, verify=True) 

# Verified 

-2503155504993241601315571986085849 

sage: sage_input(-37, preparse=False) 

-ZZ(37) 

sage: sage_input(-37 * polygen(ZZ), preparse=False) 

R = ZZ['x'] 

x = R.gen() 

-37*x 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: (-314159)._sage_input_(SageInputBuilder(preparse=False), False) 

{unop:- {call: {atomic:ZZ}({atomic:314159})}} 

sage: (314159)._sage_input_(SageInputBuilder(preparse=False), True) 

{atomic:314159} 

""" 

if coerced or sib.preparse(): 

return sib.int(self) 

else: 

if self < 0: 

return -sib.name('ZZ')(sib.int(-self)) 

else: 

return sib.name('ZZ')(sib.int(self)) 

  

def sqrtrem(self): 

r""" 

Return (s, r) where s is the integer square root of self and 

r is the remainder such that `\text{self} = s^2 + r`. 

Raises ``ValueError`` if self is negative. 

  

EXAMPLES:: 

  

sage: 25.sqrtrem() 

(5, 0) 

sage: 27.sqrtrem() 

(5, 2) 

sage: 0.sqrtrem() 

(0, 0) 

  

:: 

  

sage: Integer(-102).sqrtrem() 

Traceback (most recent call last): 

... 

ValueError: square root of negative integer not defined. 

  

""" 

if mpz_sgn(self.value) < 0: 

raise ValueError("square root of negative integer not defined.") 

cdef Integer s = PY_NEW(Integer) 

cdef Integer r = PY_NEW(Integer) 

mpz_sqrtrem(s.value, r.value, self.value) 

return s, r 

  

def isqrt(self): 

r""" 

Returns the integer floor of the square root of self, or raises an 

``ValueError`` if self is negative. 

  

EXAMPLES:: 

  

sage: a = Integer(5) 

sage: a.isqrt() 

2 

  

:: 

  

sage: Integer(-102).isqrt() 

Traceback (most recent call last): 

... 

ValueError: square root of negative integer not defined. 

""" 

if mpz_sgn(self.value) < 0: 

raise ValueError("square root of negative integer not defined.") 

  

cdef Integer x = PY_NEW(Integer) 

  

sig_on() 

mpz_sqrt(x.value, self.value) 

sig_off() 

  

return x 

  

def sqrt(self, prec=None, extend=True, all=False): 

""" 

The square root function. 

  

INPUT: 

  

- ``prec`` - integer (default: None): if None, returns 

an exact square root; otherwise returns a numerical square root if 

necessary, to the given bits of precision. 

  

- ``extend`` - bool (default: True); if True, return a 

square root in an extension ring, if necessary. Otherwise, raise a 

ValueError if the square is not in the base ring. Ignored if prec 

is not None. 

  

- ``all`` - bool (default: False); if True, return all 

square roots of self, instead of just one. 

  

EXAMPLES:: 

  

sage: Integer(144).sqrt() 

12 

sage: sqrt(Integer(144)) 

12 

sage: Integer(102).sqrt() 

sqrt(102) 

  

:: 

  

sage: n = 2 

sage: n.sqrt(all=True) 

[sqrt(2), -sqrt(2)] 

sage: n.sqrt(prec=10) 

1.4 

sage: n.sqrt(prec=100) 

1.4142135623730950488016887242 

sage: n.sqrt(prec=100,all=True) 

[1.4142135623730950488016887242, -1.4142135623730950488016887242] 

sage: n.sqrt(extend=False) 

Traceback (most recent call last): 

... 

ValueError: square root of 2 not an integer 

sage: Integer(144).sqrt(all=True) 

[12, -12] 

sage: Integer(0).sqrt(all=True) 

[0] 

sage: type(Integer(5).sqrt()) 

<type 'sage.symbolic.expression.Expression'> 

sage: type(Integer(5).sqrt(prec=53)) 

<type 'sage.rings.real_mpfr.RealNumber'> 

sage: type(Integer(-5).sqrt(prec=53)) 

<type 'sage.rings.complex_number.ComplexNumber'> 

  

TESTS: 

  

Check that :trac:`9466` is fixed:: 

  

sage: 3.sqrt(extend=False, all=True) 

[] 

""" 

if mpz_sgn(self.value) == 0: 

return [self] if all else self 

  

if mpz_sgn(self.value) < 0: 

if not extend: 

raise ValueError("square root of negative number not an integer") 

from sage.functions.other import _do_sqrt 

return _do_sqrt(self, prec=prec, all=all) 

  

cdef int non_square 

cdef Integer z = PY_NEW(Integer) 

cdef mpz_t tmp 

sig_on() 

mpz_init(tmp) 

mpz_sqrtrem(z.value, tmp, self.value) 

non_square = mpz_sgn(tmp) != 0 

mpz_clear(tmp) 

sig_off() 

  

if non_square: 

if not extend: 

if not all: 

raise ValueError("square root of %s not an integer" % self) 

else: 

return [] 

from sage.functions.other import _do_sqrt 

return _do_sqrt(self, prec=prec, all=all) 

  

if prec: 

from sage.functions.other import _do_sqrt 

return _do_sqrt(self, prec=prec, all=all) 

  

if all: 

return [z, -z] 

return z 

  

@coerce_binop 

def xgcd(self, Integer n): 

r""" 

Return the extended gcd of this element and ``n``. 

  

INPUT: 

  

- ``n`` -- an integer 

  

OUTPUT: 

  

A triple ``(g, s, t)`` such that ``g`` is the non-negative gcd of 

``self`` and ``n``, and ``s`` and ``t`` are cofactors satisfying the 

Bezout identity 

  

.. MATH:: 

  

g = s \cdot \mathrm{self} + t \cdot n. 

  

.. NOTE:: 

  

There is no guarantee that the cofactors will be minimal. If you 

need the cofactors to be minimal use :meth:`_xgcd`. Also, using 

:meth:`_xgcd` directly might be faster in some cases, see 

:trac:`13628`. 

  

EXAMPLES:: 

  

sage: 6.xgcd(4) 

(2, 1, -1) 

  

""" 

return self._xgcd(n) 

  

def _xgcd(self, Integer n, bint minimal=0): 

r""" 

Return the extended gcd of ``self`` and ``n``. 

  

INPUT: 

  

- ``n`` -- an integer 

- ``minimal`` -- a boolean (default: ``False``), whether to compute 

minimal cofactors (see below) 

  

OUTPUT: 

  

A triple ``(g, s, t)`` such that ``g`` is the non-negative gcd of 

``self`` and ``n``, and ``s`` and ``t`` are cofactors satisfying the 

Bezout identity 

  

.. MATH:: 

  

g = s \cdot \mathrm{self} + t \cdot n. 

  

.. NOTE:: 

  

If ``minimal`` is ``False``, then there is no guarantee that the 

returned cofactors will be minimal in any sense; the only guarantee 

is that the Bezout identity will be satisfied (see examples below). 

  

If ``minimal`` is ``True``, the cofactors will satisfy the following 

conditions. If either ``self`` or ``n`` are zero, the trivial 

solution is returned. If both ``self`` and ``n`` are nonzero, the 

function returns the unique solution such that `0 \leq s < |n|/g` 

(which then must also satisfy 

`0 \leq |t| \leq |\mbox{\rm self}|/g`). 

  

EXAMPLES:: 

  

sage: 5._xgcd(7) 

(1, 3, -2) 

sage: 5*3 + 7*-2 

1 

sage: g,s,t = 58526524056._xgcd(101294172798) 

sage: g 

22544886 

sage: 58526524056 * s + 101294172798 * t 

22544886 

  

Try ``minimal`` option with various edge cases:: 

  

sage: 5._xgcd(0, minimal=True) 

(5, 1, 0) 

sage: (-5)._xgcd(0, minimal=True) 

(5, -1, 0) 

sage: 0._xgcd(5, minimal=True) 

(5, 0, 1) 

sage: 0._xgcd(-5, minimal=True) 

(5, 0, -1) 

sage: 0._xgcd(0, minimal=True) 

(0, 1, 0) 

  

Output may differ with and without the ``minimal`` option:: 

  

sage: 5._xgcd(6) 

(1, -1, 1) 

sage: 5._xgcd(6, minimal=True) 

(1, 5, -4) 

  

Exhaustive tests, checking minimality conditions:: 

  

sage: for a in srange(-20, 20): 

....: for b in srange(-20, 20): 

....: if a == 0 or b == 0: continue 

....: g, s, t = a._xgcd(b) 

....: assert g > 0 

....: assert a % g == 0 and b % g == 0 

....: assert a*s + b*t == g 

....: g, s, t = a._xgcd(b, minimal=True) 

....: assert g > 0 

....: assert a % g == 0 and b % g == 0 

....: assert a*s + b*t == g 

....: assert s >= 0 and s < abs(b)/g 

....: assert abs(t) <= abs(a)/g 

  

AUTHORS: 

  

- David Harvey (2007-12-26): added minimality option 

""" 

cdef Integer g = PY_NEW(Integer) 

cdef Integer s = PY_NEW(Integer) 

cdef Integer t = PY_NEW(Integer) 

  

sig_on() 

mpz_gcdext(g.value, s.value, t.value, self.value, n.value) 

sig_off() 

  

# Note: the GMP documentation for mpz_gcdext (or mpn_gcdext for that 

# matter) makes absolutely no claims about any minimality conditions 

# satisfied by the returned cofactors. They guarantee a non-negative 

# gcd, but that's it. So we have to do some work ourselves. 

  

if not minimal: 

return g, s, t 

  

# handle degenerate cases n == 0 and self == 0 

  

if not mpz_sgn(n.value): 

mpz_set_ui(t.value, 0) 

mpz_abs(g.value, self.value) 

mpz_set_si(s.value, 1 if mpz_sgn(self.value) >= 0 else -1) 

return g, s, t 

  

if not mpz_sgn(self.value): 

mpz_set_ui(s.value, 0) 

mpz_abs(g.value, n.value) 

mpz_set_si(t.value, 1 if mpz_sgn(n.value) >= 0 else -1) 

return g, s, t 

  

# both n and self are nonzero, so we need to do a division and 

# make the appropriate adjustment 

  

cdef mpz_t u1, u2 

mpz_init(u1) 

mpz_init(u2) 

mpz_divexact(u1, n.value, g.value) 

mpz_divexact(u2, self.value, g.value) 

if mpz_sgn(u1) > 0: 

mpz_fdiv_qr(u1, s.value, s.value, u1) 

else: 

mpz_cdiv_qr(u1, s.value, s.value, u1) 

mpz_addmul(t.value, u1, u2) 

mpz_clear(u2) 

mpz_clear(u1) 

  

return g, s, t 

  

cpdef _shift_helper(Integer self, y, int sign): 

""" 

Function used to compute left and right shifts of integers. 

Shifts self y bits to the left if sign is 1, and to the right 

if sign is -1. 

  

WARNING: This function does no error checking. In particular, 

it assumes that sign is either 1 or -1, 

  

EXAMPLES:: 

  

sage: n = 1234 

sage: factor(n) 

2 * 617 

sage: n._shift_helper(1, 1) 

2468 

sage: n._shift_helper(1, -1) 

617 

sage: n._shift_helper(100, 1) 

1564280840681635081446931755433984 

sage: n._shift_helper(100, -1) 

0 

sage: n._shift_helper(-100, 1) 

0 

sage: n._shift_helper(-100, -1) 

1564280840681635081446931755433984 

  

TESTS:: 

  

sage: 1 << (2^60) # optional - mpir 

Traceback (most recent call last): 

... 

MemoryError: failed to allocate ... bytes # 64-bit 

OverflowError: Python int too large to convert to C long # 32-bit 

  

sage: 1 << (2^60) # optional - gmp 

Traceback (most recent call last): 

... 

RuntimeError: Aborted # 64-bit 

OverflowError: Python int too large to convert to C long # 32-bit 

""" 

cdef long n 

  

if type(y) is int: 

# For a Python int, we can just use the Python/C API. 

n = PyInt_AS_LONG(y) 

else: 

# If it's not already an Integer, try to convert it. 

if not isinstance(y, Integer): 

try: 

y = Integer(y) 

except TypeError: 

raise TypeError("unsupported operands for %s: %s, %s"%(("<<" if sign == 1 else ">>"), self, y)) 

except ValueError: 

return bin_op(self, y, operator.lshift if sign == 1 else operator.rshift) 

  

# If y wasn't a Python int, it's now an Integer, so set n 

# accordingly. 

if mpz_fits_slong_p((<Integer>y).value): 

n = mpz_get_si((<Integer>y).value) 

elif sign * mpz_sgn((<Integer>y).value) < 0: 

# Doesn't fit in a long so shifting to the right by 

# this much will be 0. 

return PY_NEW(Integer) 

else: 

# Doesn't fit in a long so shifting to the left by 

# this much will raise appropriate overflow error 

n = y 

  

# Decide which way we're shifting 

n *= sign 

  

# Now finally call into MPIR to do the shifting. 

cdef Integer z = PY_NEW(Integer) 

sig_on() 

if n < 0: 

mpz_fdiv_q_2exp(z.value, self.value, -n) 

else: 

mpz_mul_2exp(z.value, self.value, n) 

sig_off() 

return z 

  

def __lshift__(x, y): 

""" 

Shift x to the left by y bits. 

  

EXAMPLES:: 

  

sage: 32 << 2 

128 

sage: 32 << int(2) 

128 

sage: int(32) << 2 

128 

sage: 1 << 2.5 

Traceback (most recent call last): 

... 

TypeError: unsupported operands for <<: 1, 2.5000... 

  

sage: 32 << (4/2) 

128 

  

A negative shift to the left is treated as a right shift:: 

  

sage: 128 << -2 

32 

sage: 128 << (-2^100) 

0 

""" 

# note that x need not be self -- int(3) << ZZ(2) will 

# dispatch this function 

if not isinstance(x, Integer): 

return x << int(y) 

return (<Integer>x)._shift_helper(y, 1) 

  

def __rshift__(x, y): 

""" 

Shift x to the right by y bits. 

  

EXAMPLES:: 

  

sage: 32 >> 2 

8 

sage: 32 >> int(2) 

8 

sage: int(32) >> 2 

8 

sage: 1 >> 2.5 

Traceback (most recent call last): 

... 

TypeError: unsupported operands for >>: 1, 2.5000... 

sage: 10^5 >> 10^100 

0 

  

A negative shift to the right is treated as a left shift:: 

  

sage: 8 >> -2 

32 

""" 

# note that x need not be self -- int(3) >> ZZ(2) will 

# dispatch this function 

if not isinstance(x, Integer): 

return x >> int(y) 

return (<Integer>x)._shift_helper(y, -1) 

  

cdef _and(Integer self, Integer other): 

cdef Integer x = PY_NEW(Integer) 

mpz_and(x.value, self.value, other.value) 

return x 

  

def __and__(x, y): 

""" 

Return the bitwise and two integers. 

  

EXAMPLES:: 

  

sage: n = Integer(6); m = Integer(2) 

sage: n & m 

2 

sage: n.__and__(m) 

2 

""" 

if isinstance(x, Integer) and isinstance(y, Integer): 

return (<Integer>x)._and(y) 

return bin_op(x, y, operator.and_) 

  

cdef _or(Integer self, Integer other): 

cdef Integer x = PY_NEW(Integer) 

mpz_ior(x.value, self.value, other.value) 

return x 

  

def __or__(x, y): 

""" 

Return the bitwise or of the integers x and y. 

  

EXAMPLES:: 

  

sage: n = 8; m = 4 

sage: n.__or__(m) 

12 

""" 

if isinstance(x, Integer) and isinstance(y, Integer): 

return (<Integer>x)._or(y) 

return bin_op(x, y, operator.or_) 

  

def __invert__(self): 

""" 

Return the multiplicative inverse of self, as a rational number. 

  

EXAMPLES:: 

  

sage: n = 10 

sage: 1/n 

1/10 

sage: n.__invert__() 

1/10 

sage: n = -3 

sage: ~n 

-1/3 

""" 

if mpz_sgn(self.value) == 0: 

raise ZeroDivisionError("rational division by zero") 

cdef Rational x 

x = <Rational> Rational.__new__(Rational) 

mpz_set_ui(mpq_numref(x.value), 1) 

mpz_set(mpq_denref(x.value), self.value) 

if mpz_sgn(self.value) == -1: 

mpz_neg(mpq_numref(x.value), mpq_numref(x.value)) 

mpz_neg(mpq_denref(x.value), mpq_denref(x.value)) 

return x 

  

def inverse_of_unit(self): 

""" 

Return inverse of self if self is a unit in the integers, i.e., 

self is -1 or 1. Otherwise, raise a ZeroDivisionError. 

  

EXAMPLES:: 

  

sage: (1).inverse_of_unit() 

1 

sage: (-1).inverse_of_unit() 

-1 

sage: 5.inverse_of_unit() 

Traceback (most recent call last): 

... 

ArithmeticError: inverse does not exist 

sage: 0.inverse_of_unit() 

Traceback (most recent call last): 

... 

ArithmeticError: inverse does not exist 

""" 

if mpz_cmpabs_ui(self.value, 1) == 0: 

return self 

else: 

raise ArithmeticError("inverse does not exist") 

  

def inverse_mod(self, n): 

""" 

Returns the inverse of self modulo `n`, if this inverse exists. 

Otherwise, raises a ``ZeroDivisionError`` exception. 

  

INPUT: 

  

- ``self`` - Integer 

  

- ``n`` - Integer, or ideal of integer ring 

  

OUTPUT: 

  

- ``x`` - Integer such that x\*self = 1 (mod m), or 

raises ZeroDivisionError. 

  

IMPLEMENTATION: 

  

Call the mpz_invert GMP library function. 

  

EXAMPLES:: 

  

sage: a = Integer(189) 

sage: a.inverse_mod(10000) 

4709 

sage: a.inverse_mod(-10000) 

4709 

sage: a.inverse_mod(1890) 

Traceback (most recent call last): 

... 

ZeroDivisionError: Inverse does not exist. 

sage: a = Integer(19)**100000 

sage: b = a*a 

sage: c = a.inverse_mod(b) 

Traceback (most recent call last): 

... 

ZeroDivisionError: Inverse does not exist. 

  

We check that :trac:`10625` is fixed:: 

  

sage: ZZ(2).inverse_mod(ZZ.ideal(3)) 

2 

  

We check that :trac:`9955` is fixed:: 

  

sage: Rational(3)%Rational(-1) 

0 

""" 

cdef int r 

if isinstance(n, sage.rings.ideal.Ideal_pid) and n.ring() == the_integer_ring: 

n = n.gen() 

cdef Integer m = as_Integer(n) 

cdef Integer ans = <Integer>PY_NEW(Integer) 

if mpz_cmpabs_ui(m.value, 1) == 0: 

return zero 

sig_on() 

r = mpz_invert(ans.value, self.value, m.value) 

sig_off() 

if r == 0: 

raise ZeroDivisionError("Inverse does not exist.") 

return ans 

  

def gcd(self, n): 

""" 

Return the greatest common divisor of self and `n`. 

  

EXAMPLES:: 

  

sage: gcd(-1,1) 

1 

sage: gcd(0,1) 

1 

sage: gcd(0,0) 

0 

sage: gcd(2,2^6) 

2 

sage: gcd(21,2^6) 

1 

""" 

if not isinstance(n, Integer) and not isinstance(n, int): 

left, right = coercion_model.canonical_coercion(self, n) 

return left.gcd(right) 

cdef Integer m = as_Integer(n) 

cdef Integer g = PY_NEW(Integer) 

sig_on() 

mpz_gcd(g.value, self.value, m.value) 

sig_off() 

return g 

  

def crt(self, y, m, n): 

""" 

Return the unique integer between `0` and `mn` that is congruent to 

the integer modulo `m` and to `y` modulo `n`. We assume that `m` and 

`n` are coprime. 

  

EXAMPLES:: 

  

sage: n = 17 

sage: m = n.crt(5, 23, 11); m 

247 

sage: m%23 

17 

sage: m%11 

5 

""" 

cdef object g, s, t 

cdef Integer _y, _m, _n 

_y = Integer(y); _m = Integer(m); _n = Integer(n) 

g, s, t = _m.xgcd(_n) 

if not g.is_one(): 

raise ArithmeticError("CRT requires that gcd of moduli is 1.") 

# Now s*m + t*n = 1, so the answer is x + (y-x)*s*m, where x=self. 

return (self + (_y - self) * s * _m) % (_m * _n) 

  

def test_bit(self, long index): 

r""" 

Return the bit at ``index``. 

  

If the index is negative, returns 0. 

  

Although internally a sign-magnitude representation is used 

for integers, this method pretends to use a two's complement 

representation. This is illustrated with a negative integer 

below. 

  

EXAMPLES:: 

  

sage: w = 6 

sage: w.str(2) 

'110' 

sage: w.test_bit(2) 

1 

sage: w.test_bit(-1) 

0 

sage: x = -20 

sage: x.str(2) 

'-10100' 

sage: x.test_bit(4) 

0 

sage: x.test_bit(5) 

1 

sage: x.test_bit(6) 

1 

""" 

if index < 0: 

return 0 

else: 

return mpz_tstbit(self.value, index) 

  

def popcount(self): 

""" 

Return the number of 1 bits in the binary representation. 

If self<0, we return Infinity. 

  

EXAMPLES:: 

  

sage: n = 123 

sage: n.str(2) 

'1111011' 

sage: n.popcount() 

6 

  

sage: n = -17 

sage: n.popcount() 

+Infinity 

""" 

if mpz_sgn(self.value) < 0: 

return sage.rings.infinity.Infinity 

return smallInteger(mpz_popcount(self.value)) 

  

  

def conjugate(self): 

""" 

Return the complex conjugate of this integer, which is the 

integer itself. 

  

EXAMPLES: 

sage: n = 205 

sage: n.conjugate() 

205 

""" 

return self 

  

def binomial(self, m, algorithm='mpir'): 

""" 

Return the binomial coefficient "self choose m". 

  

INPUT: 

  

- ``m`` -- an integer 

  

- ``algorithm`` -- ``'mpir'`` (default) or ``'pari'``; ``'mpir'`` is 

faster for small ``m``, and ``'pari'`` tends to be faster for 

large ``m`` 

  

OUTPUT: 

  

- integer 

  

EXAMPLES:: 

  

sage: 10.binomial(2) 

45 

sage: 10.binomial(2, algorithm='pari') 

45 

sage: 10.binomial(-2) 

0 

sage: (-2).binomial(3) 

-4 

sage: (-3).binomial(0) 

1 

  

The argument ``m`` or (``self-m``) must fit into unsigned long:: 

  

sage: (2**256).binomial(2**256) 

1 

sage: (2**256).binomial(2**256-1) 

115792089237316195423570985008687907853269984665640564039457584007913129639936 

sage: (2**256).binomial(2**128) 

Traceback (most recent call last): 

... 

OverflowError: m must fit in an unsigned long 

  

TESTS:: 

  

sage: 0.binomial(0) 

1 

sage: 0.binomial(1) 

0 

sage: 0.binomial(-1) 

0 

sage: 13.binomial(2r) 

78 

  

Check that it can be interrupted (:trac:`17852`):: 

  

sage: alarm(0.5); (2^100).binomial(2^22, algorithm='mpir') 

Traceback (most recent call last): 

... 

AlarmInterrupt 

  

For PARI, we try 10 interrupts with increasing intervals to 

check for reliable interrupting, see :trac:`18919`:: 

  

sage: from cysignals import AlarmInterrupt 

sage: for i in [1..10]: # long time (5s) 

....: try: 

....: alarm(i/11) 

....: (2^100).binomial(2^22, algorithm='pari') 

....: except AlarmInterrupt: 

....: pass 

""" 

cdef Integer x 

cdef Integer mm 

  

if isinstance(m, Integer): 

mm = m 

else: 

mm = Integer(m) 

  

# trivial cases and potential simplification binom(n,x) -> binom(n,n-x) 

if self == zero or mm < zero or mm > self > zero: 

return one if mm == zero else zero 

  

if 2*mm > self > zero: 

mm = self - mm 

  

if mm == zero: 

return one 

if mm == one: 

return self 

  

# now call the various backend 

if algorithm == 'mpir': 

x = PY_NEW(Integer) 

if mpz_fits_ulong_p(mm.value): 

sig_on() 

mpz_bin_ui(x.value, self.value, mpz_get_ui(mm.value)) 

sig_off() 

else: 

raise OverflowError("m must fit in an unsigned long") 

return x 

elif algorithm == 'pari': 

return the_integer_ring(self.__pari__().binomial(mm)) 

else: 

raise ValueError("algorithm must be one of: 'pari', 'mpir'") 

  

  

cdef int mpz_set_str_python(mpz_ptr z, char* s, int base) except -1: 

""" 

Wrapper around ``mpz_set_str()`` which supports :pep:`3127` 

literals. 

  

If the string is invalid, a ``TypeError`` will be raised. 

  

INPUT: 

  

- ``z`` -- A pre-allocated ``mpz_t`` where the result will be 

stored. 

  

- ``s`` -- A string to be converted to an ``mpz_t``. 

  

- ``base`` -- Either 0 or a base between 2 and 36: a base to use 

for the string conversion. 0 means auto-detect using prefixes. 

  

EXAMPLES:: 

  

sage: Integer('12345') 

12345 

sage: Integer(' - 1 2 3 4 5 ') 

-12345 

sage: Integer(u' - 0x 1 2 3 4 5 ') 

-74565 

sage: Integer('-0012345', 16) 

-74565 

sage: Integer('+0x12345') 

74565 

sage: Integer('0X12345', 16) 

Traceback (most recent call last): 

... 

TypeError: unable to convert '0X12345' to an integer 

sage: Integer('0x12345', 1000) 

Traceback (most recent call last): 

... 

ValueError: base (=1000) must be 0 or between 2 and 36 

sage: Integer('0x00DeadBeef') 

3735928559 

sage: Integer('0x0x12345') 

Traceback (most recent call last): 

... 

TypeError: unable to convert '0x0x12345' to an integer 

sage: Integer('-0B100') 

-4 

sage: Integer('-0B100', 16) 

-45312 

sage: Integer('0B12345') 

Traceback (most recent call last): 

... 

TypeError: unable to convert '0B12345' to an integer 

  

Test zeros:: 

  

sage: Integer('') 

Traceback (most recent call last): 

... 

TypeError: unable to convert '' to an integer 

sage: Integer("0") 

0 

sage: Integer(" 0O 0 ") # second character is the letter O 

0 

sage: Integer("-00") 

0 

sage: Integer("+00000", 4) 

0 

  

For octals, the old leading-zero style is deprecated (unless an 

explicit base is given):: 

  

sage: Integer('0o12') 

10 

sage: Integer('012', 8) 

10 

sage: Integer('012') 

doctest:...: DeprecationWarning: use 0o as octal prefix instead of 0 

If you do not want this number to be interpreted as octal, remove the leading zeros. 

See http://trac.sagemath.org/17413 for details. 

10 

  

We disallow signs in unexpected places:: 

  

sage: Integer('+ -0') 

Traceback (most recent call last): 

... 

TypeError: unable to convert '+ -0' to an integer 

sage: Integer('0o-0') 

Traceback (most recent call last): 

... 

TypeError: unable to convert '0o-0' to an integer 

""" 

cdef int sign = 1 

cdef int warnoctal = 0 

cdef char* x = s 

  

if base != 0 and (base < 2 or base > 36): 

raise ValueError("base (=%s) must be 0 or between 2 and 36"%base) 

  

while x[0] == c' ': x += 1 # Strip spaces 

  

# Check for signs 

if x[0] == c'-': 

sign = -1 

x += 1 

elif x[0] == c'+': 

x += 1 

  

while x[0] == c' ': x += 1 # Strip spaces 

  

# If no base was given, check for PEP 3127 prefixes 

if base == 0: 

if x[0] != c'0': 

base = 10 

else: 

# String starts with "0" 

if x[1] == c'b' or x[1] == c'B': 

x += 2 

base = 2 

elif x[1] == c'o' or x[1] == c'O': 

x += 2 

base = 8 

elif x[1] == c'x' or x[1] == c'X': 

x += 2 

base = 16 

else: 

# Give deprecation warning about octals, unless the 

# number is zero (to allow for "0"). 

base = 8 

warnoctal = 1 

  

while x[0] == c' ': x += 1 # Strip spaces 

  

# Disallow a sign here 

if x[0] == '-' or x[0] == '+': 

x = "" # Force an error below 

  

assert base >= 2 

if mpz_set_str(z, x, base) != 0: 

raise TypeError("unable to convert %r to an integer" % char_to_str(s)) 

if sign < 0: 

mpz_neg(z, z) 

if warnoctal and mpz_sgn(z) != 0: 

from sage.misc.superseded import deprecation 

deprecation(17413, "use 0o as octal prefix instead of 0\nIf you do not want this number to be interpreted as octal, remove the leading zeros.") 

  

from sage.misc.lazy_import import lazy_import 

lazy_import('sage.arith.functions', 'LCM_list', deprecation=22630) 

  

def GCD_list(v): 

r""" 

Return the greatest common divisor of a list of integers. 

  

INPUT: 

  

- ``v`` -- list or tuple 

  

Elements of `v` are converted to Sage integers. An empty list has 

GCD zero. 

  

This function is used, for example, by ``rings/arith.py``. 

  

EXAMPLES:: 

  

sage: from sage.rings.integer import GCD_list 

sage: w = GCD_list([3,9,30]); w 

3 

sage: type(w) 

<type 'sage.rings.integer.Integer'> 

  

Check that the bug reported in :trac:`3118` has been fixed:: 

  

sage: sage.rings.integer.GCD_list([2,2,3]) 

1 

  

The inputs are converted to Sage integers. 

  

:: 

  

sage: w = GCD_list([int(3), int(9), '30']); w 

3 

sage: type(w) 

<type 'sage.rings.integer.Integer'> 

  

Check that the GCD of the empty list is zero (:trac:`17257`):: 

  

sage: GCD_list([]) 

0 

""" 

cdef int i, n = len(v) 

cdef Integer z = <Integer>PY_NEW(Integer) 

  

for i from 0 <= i < n: 

if not isinstance(v[i], Integer): 

if not isinstance(v, list): 

v = list(v) 

v[i] = Integer(v[i]) 

  

if n == 0: 

return zero 

elif n == 1: 

return v[0].abs() 

  

sig_on() 

mpz_gcd(z.value, (<Integer>v[0]).value, (<Integer>v[1]).value) 

for i from 2 <= i < n: 

if mpz_cmp_ui(z.value, 1) == 0: 

break 

mpz_gcd(z.value, z.value, (<Integer>v[i]).value) 

sig_off() 

  

return z 

  

def make_integer(s): 

""" 

Create a Sage integer from the base-32 Python *string* s. This is 

used in unpickling integers. 

  

EXAMPLES:: 

  

sage: from sage.rings.integer import make_integer 

sage: make_integer('-29') 

-73 

sage: make_integer(29) 

Traceback (most recent call last): 

... 

TypeError: expected str...Integer found 

""" 

cdef Integer r = PY_NEW(Integer) 

r._reduce_set(s) 

return r 

  

cdef class int_to_Z(Morphism): 

""" 

Morphism from Python ints to Sage integers. 

  

EXAMPLES:: 

  

sage: f = ZZ.coerce_map_from(int); type(f) 

<type 'sage.rings.integer.int_to_Z'> 

sage: f(5r) 

5 

sage: type(f(5r)) 

<type 'sage.rings.integer.Integer'> 

sage: 1 + 2r 

3 

sage: type(1 + 2r) 

<type 'sage.rings.integer.Integer'> 

  

This is intented for internal use by the coercion system, 

to facilitate fast expressions mixing ints and more complex 

Python types. Note that (as with all morphisms) the input 

is forcably coerced to the domain ``int`` if it is not 

already of the correct type which may have undesirable results:: 

  

sage: f.domain() 

Set of Python objects of class 'int' 

sage: f(1/3) 

0 

sage: f(1.7) 

1 

sage: f("10") 

10 

  

A pool is used for small integers:: 

  

sage: f(10) is f(10) 

True 

sage: f(-2) is f(-2) 

True 

""" 

  

def __init__(self): 

""" 

TESTS:: 

  

sage: f = ZZ.coerce_map_from(int) 

sage: f.parent() 

Set of Morphisms from Set of Python objects of class 'int' to Integer Ring in Category of sets 

""" 

import sage.categories.homset 

from sage.structure.parent import Set_PythonType 

Morphism.__init__(self, sage.categories.homset.Hom(Set_PythonType(int), integer_ring.ZZ)) 

  

cpdef Element _call_(self, a): 

""" 

Returns a new integer with the same value as a. 

  

TESTS:: 

  

sage: f = ZZ.coerce_map_from(int) 

sage: f(100r) 

100 

""" 

if type(a) is not int: 

raise TypeError("must be a Python int object") 

  

return smallInteger(PyInt_AS_LONG(a)) 

  

def _repr_type(self): 

""" 

TESTS:: 

  

sage: f = ZZ.coerce_map_from(int) 

sage: print(f) 

Native morphism: 

From: Set of Python objects of class 'int' 

To: Integer Ring 

""" 

return "Native" 

  

  

cdef class long_to_Z(Morphism): 

""" 

EXAMPLES:: 

  

sage: f = ZZ.coerce_map_from(long); f 

Native morphism: 

From: Set of Python objects of class 'long' 

To: Integer Ring 

sage: f(1rL) 

1 

sage: f(-10000000000000000000001r) 

-10000000000000000000001 

""" 

def __init__(self): 

import sage.categories.homset 

from sage.structure.parent import Set_PythonType 

Morphism.__init__(self, sage.categories.homset.Hom(Set_PythonType(long), integer_ring.ZZ)) 

  

cpdef Element _call_(self, a): 

cdef Integer r 

cdef long l 

cdef int err = 0 

  

integer_check_long_py(a, &l, &err) 

if not err: 

return smallInteger(l) 

  

r = <Integer>PY_NEW(Integer) 

mpz_set_pylong(r.value, a) 

return r 

  

def _repr_type(self): 

return "Native" 

  

############### INTEGER CREATION CODE ##################### 

  

# This variable holds the size of any Integer object in bytes. 

cdef int sizeof_Integer 

  

# We use a global Integer element to steal all the references 

# from. DO NOT INITIALIZE IT AGAIN and DO NOT REFERENCE IT! 

cdef Integer global_dummy_Integer 

global_dummy_Integer = Integer() 

  

  

# A global pool for performance when integers are rapidly created and destroyed. 

# It operates on the following principles: 

# 

# - The pool starts out empty. 

# - When an new integer is needed, one from the pool is returned 

# if available, otherwise a new Integer object is created 

# - When an integer is collected, it will add it to the pool 

# if there is room, otherwise it will be deallocated. 

cdef int integer_pool_size = 100 

  

cdef PyObject** integer_pool 

cdef int integer_pool_count = 0 

  

# used for profiling the pool 

cdef int total_alloc = 0 

cdef int use_pool = 0 

  

  

cdef PyObject* fast_tp_new(type t, args, kwds) except NULL: 

global integer_pool, integer_pool_count, total_alloc, use_pool 

  

cdef PyObject* new 

cdef mpz_ptr new_mpz 

  

# for profiling pool usage 

# total_alloc += 1 

  

# If there is a ready integer in the pool, we will 

# decrement the counter and return that. 

  

if integer_pool_count > 0: 

  

# for profiling pool usage 

# use_pool += 1 

  

integer_pool_count -= 1 

new = <PyObject *> integer_pool[integer_pool_count] 

  

# Otherwise, we have to create one. 

else: 

  

# allocate enough room for the Integer, sizeof_Integer is 

# sizeof(Integer). The use of PyObject_Malloc directly 

# assumes that Integers are not garbage collected, i.e. 

# they do not possess references to other Python 

# objects (as indicated by the Py_TPFLAGS_HAVE_GC flag). 

# See below for a more detailed description. 

new = <PyObject*>PyObject_Malloc( sizeof_Integer ) 

if unlikely(new == NULL): 

raise MemoryError 

  

# Now set every member as set in z, the global dummy Integer 

# created before this tp_new started to operate. 

memcpy(new, (<void*>global_dummy_Integer), sizeof_Integer ) 

  

# We allocate memory for the _mp_d element of the value of this 

# new Integer. We allocate one limb. Normally, one would use 

# mpz_init() for this, but we allocate the memory directly. 

# This saves time both by avoiding extra function calls and 

# because the rest of the mpz struct was already initialized 

# fully using the memcpy above. 

# 

# What is done here is potentially very dangerous as it reaches 

# deeply into the internal structure of GMP. Consequently things 

# may break if a new release of GMP changes some internals. To 

# emphasize this, this is what the GMP manual has to say about 

# the documentation for the struct we are using: 

# 

# "This chapter is provided only for informational purposes and the 

# various internals described here may change in future GMP releases. 

# Applications expecting to be compatible with future releases should use 

# only the documented interfaces described in previous chapters." 

new_mpz = <mpz_ptr>((<Integer>new).value) 

new_mpz._mp_d = <mp_ptr>check_malloc(GMP_LIMB_BITS >> 3) 

  

# This line is only needed if Python is compiled in debugging mode 

# './configure --with-pydebug' or SAGE_DEBUG=yes. If that is the 

# case a Python object has a bunch of debugging fields which are 

# initialized with this macro. 

  

if_Py_TRACE_REFS_then_PyObject_INIT( 

new, Py_TYPE(global_dummy_Integer)) 

  

# The global_dummy_Integer may have a reference count larger than 

# one, but it is expected that newly created objects have a 

# reference count of one. This is potentially unneeded if 

# everybody plays nice, because the gobal_dummy_Integer has only 

# one reference in that case. 

  

# Objects from the pool have reference count zero, so this 

# needs to be set in this case. 

  

new.ob_refcnt = 1 

  

return new 

  

cdef void fast_tp_dealloc(PyObject* o): 

  

# If there is room in the pool for a used integer object, 

# then put it in rather than deallocating it. 

  

global integer_pool, integer_pool_count 

  

cdef mpz_ptr o_mpz = <mpz_ptr>((<Integer>o).value) 

  

if integer_pool_count < integer_pool_size: 

  

# Here we free any extra memory used by the mpz_t by 

# setting it to a single limb. 

if o_mpz._mp_alloc > 10: 

_mpz_realloc(o_mpz, 1) 

  

# It's cheap to zero out an integer, so do it here. 

o_mpz._mp_size = 0 

  

# And add it to the pool. 

integer_pool[integer_pool_count] = o 

integer_pool_count += 1 

return 

  

# Again, we move to the mpz_t and clear it. As in fast_tp_new, 

# we free the memory directly. 

sig_free(o_mpz._mp_d) 

  

# Free the object. This assumes that Py_TPFLAGS_HAVE_GC is not 

# set. If it was set another free function would need to be 

# called. 

PyObject_Free(o) 

  

from sage.misc.allocator cimport hook_tp_functions 

cdef hook_fast_tp_functions(): 

""" 

Initialize the fast integer creation functions. 

""" 

global global_dummy_Integer, sizeof_Integer, integer_pool 

  

integer_pool = <PyObject**>check_allocarray(integer_pool_size, sizeof(PyObject*)) 

  

cdef PyObject* o 

o = <PyObject *>global_dummy_Integer 

  

# store how much memory needs to be allocated for an Integer. 

sizeof_Integer = o.ob_type.tp_basicsize 

  

# Finally replace the functions called when an Integer needs 

# to be constructed/destructed. 

hook_tp_functions(global_dummy_Integer, <newfunc>(&fast_tp_new), <destructor>(&fast_tp_dealloc), False) 

  

cdef integer(x): 

if isinstance(x, Integer): 

return x 

return Integer(x) 

  

  

def free_integer_pool(): 

cdef int i 

cdef PyObject *o 

  

global integer_pool_count, integer_pool_size 

  

for i from 0 <= i < integer_pool_count: 

o = integer_pool[i] 

mpz_clear( (<Integer>o).value ) 

# Free the object. This assumes that Py_TPFLAGS_HAVE_GC is not 

# set. If it was set another free function would need to be 

# called. 

PyObject_Free(o) 

  

integer_pool_size = 0 

integer_pool_count = 0 

sig_free(integer_pool) 

  

# Replace default allocation and deletion with faster custom ones 

hook_fast_tp_functions() 

  

# zero and one initialization 

initialized = False 

cdef set_zero_one_elements(): 

global the_integer_ring, initialized 

if initialized: return 

the_integer_ring._zero_element = Integer(0) 

the_integer_ring._one_element = Integer(1) 

initialized = True 

set_zero_one_elements() 

  

cdef Integer zero = the_integer_ring._zero_element 

cdef Integer one = the_integer_ring._one_element 

  

# pool of small integer for fast sign computation 

# Use the same defaults as Python, documented at http://docs.python.org/2/c-api/int.html#PyInt_FromLong 

DEF small_pool_min = -5 

DEF small_pool_max = 256 

# we could use the above zero and one here 

cdef list small_pool = [Integer(k) for k in range(small_pool_min, small_pool_max+1)] 

  

cdef inline Integer smallInteger(long value): 

""" 

This is the fastest way to create a (likely) small Integer. 

""" 

cdef Integer z 

if small_pool_min <= value <= small_pool_max: 

return <Integer>small_pool[value - small_pool_min] 

else: 

z = PY_NEW(Integer) 

mpz_set_si(z.value, value) 

return z 

  

  

# The except value is just some random double, it doesn't matter what it is. 

cdef double mpz_get_d_nearest(mpz_t x) except? -648555075988944.5: 

""" 

Convert a ``mpz_t`` to a ``double``, with round-to-nearest-even. 

This differs from ``mpz_get_d()`` which does round-to-zero. 

  

TESTS:: 

  

sage: x = ZZ(); float(x) 

0.0 

sage: x = 2^54 - 1 

sage: float(x) 

1.8014398509481984e+16 

sage: float(-x) 

-1.8014398509481984e+16 

sage: x = 2^10000; float(x) 

inf 

sage: float(-x) 

-inf 

  

:: 

  

sage: x = (2^53 - 1) * 2^971; float(x) # Largest double 

1.7976931348623157e+308 

sage: float(-x) 

-1.7976931348623157e+308 

sage: x = (2^53) * 2^971; float(x) 

inf 

sage: float(-x) 

-inf 

sage: x = ZZ((2^53 - 1/2) * 2^971); float(x) 

inf 

sage: float(-x) 

-inf 

sage: x = ZZ((2^53 - 3/4) * 2^971); float(x) 

1.7976931348623157e+308 

sage: float(-x) 

-1.7976931348623157e+308 

  

AUTHORS: 

  

- Jeroen Demeyer (:trac:`16385`, based on :trac:`14416`) 

""" 

cdef mp_bitcnt_t sx = mpz_sizeinbase(x, 2) 

  

# Easy case: x is exactly representable as double. 

if sx <= 53: 

return mpz_get_d(x) 

  

cdef int resultsign = mpz_sgn(x) 

  

# Check for overflow 

if sx > 1024: 

if resultsign < 0: 

return -1.0/0.0 

else: 

return 1.0/0.0 

  

# General case 

  

# We should shift x right by this amount in order 

# to have 54 bits remaining. 

cdef mp_bitcnt_t shift = sx - 54 

  

# Compute q = trunc(x / 2^shift) and let remainder_is_zero be True 

# if and only if no truncation occurred. 

cdef int remainder_is_zero 

remainder_is_zero = mpz_divisible_2exp_p(x, shift) 

  

sig_on() 

  

cdef mpz_t q 

mpz_init(q) 

mpz_tdiv_q_2exp(q, x, shift) 

  

# Convert abs(q) to a 64-bit integer. 

cdef mp_limb_t* q_limbs = (<mpz_ptr>q)._mp_d 

cdef uint64_t q64 

if sizeof(mp_limb_t) >= 8: 

q64 = q_limbs[0] 

else: 

assert sizeof(mp_limb_t) == 4 

q64 = q_limbs[1] 

q64 = (q64 << 32) + q_limbs[0] 

  

mpz_clear(q) 

sig_off() 

  

# Round q from 54 to 53 bits of precision. 

if ((q64 & 1) == 0): 

# Round towards zero 

pass 

else: 

if not remainder_is_zero: 

# Remainder is non-zero: round away from zero 

q64 += 1 

else: 

# Halfway case: round to even 

q64 += (q64 & 2) - 1 

  

# The conversion of q64 to double is *exact*. 

# This is because q64 is even and satisfies 2^53 <= q64 <= 2^54. 

cdef double d = <double>q64 

if resultsign < 0: 

d = -d 

return ldexp(d, shift)