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

7493

7494

7495

7496

7497

7498

7499

7500

7501

7502

7503

7504

7505

7506

7507

7508

7509

7510

7511

7512

7513

7514

7515

7516

7517

7518

7519

7520

7521

7522

7523

7524

7525

7526

7527

7528

7529

7530

7531

7532

7533

7534

7535

7536

7537

7538

7539

7540

7541

7542

7543

7544

7545

7546

7547

7548

7549

7550

7551

7552

7553

7554

7555

7556

7557

7558

7559

7560

7561

7562

7563

7564

7565

7566

7567

7568

7569

7570

7571

7572

7573

7574

7575

7576

7577

7578

7579

7580

7581

7582

7583

7584

7585

7586

7587

7588

7589

7590

7591

7592

7593

7594

7595

7596

7597

7598

7599

7600

7601

7602

7603

7604

7605

7606

7607

7608

7609

7610

7611

7612

7613

7614

7615

7616

7617

7618

7619

7620

7621

7622

7623

7624

7625

7626

7627

7628

7629

7630

7631

7632

7633

7634

7635

7636

7637

7638

7639

7640

7641

7642

7643

7644

7645

7646

7647

7648

7649

7650

7651

7652

7653

7654

7655

7656

7657

7658

7659

7660

7661

7662

7663

7664

7665

7666

7667

7668

7669

7670

7671

7672

7673

7674

7675

7676

7677

7678

7679

7680

7681

7682

7683

7684

7685

7686

7687

7688

7689

7690

7691

7692

7693

7694

7695

7696

7697

7698

7699

7700

7701

7702

7703

7704

7705

7706

7707

7708

7709

7710

7711

7712

7713

7714

7715

7716

7717

7718

7719

7720

7721

7722

7723

7724

7725

7726

7727

7728

7729

7730

7731

7732

7733

7734

7735

7736

7737

7738

7739

7740

7741

7742

7743

7744

7745

7746

7747

7748

7749

7750

7751

7752

7753

7754

7755

7756

7757

7758

7759

7760

7761

7762

7763

7764

7765

7766

7767

7768

7769

7770

7771

7772

7773

7774

7775

7776

7777

7778

7779

7780

7781

7782

7783

7784

7785

7786

7787

7788

7789

7790

7791

7792

7793

7794

7795

7796

7797

7798

7799

7800

7801

7802

7803

7804

7805

7806

7807

7808

7809

7810

7811

7812

7813

7814

7815

7816

7817

7818

7819

7820

7821

7822

7823

7824

7825

7826

7827

7828

7829

7830

7831

7832

7833

7834

7835

7836

7837

7838

7839

7840

7841

7842

7843

7844

7845

7846

7847

7848

7849

7850

7851

7852

7853

7854

7855

7856

7857

7858

7859

7860

7861

7862

7863

7864

7865

7866

7867

7868

7869

7870

7871

7872

7873

7874

7875

7876

7877

7878

7879

7880

7881

7882

7883

7884

7885

7886

7887

7888

7889

7890

7891

7892

7893

7894

7895

7896

7897

7898

7899

7900

7901

7902

7903

7904

7905

7906

7907

7908

7909

7910

7911

7912

7913

7914

7915

7916

7917

7918

7919

7920

7921

7922

7923

7924

7925

7926

7927

7928

7929

7930

7931

7932

7933

7934

7935

7936

7937

7938

7939

7940

7941

7942

7943

7944

7945

7946

7947

7948

7949

7950

7951

7952

7953

7954

7955

7956

7957

7958

7959

7960

7961

7962

7963

7964

7965

7966

7967

7968

7969

7970

7971

7972

7973

7974

7975

7976

7977

7978

7979

7980

7981

7982

7983

7984

7985

7986

7987

7988

7989

7990

7991

7992

7993

7994

7995

7996

7997

7998

7999

8000

8001

8002

8003

8004

8005

8006

8007

8008

8009

8010

8011

8012

8013

8014

8015

8016

8017

8018

8019

8020

8021

8022

8023

8024

8025

8026

8027

8028

8029

8030

8031

8032

8033

8034

8035

8036

8037

8038

8039

8040

8041

8042

8043

8044

8045

8046

8047

8048

8049

8050

8051

8052

8053

8054

8055

8056

8057

8058

8059

8060

8061

8062

8063

8064

8065

8066

8067

8068

8069

8070

8071

8072

8073

8074

8075

8076

8077

8078

8079

8080

8081

8082

8083

8084

8085

8086

8087

8088

8089

8090

8091

8092

8093

8094

8095

8096

8097

8098

8099

8100

8101

8102

8103

8104

8105

8106

8107

8108

8109

8110

8111

8112

8113

8114

8115

8116

8117

8118

8119

8120

8121

8122

8123

8124

8125

8126

8127

8128

8129

8130

8131

8132

8133

8134

8135

8136

8137

8138

8139

8140

8141

8142

8143

8144

8145

8146

8147

8148

8149

8150

8151

8152

8153

8154

8155

8156

8157

8158

8159

8160

8161

8162

8163

8164

8165

8166

8167

8168

8169

8170

8171

8172

8173

8174

8175

8176

8177

8178

8179

8180

8181

8182

8183

8184

8185

8186

8187

8188

8189

8190

8191

8192

8193

8194

8195

8196

8197

8198

8199

8200

8201

8202

8203

8204

8205

8206

8207

8208

8209

8210

8211

8212

8213

8214

8215

8216

8217

8218

8219

8220

8221

8222

8223

8224

8225

8226

8227

8228

8229

8230

8231

8232

8233

8234

8235

8236

8237

8238

8239

8240

8241

8242

8243

8244

8245

8246

8247

8248

8249

8250

8251

8252

8253

8254

8255

8256

8257

8258

8259

8260

8261

8262

8263

8264

8265

8266

8267

8268

8269

8270

8271

8272

8273

8274

8275

8276

8277

8278

8279

8280

8281

8282

8283

8284

8285

8286

8287

8288

8289

8290

8291

8292

8293

8294

8295

8296

8297

8298

8299

8300

8301

8302

8303

8304

8305

8306

8307

8308

8309

8310

8311

8312

8313

8314

8315

8316

8317

8318

8319

8320

8321

8322

8323

8324

8325

8326

8327

8328

8329

8330

8331

8332

8333

8334

8335

8336

8337

8338

8339

8340

8341

8342

8343

8344

8345

8346

8347

8348

8349

8350

8351

8352

8353

8354

8355

8356

8357

8358

8359

8360

8361

8362

8363

8364

8365

8366

8367

8368

8369

8370

8371

8372

8373

8374

8375

8376

8377

8378

8379

8380

8381

8382

8383

8384

8385

8386

8387

8388

8389

8390

8391

8392

8393

8394

8395

8396

8397

8398

8399

8400

8401

8402

8403

8404

8405

8406

8407

8408

8409

8410

8411

8412

8413

8414

8415

8416

8417

8418

8419

8420

8421

8422

8423

8424

8425

8426

8427

8428

8429

8430

8431

8432

8433

8434

8435

8436

8437

8438

8439

8440

8441

8442

8443

8444

8445

8446

8447

8448

8449

8450

8451

8452

8453

8454

8455

8456

8457

8458

8459

8460

8461

8462

8463

8464

8465

8466

8467

8468

8469

8470

8471

8472

8473

8474

8475

8476

8477

8478

8479

8480

8481

8482

8483

8484

8485

8486

8487

8488

8489

8490

8491

8492

8493

8494

8495

8496

8497

8498

8499

8500

8501

8502

8503

8504

8505

8506

8507

8508

8509

8510

8511

8512

8513

8514

8515

8516

8517

8518

8519

8520

8521

8522

8523

8524

8525

8526

8527

8528

8529

8530

8531

8532

8533

8534

8535

8536

8537

8538

8539

8540

8541

8542

8543

8544

8545

8546

8547

8548

8549

8550

8551

8552

8553

8554

8555

8556

8557

8558

8559

8560

8561

8562

8563

8564

8565

8566

8567

8568

8569

8570

8571

8572

8573

8574

8575

8576

8577

8578

8579

8580

8581

8582

8583

8584

8585

8586

8587

8588

8589

8590

8591

8592

8593

8594

8595

8596

8597

8598

8599

8600

8601

8602

8603

8604

8605

8606

8607

8608

8609

8610

8611

8612

8613

8614

8615

8616

8617

8618

8619

8620

8621

8622

8623

8624

8625

8626

8627

8628

8629

8630

8631

8632

8633

8634

8635

8636

8637

8638

8639

8640

8641

8642

8643

8644

8645

8646

8647

8648

8649

8650

8651

8652

8653

8654

8655

8656

8657

8658

8659

8660

8661

8662

8663

8664

8665

8666

8667

8668

8669

8670

8671

8672

8673

8674

8675

8676

8677

8678

8679

8680

8681

8682

8683

8684

8685

8686

8687

8688

8689

8690

8691

8692

8693

8694

8695

8696

8697

8698

8699

8700

8701

8702

8703

8704

8705

8706

8707

8708

8709

8710

8711

8712

8713

8714

8715

8716

8717

8718

8719

8720

8721

8722

8723

8724

8725

8726

8727

8728

8729

8730

8731

8732

8733

8734

8735

8736

8737

8738

8739

8740

8741

8742

8743

8744

8745

8746

8747

8748

8749

8750

8751

8752

8753

8754

8755

8756

8757

8758

8759

8760

8761

8762

8763

8764

8765

8766

8767

8768

8769

8770

8771

8772

8773

8774

8775

8776

8777

8778

8779

8780

8781

8782

8783

8784

8785

8786

8787

8788

8789

8790

8791

8792

8793

8794

8795

8796

8797

8798

8799

8800

8801

8802

8803

8804

8805

8806

8807

8808

8809

8810

8811

8812

8813

8814

8815

8816

8817

8818

8819

8820

8821

8822

8823

8824

8825

8826

8827

8828

8829

8830

8831

8832

8833

8834

8835

8836

8837

8838

8839

8840

8841

8842

8843

8844

8845

8846

8847

8848

8849

8850

8851

8852

8853

8854

8855

8856

8857

8858

8859

8860

8861

8862

8863

8864

8865

8866

8867

8868

8869

8870

8871

8872

8873

8874

8875

8876

8877

8878

8879

8880

8881

8882

8883

8884

8885

8886

8887

8888

8889

8890

8891

8892

8893

8894

8895

8896

8897

8898

8899

8900

8901

8902

8903

8904

8905

8906

8907

8908

8909

8910

8911

8912

8913

8914

8915

8916

8917

8918

8919

8920

8921

8922

8923

8924

8925

8926

8927

8928

8929

8930

8931

8932

8933

8934

8935

8936

8937

8938

8939

8940

8941

8942

8943

8944

8945

8946

8947

8948

8949

8950

8951

8952

8953

8954

8955

8956

8957

8958

8959

8960

8961

8962

8963

8964

8965

8966

8967

8968

8969

8970

8971

8972

8973

8974

8975

8976

8977

8978

8979

8980

8981

8982

8983

8984

8985

8986

8987

8988

8989

8990

8991

8992

8993

8994

8995

8996

8997

8998

8999

9000

9001

9002

9003

9004

9005

9006

9007

9008

9009

9010

9011

9012

9013

9014

9015

9016

9017

9018

9019

9020

9021

9022

9023

9024

9025

9026

9027

9028

9029

9030

9031

9032

9033

9034

9035

9036

9037

9038

9039

9040

9041

9042

9043

9044

9045

9046

9047

9048

9049

9050

9051

9052

9053

9054

9055

9056

9057

9058

9059

9060

9061

9062

9063

9064

9065

9066

9067

9068

9069

9070

9071

9072

9073

9074

9075

9076

9077

9078

9079

9080

9081

9082

9083

9084

9085

9086

9087

9088

9089

9090

9091

9092

9093

9094

9095

9096

9097

9098

9099

9100

9101

9102

9103

9104

9105

9106

9107

9108

9109

9110

9111

9112

9113

9114

9115

9116

9117

9118

9119

9120

9121

9122

9123

9124

9125

9126

9127

9128

9129

9130

9131

9132

9133

9134

9135

9136

9137

9138

9139

9140

9141

9142

9143

9144

9145

9146

9147

9148

9149

9150

9151

9152

9153

9154

9155

9156

9157

9158

9159

9160

9161

9162

9163

9164

9165

9166

9167

9168

9169

9170

9171

9172

9173

9174

9175

9176

9177

9178

9179

9180

9181

9182

9183

9184

9185

9186

9187

9188

9189

9190

9191

9192

9193

9194

9195

9196

9197

9198

9199

9200

9201

9202

9203

9204

9205

9206

9207

9208

9209

9210

9211

9212

9213

9214

9215

9216

9217

9218

9219

9220

9221

9222

9223

9224

9225

9226

9227

9228

9229

9230

9231

9232

9233

9234

9235

9236

9237

9238

9239

9240

9241

9242

9243

9244

9245

9246

9247

9248

9249

9250

9251

9252

9253

9254

9255

9256

9257

9258

9259

9260

9261

9262

9263

9264

9265

9266

9267

9268

9269

9270

9271

9272

9273

9274

9275

9276

9277

9278

9279

9280

9281

9282

9283

9284

9285

9286

9287

9288

9289

9290

9291

9292

9293

9294

9295

9296

9297

9298

9299

9300

9301

9302

9303

9304

9305

9306

9307

9308

9309

9310

9311

9312

9313

9314

9315

9316

9317

9318

9319

9320

9321

9322

9323

9324

9325

9326

9327

9328

9329

9330

9331

9332

9333

9334

9335

9336

9337

9338

9339

9340

9341

9342

9343

9344

9345

9346

9347

9348

9349

9350

9351

9352

9353

9354

9355

9356

9357

9358

9359

9360

9361

9362

9363

9364

9365

9366

9367

9368

9369

9370

9371

9372

9373

9374

9375

9376

9377

9378

9379

9380

9381

9382

9383

9384

9385

9386

9387

9388

9389

9390

9391

9392

9393

9394

9395

9396

9397

9398

9399

9400

9401

9402

9403

9404

9405

9406

9407

9408

9409

9410

9411

9412

9413

9414

9415

9416

9417

9418

9419

9420

9421

9422

9423

9424

9425

9426

9427

9428

9429

9430

9431

9432

9433

9434

9435

9436

9437

9438

9439

9440

9441

9442

9443

9444

9445

9446

9447

9448

9449

9450

9451

9452

9453

9454

9455

9456

9457

9458

9459

9460

9461

9462

9463

9464

9465

9466

9467

9468

9469

9470

9471

9472

9473

9474

9475

9476

9477

9478

9479

9480

9481

9482

9483

9484

9485

9486

9487

9488

9489

9490

9491

9492

9493

9494

9495

9496

9497

9498

9499

9500

9501

9502

9503

9504

9505

9506

9507

9508

9509

9510

9511

9512

9513

9514

9515

9516

9517

9518

9519

9520

9521

9522

9523

9524

9525

9526

9527

9528

9529

9530

9531

9532

9533

9534

9535

9536

9537

9538

9539

9540

9541

9542

9543

9544

9545

9546

9547

9548

9549

9550

9551

9552

9553

9554

9555

9556

9557

9558

9559

9560

9561

9562

9563

9564

9565

9566

9567

9568

9569

9570

9571

9572

9573

9574

9575

9576

9577

9578

9579

9580

9581

9582

9583

9584

9585

9586

9587

9588

9589

9590

9591

9592

9593

9594

9595

9596

9597

9598

9599

9600

9601

9602

9603

9604

9605

9606

9607

9608

9609

9610

9611

9612

9613

9614

9615

9616

9617

9618

9619

9620

9621

9622

9623

9624

9625

9626

9627

9628

9629

9630

9631

9632

9633

9634

9635

9636

9637

9638

9639

9640

9641

9642

9643

9644

9645

9646

9647

9648

9649

9650

9651

9652

9653

9654

9655

9656

9657

9658

9659

9660

9661

9662

9663

9664

9665

9666

9667

9668

9669

9670

9671

9672

9673

9674

9675

9676

9677

9678

9679

9680

9681

9682

9683

9684

9685

9686

9687

9688

9689

9690

9691

9692

9693

9694

9695

9696

9697

9698

9699

9700

9701

9702

9703

9704

9705

9706

9707

9708

9709

9710

9711

9712

9713

9714

9715

9716

9717

9718

9719

9720

9721

9722

9723

9724

9725

9726

9727

9728

9729

9730

9731

9732

9733

9734

9735

9736

9737

9738

9739

9740

9741

9742

9743

9744

9745

9746

9747

9748

9749

9750

9751

9752

9753

9754

9755

9756

9757

9758

9759

9760

9761

9762

9763

9764

9765

9766

9767

9768

9769

9770

9771

9772

9773

9774

9775

9776

9777

9778

9779

9780

9781

9782

9783

9784

9785

9786

9787

9788

9789

9790

9791

9792

9793

9794

9795

9796

9797

9798

9799

9800

9801

9802

9803

9804

9805

9806

9807

9808

9809

9810

9811

9812

9813

9814

9815

9816

9817

9818

9819

9820

9821

9822

9823

9824

9825

9826

9827

9828

9829

9830

9831

9832

9833

9834

9835

9836

9837

9838

9839

9840

9841

9842

9843

9844

9845

9846

9847

9848

9849

9850

9851

9852

9853

9854

9855

9856

9857

9858

9859

9860

9861

9862

9863

9864

9865

9866

9867

9868

9869

9870

9871

9872

9873

9874

9875

9876

9877

9878

9879

9880

9881

9882

9883

9884

9885

9886

9887

9888

9889

9890

9891

9892

9893

9894

9895

9896

9897

9898

9899

9900

9901

9902

9903

9904

9905

9906

9907

9908

9909

9910

9911

9912

9913

9914

9915

9916

9917

9918

9919

9920

9921

9922

9923

9924

9925

9926

9927

9928

9929

9930

9931

9932

9933

9934

9935

9936

9937

9938

9939

9940

9941

9942

9943

9944

9945

9946

9947

9948

9949

9950

9951

9952

9953

9954

9955

9956

9957

9958

9959

9960

9961

9962

9963

9964

9965

9966

9967

9968

9969

9970

9971

9972

9973

9974

9975

9976

9977

9978

9979

9980

9981

9982

9983

9984

9985

9986

9987

9988

9989

9990

9991

9992

9993

9994

9995

9996

9997

9998

9999

10000

10001

10002

10003

10004

10005

10006

10007

10008

10009

10010

10011

10012

10013

10014

10015

10016

10017

10018

10019

10020

10021

10022

10023

10024

10025

10026

10027

10028

10029

10030

10031

10032

10033

10034

10035

10036

10037

10038

10039

10040

10041

10042

10043

10044

10045

10046

10047

10048

10049

10050

10051

10052

10053

10054

10055

10056

10057

10058

10059

10060

10061

10062

10063

10064

10065

10066

10067

10068

10069

10070

10071

10072

10073

10074

10075

10076

10077

10078

10079

10080

10081

10082

10083

10084

10085

10086

10087

10088

10089

10090

10091

10092

10093

10094

10095

10096

10097

10098

10099

10100

10101

10102

10103

10104

10105

10106

10107

10108

10109

10110

10111

10112

10113

10114

10115

10116

10117

10118

10119

10120

10121

10122

10123

10124

10125

10126

10127

10128

10129

10130

10131

10132

10133

10134

10135

10136

10137

10138

10139

10140

10141

10142

10143

10144

10145

10146

10147

10148

10149

10150

10151

10152

10153

10154

10155

10156

10157

10158

10159

10160

10161

10162

10163

10164

10165

10166

10167

10168

10169

10170

10171

10172

10173

10174

10175

10176

10177

10178

10179

10180

10181

10182

10183

10184

10185

10186

10187

10188

10189

10190

10191

10192

10193

10194

10195

10196

10197

10198

10199

10200

10201

10202

10203

10204

10205

10206

10207

10208

10209

10210

10211

10212

10213

10214

10215

10216

10217

10218

10219

10220

10221

10222

10223

10224

10225

10226

10227

10228

10229

10230

10231

10232

10233

10234

10235

10236

10237

10238

10239

10240

10241

10242

10243

10244

10245

10246

10247

10248

10249

10250

10251

10252

10253

10254

10255

10256

10257

10258

10259

10260

10261

10262

10263

10264

10265

10266

10267

10268

10269

10270

10271

10272

10273

10274

10275

10276

10277

10278

10279

10280

10281

10282

10283

10284

10285

10286

10287

10288

10289

10290

10291

10292

10293

10294

10295

10296

10297

10298

10299

10300

10301

10302

10303

10304

10305

10306

10307

10308

10309

10310

10311

10312

10313

10314

10315

10316

10317

10318

10319

10320

10321

10322

10323

10324

10325

10326

10327

10328

10329

10330

10331

10332

10333

10334

10335

10336

10337

10338

10339

10340

10341

10342

10343

10344

10345

10346

10347

10348

10349

10350

10351

10352

10353

10354

10355

10356

10357

10358

10359

10360

10361

10362

10363

10364

10365

10366

10367

10368

10369

10370

10371

10372

10373

10374

10375

10376

10377

10378

10379

10380

10381

10382

10383

10384

10385

10386

10387

10388

10389

10390

10391

10392

10393

10394

10395

10396

10397

10398

10399

10400

10401

10402

10403

10404

10405

10406

10407

10408

10409

10410

10411

10412

10413

10414

10415

10416

10417

10418

10419

10420

10421

10422

10423

10424

10425

10426

10427

10428

10429

10430

10431

10432

10433

10434

10435

10436

10437

10438

10439

10440

10441

10442

10443

10444

10445

10446

10447

10448

10449

10450

10451

10452

10453

10454

10455

10456

10457

10458

10459

10460

10461

10462

10463

10464

10465

10466

10467

10468

10469

10470

10471

10472

10473

10474

10475

10476

10477

10478

10479

10480

10481

10482

10483

10484

10485

10486

10487

10488

10489

10490

10491

10492

10493

10494

10495

10496

10497

10498

10499

10500

10501

10502

10503

10504

10505

10506

10507

10508

10509

10510

10511

10512

10513

10514

10515

10516

10517

10518

10519

10520

10521

10522

10523

10524

10525

10526

10527

10528

10529

10530

10531

10532

10533

10534

10535

10536

10537

10538

10539

10540

10541

10542

10543

10544

10545

10546

10547

10548

10549

10550

10551

10552

10553

10554

10555

10556

10557

10558

10559

10560

10561

10562

10563

10564

10565

10566

10567

10568

10569

10570

10571

10572

10573

10574

10575

10576

10577

10578

10579

10580

10581

10582

10583

10584

10585

10586

10587

10588

10589

10590

10591

10592

10593

10594

10595

10596

10597

10598

10599

10600

10601

10602

10603

10604

10605

10606

10607

10608

10609

10610

10611

10612

10613

10614

10615

10616

10617

10618

10619

10620

10621

10622

10623

10624

10625

10626

10627

10628

10629

10630

10631

10632

10633

10634

10635

10636

10637

10638

10639

10640

10641

10642

10643

10644

10645

10646

10647

10648

10649

10650

10651

10652

10653

10654

10655

10656

10657

10658

10659

10660

10661

10662

10663

10664

10665

10666

10667

10668

10669

10670

10671

10672

10673

10674

10675

10676

10677

10678

10679

10680

10681

10682

10683

10684

10685

10686

10687

10688

10689

10690

10691

10692

10693

10694

10695

10696

10697

10698

10699

10700

10701

10702

10703

10704

10705

10706

10707

10708

10709

10710

10711

10712

10713

10714

10715

10716

10717

10718

10719

10720

10721

10722

10723

10724

10725

10726

10727

10728

10729

10730

10731

10732

10733

10734

10735

10736

10737

10738

10739

10740

10741

10742

10743

10744

10745

10746

10747

10748

10749

10750

10751

10752

10753

10754

10755

10756

10757

10758

10759

10760

10761

10762

10763

10764

10765

10766

10767

10768

10769

10770

10771

10772

10773

10774

10775

10776

10777

10778

10779

10780

10781

10782

10783

10784

10785

10786

10787

10788

10789

10790

10791

10792

10793

10794

10795

10796

10797

10798

10799

10800

10801

10802

10803

10804

10805

10806

10807

10808

10809

10810

10811

10812

10813

10814

10815

10816

10817

10818

10819

10820

10821

10822

10823

10824

10825

10826

10827

10828

10829

10830

10831

10832

10833

10834

10835

10836

10837

10838

10839

10840

10841

10842

10843

10844

10845

10846

10847

10848

10849

10850

10851

10852

10853

10854

10855

10856

10857

10858

10859

10860

10861

10862

10863

10864

10865

10866

10867

10868

10869

10870

10871

10872

10873

10874

10875

10876

10877

10878

10879

10880

10881

10882

10883

10884

10885

10886

10887

10888

10889

10890

10891

10892

10893

10894

10895

10896

10897

10898

10899

10900

10901

10902

10903

10904

10905

10906

10907

10908

10909

10910

10911

10912

10913

10914

10915

10916

10917

10918

10919

10920

10921

10922

10923

10924

10925

10926

10927

10928

10929

10930

10931

10932

10933

10934

10935

10936

10937

10938

10939

10940

10941

10942

10943

10944

10945

10946

10947

10948

10949

10950

10951

10952

10953

10954

10955

10956

10957

10958

10959

10960

10961

10962

10963

10964

10965

10966

10967

10968

10969

10970

10971

10972

10973

10974

10975

10976

10977

10978

10979

10980

10981

10982

10983

10984

10985

10986

10987

10988

10989

10990

10991

10992

10993

10994

10995

10996

10997

10998

10999

11000

11001

11002

11003

11004

11005

11006

11007

11008

11009

11010

11011

11012

11013

11014

11015

11016

11017

11018

11019

11020

11021

11022

11023

11024

11025

11026

11027

11028

11029

11030

11031

11032

11033

11034

11035

11036

11037

11038

11039

11040

11041

11042

11043

11044

11045

11046

11047

11048

11049

11050

11051

11052

11053

11054

11055

11056

11057

11058

11059

11060

11061

11062

11063

11064

11065

11066

11067

11068

11069

11070

11071

11072

11073

11074

11075

11076

11077

11078

11079

11080

11081

11082

11083

11084

11085

11086

11087

11088

11089

11090

11091

11092

11093

11094

11095

11096

11097

11098

11099

11100

11101

11102

11103

11104

11105

11106

11107

11108

11109

11110

11111

11112

11113

11114

11115

11116

11117

11118

11119

11120

11121

11122

11123

11124

11125

11126

11127

11128

11129

11130

11131

11132

11133

11134

11135

11136

11137

11138

11139

11140

11141

11142

11143

11144

11145

11146

11147

11148

11149

11150

11151

11152

11153

11154

11155

11156

11157

11158

11159

11160

11161

11162

11163

11164

11165

11166

11167

11168

11169

11170

11171

11172

11173

11174

11175

11176

11177

11178

11179

11180

11181

11182

11183

11184

11185

11186

11187

11188

11189

11190

11191

11192

11193

11194

11195

11196

11197

11198

11199

11200

11201

11202

11203

11204

11205

11206

11207

11208

11209

11210

11211

11212

11213

11214

11215

11216

11217

11218

11219

11220

11221

11222

11223

11224

11225

11226

11227

11228

11229

11230

11231

11232

11233

11234

11235

11236

11237

11238

11239

11240

11241

11242

11243

11244

11245

11246

11247

11248

11249

11250

11251

11252

11253

11254

11255

11256

11257

11258

11259

11260

11261

11262

11263

11264

11265

11266

11267

11268

11269

11270

11271

11272

11273

11274

11275

11276

11277

11278

11279

11280

11281

11282

11283

11284

11285

11286

11287

11288

11289

11290

11291

11292

11293

11294

11295

11296

11297

11298

11299

11300

11301

11302

11303

11304

11305

11306

11307

11308

11309

11310

11311

11312

11313

11314

11315

11316

11317

11318

11319

11320

11321

11322

11323

11324

11325

11326

11327

11328

11329

11330

11331

11332

11333

11334

11335

11336

11337

11338

11339

11340

11341

11342

11343

11344

11345

11346

11347

11348

11349

11350

11351

11352

11353

11354

11355

11356

11357

11358

11359

# coding: utf-8 

""" 

Univariate Polynomial Base Class 

  

AUTHORS: 

  

- William Stein: first version. 

  

- Martin Albrecht: Added singular coercion. 

  

- Robert Bradshaw: Move Polynomial_generic_dense to Cython. 

  

- Miguel Marco: Implemented resultant in the case where PARI fails. 

  

- Simon King: Use a faster way of conversion from the base ring. 

  

- Julian Rueth (2012-05-25,2014-05-09): Fixed is_squarefree() for imperfect 

fields, fixed division without remainder over QQbar; added ``_cache_key`` 

for polynomials with unhashable coefficients 

  

- Simon King (2013-10): Implement copying of :class:`PolynomialBaseringInjection`. 

  

- Kiran Kedlaya (2016-03): Added root counting. 

  

- Edgar Costa (2017-07): Added rational reconstruction. 

  

- Kiran Kedlaya (2017-09): Added reciprocal transform, trace polynomial. 

  

- David Zureick-Brown (2017-09): Added is_weil_polynomial. 

  

TESTS:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^5 + 2*x^2 + (-1) 

sage: f == loads(dumps(f)) 

True 

  

sage: PolynomialRing(ZZ,'x').objgen() 

(Univariate Polynomial Ring in x over Integer Ring, x) 

""" 

  

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

# Copyright (C) 2007 William Stein <wstein@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 

from __future__ import print_function 

  

cdef is_FractionField, is_RealField, is_ComplexField 

cdef ZZ, QQ, RR, CC, RDF, CDF 

  

cimport cython 

from cpython.number cimport PyNumber_TrueDivide, PyNumber_Check 

  

import operator, copy, re 

  

from sage.cpython.wrapperdescr cimport wrapperdescr_fastcall 

import sage.rings.rational 

import sage.rings.integer 

from . import polynomial_ring 

import sage.rings.integer_ring 

import sage.rings.rational_field 

import sage.rings.finite_rings.integer_mod_ring 

import sage.rings.complex_field 

import sage.rings.fraction_field_element 

import sage.rings.infinity as infinity 

from sage.misc.sage_eval import sage_eval 

from sage.misc.abstract_method import abstract_method 

from sage.misc.latex import latex 

from sage.arith.power cimport generic_power 

from sage.arith.long cimport pyobject_to_long 

from sage.structure.factorization import Factorization 

from sage.structure.richcmp cimport (richcmp, richcmp_item, 

rich_to_bool, rich_to_bool_sgn) 

  

from sage.interfaces.singular import singular as singular_default, is_SingularElement 

from sage.libs.all import pari, pari_gen, PariError 

  

from sage.rings.real_mpfr import RealField, is_RealField, RR 

  

from sage.rings.complex_field import is_ComplexField, ComplexField 

CC = ComplexField() 

  

from sage.rings.real_double import is_RealDoubleField, RDF 

from sage.rings.complex_double import is_ComplexDoubleField, CDF 

from sage.rings.real_mpfi import is_RealIntervalField 

  

from sage.structure.element import coerce_binop 

from sage.structure.element cimport (parent, have_same_parent, 

Element, RingElement, coercion_model) 

  

from sage.rings.rational_field import QQ, is_RationalField 

from sage.rings.integer_ring import ZZ, is_IntegerRing 

from sage.rings.integer cimport Integer, smallInteger 

from sage.libs.gmp.mpz cimport * 

from sage.rings.fraction_field import is_FractionField 

from sage.rings.padics.generic_nodes import is_pAdicRing, is_pAdicField 

  

from sage.structure.category_object cimport normalize_names 

  

from sage.misc.derivative import multi_derivative 

  

from sage.arith.all import (sort_complex_numbers_for_display, 

power_mod, lcm, is_prime) 

  

from . import polynomial_fateman 

  

from sage.rings.ideal import is_Ideal 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

from sage.rings.polynomial.polynomial_ring import is_PolynomialRing 

from sage.rings.polynomial.multi_polynomial_ring import is_MPolynomialRing 

from sage.misc.cachefunc import cached_function 

  

from sage.categories.map cimport Map 

from sage.categories.morphism cimport Morphism 

  

from sage.misc.superseded import deprecation, deprecated_function_alias 

from sage.misc.cachefunc import cached_method 

  

cpdef is_Polynomial(f): 

""" 

Return True if f is of type univariate polynomial. 

  

INPUT: 

  

  

- ``f`` - an object 

  

  

EXAMPLES:: 

  

sage: from sage.rings.polynomial.polynomial_element import is_Polynomial 

sage: R.<x> = ZZ[] 

sage: is_Polynomial(x^3 + x + 1) 

True 

sage: S.<y> = R[] 

sage: f = y^3 + x*y -3*x; f 

y^3 + x*y - 3*x 

sage: is_Polynomial(f) 

True 

  

However this function does not return True for genuine multivariate 

polynomial type objects or symbolic polynomials, since those are 

not of the same data type as univariate polynomials:: 

  

sage: R.<x,y> = QQ[] 

sage: f = y^3 + x*y -3*x; f 

y^3 + x*y - 3*x 

sage: is_Polynomial(f) 

False 

sage: var('x,y') 

(x, y) 

sage: f = y^3 + x*y -3*x; f 

y^3 + x*y - 3*x 

sage: is_Polynomial(f) 

False 

""" 

return isinstance(f, Polynomial) 

  

from .polynomial_compiled cimport CompiledPolynomialFunction 

  

from .polydict import ETuple 

  

cdef object is_AlgebraicRealField 

cdef object is_AlgebraicField 

cdef object is_AlgebraicField_common 

cdef object NumberField_quadratic 

cdef object is_ComplexIntervalField 

  

cdef void late_import(): 

# A hack to avoid circular imports. 

global is_AlgebraicRealField 

global is_AlgebraicField 

global is_AlgebraicField_common 

global NumberField_quadratic 

global is_ComplexIntervalField 

  

if is_AlgebraicRealField is not None: 

return 

  

import sage.rings.qqbar 

is_AlgebraicRealField = sage.rings.qqbar.is_AlgebraicRealField 

is_AlgebraicField = sage.rings.qqbar.is_AlgebraicField 

is_AlgebraicField_common = sage.rings.qqbar.is_AlgebraicField_common 

import sage.rings.number_field.number_field 

NumberField_quadratic = sage.rings.number_field.number_field.NumberField_quadratic 

import sage.rings.complex_interval_field 

is_ComplexIntervalField = sage.rings.complex_interval_field.is_ComplexIntervalField 

  

  

cdef class Polynomial(CommutativeAlgebraElement): 

""" 

A polynomial. 

  

EXAMPLES:: 

  

sage: R.<y> = QQ['y'] 

sage: S.<x> = R['x'] 

sage: S 

Univariate Polynomial Ring in x over Univariate Polynomial Ring in y 

over Rational Field 

sage: f = x*y; f 

y*x 

sage: type(f) 

<type 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'> 

sage: p = (y+1)^10; p(1) 

1024 

  

.. automethod:: _add_ 

.. automethod:: _sub_ 

.. automethod:: _lmul_ 

.. automethod:: _rmul_ 

.. automethod:: _mul_ 

.. automethod:: _mul_trunc_ 

""" 

  

def __init__(self, parent, is_gen = False, construct=False): 

""" 

The following examples illustrate creation of elements of 

polynomial rings, and some basic arithmetic. 

  

First we make a polynomial over the integers and do some 

arithmetic:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^5 + 2*x^2 + (-1); f 

x^5 + 2*x^2 - 1 

sage: f^2 

x^10 + 4*x^7 - 2*x^5 + 4*x^4 - 4*x^2 + 1 

  

Next we do arithmetic in a sparse polynomial ring over the 

integers:: 

  

sage: R.<x> = ZZ[ ]; R 

Univariate Polynomial Ring in x over Integer Ring 

sage: S.<Z> = R[ ]; S 

Univariate Polynomial Ring in Z over Univariate Polynomial Ring in x over Integer Ring 

sage: f = Z^3 + (x^2-2*x+1)*Z - 3; f 

Z^3 + (x^2 - 2*x + 1)*Z - 3 

sage: f*f 

Z^6 + (2*x^2 - 4*x + 2)*Z^4 - 6*Z^3 + (x^4 - 4*x^3 + 6*x^2 - 4*x + 1)*Z^2 + (-6*x^2 + 12*x - 6)*Z + 9 

sage: f^3 == f*f*f 

True 

""" 

CommutativeAlgebraElement.__init__(self, parent) 

self._is_gen = is_gen 

  

cdef Polynomial _new_generic(self, list coeffs): 

r""" 

Quickly construct a new polynomial of the same type as ``self``, 

bypassing the parent's element constructor. 

  

The new polynomial takes ownership of the coefficient list 

given on input. 

""" 

cdef Py_ssize_t n = len(coeffs) - 1 

while n >= 0 and not coeffs[n]: 

del coeffs[n] 

n -= 1 

return type(self)(self._parent, coeffs, check=False) 

  

cpdef _add_(self, right): 

r""" 

Add two polynomials. 

  

EXAMPLES:: 

  

sage: R = ZZ['x'] 

sage: p = R([1,2,3,4]) 

sage: q = R([4,-3,2,-1]) 

sage: p + q # indirect doctest 

3*x^3 + 5*x^2 - x + 5 

""" 

cdef Py_ssize_t i, min 

cdef list x = self.list(copy=False) 

cdef list y = right.list(copy=False) 

  

if len(x) > len(y): 

min = len(y) 

high = x[min:] 

elif len(x) < len(y): 

min = len(x) 

high = y[min:] 

else: 

min = len(x) 

high = [] 

  

low = [x[i] + y[i] for i in range(min)] 

return self._new_generic(low + high) 

  

cpdef _neg_(self): 

return self._new_generic([-x for x in self.list(copy=False)]) 

  

cpdef bint is_zero(self): 

r""" 

Test whether this polynomial is zero. 

  

EXAMPLES:: 

  

sage: R = GF(2)['x']['y'] 

sage: R([0,1]).is_zero() 

False 

sage: R([0]).is_zero() 

True 

sage: R([-1]).is_zero() 

False 

""" 

return self.degree() < 0 

  

cpdef bint is_one(self): 

r""" 

Test whether this polynomial is 1. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: (x-3).is_one() 

False 

sage: R(1).is_one() 

True 

  

sage: R2.<y> = R[] 

sage: R2(x).is_one() 

False 

sage: R2(1).is_one() 

True 

sage: R2(-1).is_one() 

False 

""" 

return self.degree() == 0 and self.get_unsafe(0).is_one() 

  

def plot(self, xmin=None, xmax=None, *args, **kwds): 

""" 

Return a plot of this polynomial. 

  

INPUT: 

  

  

- ``xmin`` - float 

  

- ``xmax`` - float 

  

- ``*args, **kwds`` - passed to either plot or 

point 

  

  

OUTPUT: returns a graphic object. 

  

EXAMPLES:: 

  

sage: x = polygen(GF(389)) 

sage: plot(x^2 + 1, rgbcolor=(0,0,1)) 

Graphics object consisting of 1 graphics primitive 

sage: x = polygen(QQ) 

sage: plot(x^2 + 1, rgbcolor=(1,0,0)) 

Graphics object consisting of 1 graphics primitive 

""" 

R = self.base_ring() 

from sage.plot.all import plot, point, line 

if R.characteristic() == 0: 

if xmin is None and xmax is None: 

(xmin, xmax) = (-1,1) 

elif xmin is None or xmax is None: 

raise AttributeError("must give both plot endpoints") 

return plot(self.__call__, (xmin, xmax), *args, **kwds) 

else: 

if R.is_finite(): 

v = list(R) 

v.sort() 

w = dict([(v[i],i) for i in range(len(v))]) 

z = [(i, w[self(v[i])]) for i in range(len(v))] 

return point(z, *args, **kwds) 

raise NotImplementedError("plotting of polynomials over %s not implemented"%R) 

  

cpdef _lmul_(self, Element left): 

""" 

Multiply self on the left by a scalar. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = (x^3 + x + 5) 

sage: f._lmul_(7) 

7*x^3 + 7*x + 35 

sage: 7*f 

7*x^3 + 7*x + 35 

""" 

# todo -- should multiply individual coefficients?? 

# that could be in derived class. 

# Note that we are guaranteed that right is in the base ring, so this could be fast. 

if not left: 

return self._parent.zero() 

return self._parent(left) * self 

  

cpdef _rmul_(self, Element right): 

""" 

Multiply self on the right by a scalar. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = (x^3 + x + 5) 

sage: f._rmul_(7) 

7*x^3 + 7*x + 35 

sage: f*7 

7*x^3 + 7*x + 35 

""" 

# todo -- Should multiply individual coefficients?? 

# that could be in derived class. 

# Note that we are guaranteed that right is in the base ring, so this could be fast. 

if not right: 

return self._parent.zero() 

return self * self._parent(right) 

  

def subs(self, *x, **kwds): 

r""" 

Identical to self(\*x). 

  

See the docstring for ``self.__call__``. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x^3 + x - 3 

sage: f.subs(x=5) 

127 

sage: f.subs(5) 

127 

sage: f.subs({x:2}) 

7 

sage: f.subs({}) 

x^3 + x - 3 

sage: f.subs({'x':2}) 

Traceback (most recent call last): 

... 

TypeError: keys do not match self's parent 

""" 

if len(x) == 1 and isinstance(x[0], dict): 

g = self._parent.gen() 

if g in x[0]: 

return self(x[0][g]) 

elif len(x[0]) > 0: 

raise TypeError("keys do not match self's parent") 

return self 

return self(*x, **kwds) 

substitute = subs 

  

@cython.boundscheck(False) 

@cython.wraparound(False) 

def __call__(self, *args, **kwds): 

""" 

Evaluate this polynomial. 

  

INPUT: 

  

- ``*args`` -- ring elements, need not be in the coefficient ring of 

the polynomial. The **first** positional argument is substituted 

for the polynomial's indeterminate. Remaining arguments, if any, 

are used **from left to right** to evaluate the coefficients. 

- ``**kwds`` -- variable name-value pairs. 

  

OUTPUT: 

  

The value of the polynomial at the point specified by the arguments. 

  

ALGORITHM: 

  

By default, use Horner's method or create a 

:class:`~sage.rings.polynomial.polynomial_compiled.CompiledPolynomialFunction` 

depending on the polynomial's degree. 

  

Element classes may define a method called ``_evaluate_polynomial`` 

to provide an alternative evaluation algorithm for a given argument 

type. Note that ``_evaluated_polynomial`` may not always be used: 

for instance, subclasses dedicated to specific coefficient rings 

typically do not call it. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x/2 - 5 

sage: f(3) 

-7/2 

sage: R.<x> = ZZ[] 

sage: f = (x-1)^5 

sage: f(2/3) 

-1/243 

  

We evaluate a polynomial over a quaternion algebra:: 

  

sage: A.<i,j,k> = QuaternionAlgebra(QQ, -1,-1) 

sage: R.<w> = PolynomialRing(A,sparse=True) 

sage: f = i*j*w^5 - 13*i*w^2 + (i+j)*w + i 

sage: f(i+j+1) 

24 + 26*i - 10*j - 25*k 

sage: w = i+j+1; i*j*w^5 - 13*i*w^2 + (i+j)*w + i 

24 + 26*i - 10*j - 25*k 

  

The parent ring of the answer always "starts" with the parent of 

the object at which we are evaluating. Thus, e.g., if we input a 

matrix, we are guaranteed to get a matrix out, though the base ring 

of that matrix may change depending on the base of the polynomial 

ring. :: 

  

sage: R.<x> = QQ[] 

sage: f = R(2/3) 

sage: a = matrix(ZZ,2) 

sage: b = f(a); b 

[2/3 0] 

[ 0 2/3] 

sage: b.parent() 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

sage: f = R(1) 

sage: b = f(a); b 

[1 0] 

[0 1] 

sage: b.parent() 

Full MatrixSpace of 2 by 2 dense matrices over Rational Field 

  

:: 

  

sage: R.<w> = GF(17)[] 

sage: f = w^3 + 3*w +2 

sage: f(5) 

6 

sage: f(w=5) 

6 

sage: f(x=10) # x isn't mentioned 

w^3 + 3*w + 2 

  

Nested polynomial ring elements can be called like multivariate 

polynomials. Note the order of the arguments:: 

  

sage: R.<x> = QQ[]; S.<y> = R[] 

sage: f = x+y*x+y^2 

sage: f.parent() 

Univariate Polynomial Ring in y over Univariate Polynomial Ring in x over Rational Field 

sage: f(2) 

3*x + 4 

sage: f(2,4) 

16 

sage: f(y=2,x=4) 

16 

sage: f(2,x=4) 

16 

sage: f(2,x=4,z=5) 

16 

sage: f(2,4, z=10) 

16 

sage: f(y=x) 

2*x^2 + x 

sage: f(x=y) 

2*y^2 + y 

  

Also observe that ``f(y0, x0)`` means ``f(x=x0)(y=y0)``, not 

``f(y=y0)(x=x0)``. The two expressions may take different values:: 

  

sage: f(y, x) 

y^2 + x*y + x 

sage: f(y)(x) 

2*x^2 + x 

  

Polynomial ring elements can also, like multivariate 

polynomials, be called with an argument that is a list or 

tuple containing the values to be substituted, though it is 

perhaps more natural to just unpack the list:: 

  

sage: f([2]) # calling with a list 

3*x + 4 

sage: f((2,)) # calling with a tuple 

3*x + 4 

sage: f(*[2]) # unpacking the list to call normally 

3*x + 4 

  

The following results in an element of the symbolic ring. :: 

  

sage: f(x=sqrt(2)) 

y^2 + sqrt(2)*y + sqrt(2) 

  

:: 

  

sage: R.<t> = PowerSeriesRing(QQ, 't'); S.<x> = R[] 

sage: f = 1 + x*t^2 + 3*x*t^4 

sage: f(2) 

1 + 2*t^2 + 6*t^4 

sage: f(2, 1/2) 

15/8 

  

Some special cases are optimized. :: 

  

sage: R.<x> = PolynomialRing(QQ, sparse=True) 

sage: f = x^3-2*x 

sage: f(x) is f 

True 

sage: f(1/x) 

(-2*x^2 + 1)/x^3 

  

sage: f = x^100 + 3 

sage: f(0) 

3 

sage: parent(f(0)) 

Rational Field 

sage: parent(f(Qp(5)(0))) 

5-adic Field with capped relative precision 20 

  

TESTS: 

  

The following shows that :trac:`2360` is indeed fixed. :: 

  

sage: R.<x,y> = ZZ[] 

sage: P.<a> = ZZ[] 

sage: e = [x^2,y^3] 

sage: f = 6*a^4 

sage: f(x) 

6*x^4 

sage: f(e) 

Traceback (most recent call last): 

... 

TypeError: Wrong number of arguments 

sage: f(x) 

6*x^4 

  

The following shows that :trac:`9006` is also fixed. :: 

  

sage: f = ZZ['x'](1000000 * [1]) 

sage: f(1) 

1000000 

  

The following test came up in :trac:`9051`:: 

  

sage: Cif = ComplexIntervalField(64) 

sage: R.<x> = Cif[] 

sage: f = 2*x-1 

sage: jj = Cif(RIF(0,2)) 

sage: f(jj).center(), f(jj).diameter() 

(1.00000000000000000, 4.00000000000000000) 

  

The following failed before the patch to :trac:`3979` 

  

:: 

  

sage: R.<x> = ZZ[] 

sage: S.<y> = R[] 

sage: g = x*y + 1 

sage: g(x=3) 

3*y + 1 

  

:: 

  

sage: Pol_x.<x> = QQ[] 

sage: Pol_xy.<y> = Pol_x[] 

sage: pol = 1000*x^2*y^2 + 100*y + 10*x + 1 

  

sage: pol(y, 0) 

100*y + 1 

  

sage: pol(~y, 0) 

(y + 100)/y 

  

sage: pol(y=x, x=1) 

1000*x^2 + 100*x + 11 

  

sage: zero = Pol_xy(0) 

sage: zero(1).parent() 

Univariate Polynomial Ring in x over Rational Field 

  

sage: zero = QQ['x'](0) 

sage: a = matrix(ZZ, [[1]]) 

sage: zero(a).parent() 

Full MatrixSpace of 1 by 1 dense matrices over Rational Field 

  

sage: pol(y, x).parent() is pol(x, y).parent() is pol(y, y).parent() is Pol_xy 

True 

  

sage: pol(x, x).parent() 

Univariate Polynomial Ring in x over Rational Field 

  

sage: one = Pol_xy(1) 

sage: one(1, 1.).parent() 

Real Field with 53 bits of precision 

  

sage: zero = GF(2)['x'](0) 

sage: zero(1.).parent() # should raise an error 

Traceback (most recent call last): 

... 

TypeError: no common canonical parent for objects with parents: 

'Finite Field of size 2' and 'Real Field with 53 bits of precision' 

  

sage: pol(x, y, x=1) 

Traceback (most recent call last): 

... 

TypeError: Wrong number of arguments 

  

Check that :trac:`22317` is fixed:: 

  

sage: R = ZZ['x']['y']['z'] 

sage: d = R.gens_dict_recursive() 

sage: p = d['x'] * d['z'] 

sage: p(x=QQ(0)) 

0 

  

AUTHORS: 

  

- David Joyner (2005-04-10) 

  

- William Stein (2006-01-22): change so parent is determined by the 

arithmetic 

  

- William Stein (2007-03-24): fix parent being determined in the 

constant case! 

  

- Robert Bradshaw (2007-04-09): add support for nested calling 

  

- Tom Boothby (2007-05-01): evaluation done by 

CompiledPolynomialFunction 

  

- William Stein (2007-06-03): add support for keyword arguments. 

  

- Francis Clarke (2012-08-26): fix keyword substitution in the 

leading coefficient. 

""" 

cdef long i 

cdef Polynomial pol = self 

cdef long d 

  

cst = self._parent._base.zero() if self.degree() < 0 else self.get_unsafe(0) 

a = args[0] if len(args) == 1 else None 

if kwds or not (isinstance(a, Element) or PyNumber_Check(a)): 

# slow path 

  

# Isolate the variable we are interested in, check remaining 

# arguments 

  

a = kwds.pop(self.variable_name(), None) 

if args: 

if a is not None: 

raise TypeError("unsupported mix of keyword and positional arguments") 

if isinstance(args[0], (list, tuple)): 

if len(args) > 1: 

raise TypeError("invalid arguments") 

args = args[0] 

a, args = args[0], args[1:] 

if a is None: 

a = self._parent.gen() 

  

eval_coeffs = False 

if args or kwds: 

try: 

# Note that we may be calling a different implementation that 

# is more permissive about its arguments than we are. 

cst = cst(*args, **kwds) 

eval_coeffs = True 

except TypeError: 

if args: # bwd compat: nonsense *keyword* arguments are okay 

raise TypeError("Wrong number of arguments") 

  

# Evaluate the coefficients, then fall through to evaluate the 

# resulting univariate polynomial 

  

if eval_coeffs: 

pol = pol.map_coefficients(lambda c: c(*args, **kwds), 

new_base_ring=cst.parent()) 

  

# Coerce a once and for all to a parent containing the coefficients. 

# This can save lots of coercions when the common parent is the 

# polynomial's base ring (e.g., for evaluations at integers). 

  

if not type(a) is type(cst): 

cst, aa = coercion_model.canonical_coercion(cst, a) 

tgt = parent(cst) 

# Use fast right multiplication actions like matrix × scalar 

if (isinstance(tgt, type) 

or (<Parent> tgt).get_action(parent(a), operator.mul) is None): 

a = aa 

  

d = pol.degree() 

  

if d <= 0 or (isinstance(a, Element) 

and a.parent().is_exact() and a.is_zero()): 

return cst # with the right parent thanks to the above coercion 

elif parent(a) is pol._parent and a.is_gen(): 

return pol 

elif hasattr(a, "_evaluate_polynomial"): 

try: 

return a._evaluate_polynomial(pol) 

except NotImplementedError: 

pass 

  

if pol._compiled is None: 

if d < 4 or d > 50000: 

result = pol.get_unsafe(d) 

for i in xrange(d - 1, -1, -1): 

result = result * a + pol.get_unsafe(i) 

return result 

pol._compiled = CompiledPolynomialFunction(pol.list()) 

return pol._compiled.eval(a) 

  

def compose_trunc(self, Polynomial other, long n): 

r""" 

Return the composition of ``self`` and ``other``, truncated to `O(x^n)`. 

  

This method currently works for some specific coefficient rings only. 

  

EXAMPLES:: 

  

sage: Pol.<x> = CBF[] 

sage: (1 + x + x^2/2 + x^3/6 + x^4/24 + x^5/120).compose_trunc(1 + x, 2) 

([2.708333333333333 +/- 6.64e-16])*x + [2.71666666666667 +/- 4.29e-15] 

  

sage: Pol.<x> = QQ['y'][] 

sage: (1 + x + x^2/2 + x^3/6 + x^4/24 + x^5/120).compose_trunc(1 + x, 2) 

Traceback (most recent call last): 

... 

NotImplementedError: truncated composition is not implemented for this subclass of polynomials 

""" 

raise NotImplementedError("truncated composition is not implemented " 

"for this subclass of polynomials") 

  

def _compile(self): 

# For testing 

self._compiled = CompiledPolynomialFunction(self.list()) 

return self._compiled 

  

def _get_compiled(self): 

# For testing 

return self._compiled 

  

def _fast_float_(self, *vars): 

""" 

Returns a quickly-evaluating function on floats. 

  

EXAMPLES:: 

  

sage: R.<t> = QQ[] 

sage: f = t^3-t 

sage: ff = f._fast_float_() 

sage: ff(10) 

990.0 

  

Horner's method is used:: 

  

sage: f = (t+10)^3; f 

t^3 + 30*t^2 + 300*t + 1000 

sage: list(f._fast_float_()) 

['load 0', 'push 30.0', 'add', 'load 0', 'mul', 'push 300.0', 'add', 'load 0', 'mul', 'push 1000.0', 'add'] 

  

TESTS:: 

  

sage: f = t + 2 - t 

sage: ff = f._fast_float_() 

sage: ff(3) 

2.0 

sage: list(f._fast_float_()) 

['push 2.0'] 

  

sage: f = t - t 

sage: ff = f._fast_float_() 

sage: ff(3) 

0.0 

sage: list(f._fast_float_()) 

['push 0.0'] 

""" 

from sage.ext.fast_eval import fast_float_arg, fast_float_constant 

var = self._parent._names[0] 

if len(vars) == 0: 

x = fast_float_arg(0) 

elif var in vars: 

x = fast_float_arg(list(vars).index(var)) 

else: 

raise ValueError("free variable: %s" % var) 

cdef int i, d = self.degree() 

expr = x 

coeff = self[d] 

if d <= 0: 

return fast_float_constant(coeff) 

if coeff != 1: 

expr *= fast_float_constant(coeff) 

for i from d > i >= 0: 

coeff = self.get_unsafe(i) 

if coeff: 

expr += fast_float_constant(coeff) 

if i > 0: 

expr *= x 

return expr 

  

def _fast_callable_(self, etb): 

r""" 

Given an ExpressionTreeBuilder, return an Expression representing 

this value. 

  

EXAMPLES:: 

  

sage: from sage.ext.fast_callable import ExpressionTreeBuilder 

sage: etb = ExpressionTreeBuilder(vars=['t']) 

sage: R.<t> = QQ[] 

sage: v = R.random_element(6); v 

-t^6 - 12*t^5 + 1/2*t^4 - 1/95*t^3 - 1/2*t^2 - 4 

sage: v._fast_callable_(etb) 

add(mul(mul(add(mul(add(mul(add(mul(add(mul(v_0, -1), -12), v_0), 1/2), v_0), -1/95), v_0), -1/2), v_0), v_0), -4) 

  

TESTS:: 

  

sage: R(2)._fast_callable_(etb) 

2 

sage: R(0)._fast_callable_(etb) 

0 

sage: fast_callable(R(2))(3) 

2 

""" 

x = etb.var(self.variable_name()) 

expr = x 

cdef int i, d = self.degree() 

coeff = self[d] 

# We handle polynomial rings like QQ['x']['y']; that gives us some 

# slowdown. Optimize away some of that: 

if len(etb._vars) == 1: 

# OK, we're in the (very common) univariate case. 

coeff_maker = etb.constant 

else: 

# There may be variables in our coefficients... 

coeff_maker = etb.make 

if d <= 0: 

return coeff_maker(coeff) 

if coeff != 1: 

expr *= coeff_maker(coeff) 

for i from d > i >= 0: 

coeff = self.get_unsafe(i) 

if coeff: 

expr += coeff_maker(coeff) 

if i > 0: 

expr *= x 

return expr 

  

cpdef _richcmp_(self, other, int op): 

""" 

Compare the two polynomials self and other. 

  

We order polynomials first by degree (but treating 0 as having 

degree 0), then in dictionary order starting with the 

coefficient of largest degree. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ['x'] 

sage: 3*x^3 + 5 > 10*x^2 + 19 

True 

sage: x^2 - 2*x - 1 < x^2 - 1 

True 

sage: x^2 - 2*x - 1 > x^2 - 1 

False 

sage: x^3 - 3 > 393939393 

True 

  

Test comparison with zero (:trac:`18633`):: 

  

sage: 0 < R(1) 

True 

sage: R(-1) < 0 

True 

sage: -x < 0 

False 

sage: R(0) == R(0) 

True 

  

TESTS:: 

  

Test that comparisons are consistent when using interval 

coefficients:: 

  

sage: R.<x> = RIF[] 

sage: a = RIF(0,1) * x 

sage: b = RIF(1,2) * x 

sage: a == a 

False 

sage: a != a 

False 

sage: a == b 

False 

sage: a < b 

False 

sage: a > b 

False 

sage: a <= b 

True 

sage: a >= b 

False 

sage: a != b 

False 

  

sage: R.<x> = RBF[] 

sage: pol = RBF(1.0, 0.1) 

sage: pol == pol 

False 

""" 

cdef Polynomial pol = <Polynomial?>other 

  

cdef Py_ssize_t d1 = self.degree() 

cdef Py_ssize_t d2 = pol.degree() 

  

# Special case constant polynomials 

if d1 <= 0 and d2 <= 0: 

return richcmp(self[0], pol[0], op) 

  

# For different degrees, compare the degree 

if d1 != d2: 

return rich_to_bool_sgn(op, d1 - d2) 

  

cdef Py_ssize_t i 

for i in reversed(range(d1+1)): 

x = self.get_unsafe(i) 

y = pol.get_unsafe(i) 

res = richcmp_item(x, y, op) 

if res is not NotImplemented: 

return res 

return rich_to_bool(op, 0) 

  

def __nonzero__(self): 

""" 

EXAMPLES:: 

  

sage: P = PolynomialRing(ZZ,'x')(0) 

sage: bool(P) 

False 

sage: P = PolynomialRing(ZZ, 'x')([1,2,3]) 

sage: bool(P) 

True 

""" 

return self.degree() >= 0 

  

def __getitem__(self, n): 

r""" 

Return the `n`-th coefficient of ``self``. 

  

.. WARNING:: 

  

If `P` is a polynomial of degree `d`, then ``P[i]`` 

returns `0` when `i < 0` or `i > d`. This behaviour 

intentionally differs from that of lists: if `L` is a list 

of length `n`, then Python defines ``L[-i] = L[n - i]`` 

for `0 < i \le n``. The definition used here is more 

meaningful for polynomials, since it can be extended 

immediately to Laurent series, for example. 

  

EXAMPLES: 

  

We illustrate the difference between polynomials and lists 

when negative indices are involved:: 

  

sage: R.<x> = QQ[] 

sage: f = x + 2 

sage: f[-1] 

0 

sage: list(f)[-1] 

1 

  

Slices can be used to truncate polynomials:: 

  

sage: pol = R(range(8)); pol 

7*x^7 + 6*x^6 + 5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x 

sage: pol[:6] 

5*x^5 + 4*x^4 + 3*x^3 + 2*x^2 + x 

  

Any other kind of slicing is deprecated or an error, see 

:trac:`18940`:: 

  

sage: f[1:3] 

doctest:...: DeprecationWarning: polynomial slicing with a start index is deprecated, use list() and slice the resulting list instead 

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

x 

sage: f[1:3:2] 

Traceback (most recent call last): 

... 

NotImplementedError: polynomial slicing with a step is not defined 

""" 

cdef Py_ssize_t d = self.degree() + 1 

if isinstance(n, slice): 

start, stop, step = n.start, n.stop, n.step 

if step is not None: 

raise NotImplementedError("polynomial slicing with a step is not defined") 

if start is None: 

start = 0 

else: 

if start < 0: 

start = 0 

from sage.misc.superseded import deprecation 

deprecation(18940, "polynomial slicing with a start index is deprecated, use list() and slice the resulting list instead") 

if stop is None or stop > d: 

stop = d 

values = ([self.base_ring().zero()] * start 

+ [self.get_unsafe(i) for i in xrange(start, stop)]) 

return self._new_generic(values) 

  

cdef long k = pyobject_to_long(n) 

if k < 0 or k >= d: 

return self.base_ring().zero() 

return self.get_unsafe(k) 

  

cdef get_unsafe(self, Py_ssize_t i): 

""" 

Return the `i`-th coefficient of ``self``. 

  

Used as building block for a generic :meth:`__getitem__`. Should be 

overridden by Cython subclasses. The default implementation makes it 

possible to implement concrete subclasses in Python. 

""" 

return self[i] 

  

def __iter__(self): 

""" 

EXAMPLES:: 

  

sage: P = PolynomialRing(ZZ, 'x')([1,2,3]) 

sage: [y for y in iter(P)] 

[1, 2, 3] 

""" 

return iter(self.list(copy=False)) 

  

def _cache_key(self): 

""" 

Return a hashable key which identifies this element. 

  

EXAMPLES:: 

  

sage: K.<u> = Qq(4) 

sage: R.<x> = K[] 

sage: f = x 

sage: hash(f) 

Traceback (most recent call last): 

... 

TypeError: unhashable type: 'sage.rings.padics.qadic_flint_CR.qAdicCappedRelativeElement' 

sage: f._cache_key() 

(Univariate Polynomial Ring in x over Unramified Extension in u defined by x^2 + x + 1 with capped relative precision 20 over 2-adic Field, 

0, 

1 + O(2^20)) 

sage: @cached_function 

....: def foo(t): return t 

....: 

sage: foo(x) 

(1 + O(2^20))*x 

""" 

return (self._parent,) + tuple(self) 

  

def __hash__(self): 

return self._hash_c() 

  

cdef long _hash_c(self) except -1: 

""" 

This hash incorporates the variable name in an effort to respect 

the obvious inclusions into multi-variable polynomial rings. 

  

The tuple algorithm is borrowed from 

http://effbot.org/zone/python-hash.htm. 

  

EXAMPLES:: 

  

sage: R.<x>=ZZ[] 

sage: hash(R(1))==hash(1) # respect inclusions of the integers 

True 

sage: hash(R.0)==hash(FractionField(R).0) # respect inclusions into the fraction field 

True 

sage: R.<x>=QQ[] 

sage: hash(R(1/2))==hash(1/2) # respect inclusions of the rationals 

True 

sage: hash(R.0)==hash(FractionField(R).0) # respect inclusions into the fraction field 

True 

sage: R.<x>=IntegerModRing(11)[] 

sage: hash(R.0)==hash(FractionField(R).0) # respect inclusions into the fraction field 

True 

  

TESTS: 

  

Verify that :trac:`16251` has been resolved, i.e., polynomials with 

unhashable coefficients are unhashable:: 

  

sage: K.<a> = Qq(9) 

sage: R.<t> = K[] 

sage: hash(t) 

Traceback (most recent call last): 

... 

TypeError: unhashable type: 'sage.rings.padics.qadic_flint_CR.qAdicCappedRelativeElement' 

  

""" 

cdef long result = 0 # store it in a c-int and just let the overflowing additions wrap 

cdef long result_mon 

cdef long c_hash 

cdef long var_name_hash 

cdef int i 

for i from 0<= i <= self.degree(): 

if i == 1: 

# we delay the hashing until now to not waste it on a constant poly 

var_name_hash = hash(self._parent._names[0]) 

# I'm assuming (incorrectly) that hashes of zero indicate that the element is 0. 

# This assumption is not true, but I think it is true enough for the purposes and it 

# it allows us to write fast code that omits terms with 0 coefficients. This is 

# important if we want to maintain the '==' relationship with sparse polys. 

c_hash = hash(self[i]) 

if c_hash != 0: 

if i == 0: 

result += c_hash 

else: 

# Hash (self[i], generator, i) as a tuple according to the algorithm. 

result_mon = c_hash 

result_mon = (1000003 * result_mon) ^ var_name_hash 

result_mon = (1000003 * result_mon) ^ i 

result += result_mon 

if result == -1: 

return -2 

return result 

  

def __float__(self): 

""" 

EXAMPLES:: 

  

sage: P = PolynomialRing(ZZ, 'x')([1]) 

sage: float(P) 

1.0 

""" 

if self.degree() > 0: 

raise TypeError("cannot coerce nonconstant polynomial to float") 

return float(self[0]) 

  

def __int__(self): 

""" 

EXAMPLES:: 

  

sage: P = PolynomialRing(ZZ, 'x')([3]) 

sage: int(P) 

3 

""" 

if self.degree() > 0: 

raise TypeError("cannot coerce nonconstant polynomial to int") 

return int(self[0]) 

  

def _im_gens_(self, codomain, im_gens): 

""" 

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: H = Hom(R, QQ); H 

Set of Homomorphisms from Univariate Polynomial Ring in x over Integer Ring to Rational Field 

sage: f = H([5]); f 

Ring morphism: 

From: Univariate Polynomial Ring in x over Integer Ring 

To: Rational Field 

Defn: x |--> 5 

sage: f(x) 

5 

sage: f(x^2 + 3) 

28 

""" 

a = im_gens[0] 

P = a.parent() 

d = self.degree() 

result = P._coerce_(self[d]) 

i = d - 1 

while i >= 0: 

result = result * a + P._coerce_(self.get_unsafe(i)) 

i -= 1 

return result 

  

def _integer_(self, ZZ): 

r""" 

EXAMPLES:: 

  

sage: k = GF(47) 

sage: R.<x> = PolynomialRing(k) 

sage: ZZ(R(45)) 

45 

sage: ZZ(3*x + 45) 

Traceback (most recent call last): 

... 

TypeError: cannot coerce nonconstant polynomial 

""" 

if self.degree() > 0: 

raise TypeError("cannot coerce nonconstant polynomial") 

return ZZ(self[0]) 

  

def _rational_(self): 

r""" 

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: QQ(R(45/4)) 

45/4 

sage: QQ(3*x + 45) 

Traceback (most recent call last): 

... 

TypeError: not a constant polynomial 

""" 

if self.degree() > 0: 

raise TypeError("not a constant polynomial") 

return sage.rings.rational.Rational(self[0]) 

  

def _symbolic_(self, R): 

""" 

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x^3 + x 

sage: g = f._symbolic_(SR); g 

x^3 + x 

sage: g(x=2) 

10 

  

sage: g = SR(f) 

sage: g(x=2) 

10 

  

The polynomial has to be over a field of characteristic 0 (see 

:trac:`24072`):: 

  

sage: R.<w> = GF(7)[] 

sage: f = SR(2*w^3 + 1); f 

Traceback (most recent call last): 

... 

TypeError: positive characteristic not allowed in symbolic computations 

""" 

d = dict([(repr(g), R.var(g)) for g in self._parent.gens()]) 

return self.subs(**d) 

  

def __invert__(self): 

""" 

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x - 90283 

sage: f.__invert__() 

1/(x - 90283) 

sage: ~f 

1/(x - 90283) 

""" 

return self.parent().one() / self 

  

def inverse_of_unit(self): 

""" 

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x - 90283 

sage: f.inverse_of_unit() 

Traceback (most recent call last): 

... 

ValueError: self is not a unit 

sage: f = R(-90283); g = f.inverse_of_unit(); g 

-1/90283 

sage: parent(g) 

Univariate Polynomial Ring in x over Rational Field 

""" 

if self.degree() > 0: 

if not self.is_unit(): 

raise ValueError("self is not a unit") 

else: 

raise NotImplementedError("polynomial inversion over non-integral domains not implemented") 

return self._parent(~(self[0])) 

  

def inverse_mod(a, m): 

""" 

Inverts the polynomial a with respect to m, or raises a ValueError 

if no such inverse exists. The parameter m may be either a single 

polynomial or an ideal (for consistency with inverse_mod in other 

rings). 

  

.. SEEALSO:: 

  

If you are only interested in the inverse modulo a monomial `x^k` 

then you might use the specialized method 

:meth:`inverse_series_trunc` which is much faster. 

  

EXAMPLES:: 

  

sage: S.<t> = QQ[] 

sage: f = inverse_mod(t^2 + 1, t^3 + 1); f 

-1/2*t^2 - 1/2*t + 1/2 

sage: f * (t^2 + 1) % (t^3 + 1) 

1 

sage: f = t.inverse_mod((t+1)^7); f 

-t^6 - 7*t^5 - 21*t^4 - 35*t^3 - 35*t^2 - 21*t - 7 

sage: (f * t) + (t+1)^7 

1 

sage: t.inverse_mod(S.ideal((t + 1)^7)) == f 

True 

  

This also works over inexact rings, but note that due to rounding 

error the product may not always exactly equal the constant 

polynomial 1 and have extra terms with coefficients close to zero. :: 

  

sage: R.<x> = RDF[] 

sage: epsilon = RDF(1).ulp()*50 # Allow an error of up to 50 ulp 

sage: f = inverse_mod(x^2 + 1, x^5 + x + 1); f # abs tol 1e-14 

0.4*x^4 - 0.2*x^3 - 0.4*x^2 + 0.2*x + 0.8 

sage: poly = f * (x^2 + 1) % (x^5 + x + 1) 

sage: # Remove noisy zero terms: 

sage: parent(poly)([ 0.0 if abs(c)<=epsilon else c for c in poly.coefficients(sparse=False) ]) 

1.0 

sage: f = inverse_mod(x^3 - x + 1, x - 2); f 

0.14285714285714285 

sage: f * (x^3 - x + 1) % (x - 2) 

1.0 

sage: g = 5*x^3+x-7; m = x^4-12*x+13; f = inverse_mod(g, m); f 

-0.0319636125...*x^3 - 0.0383269759...*x^2 - 0.0463050900...*x + 0.346479687... 

sage: poly = f*g % m 

sage: # Remove noisy zero terms: 

sage: parent(poly)([ 0.0 if abs(c)<=epsilon else c for c in poly.coefficients(sparse=False) ]) # abs tol 1e-14 

1.0000000000000004 

  

ALGORITHM: Solve the system as + mt = 1, returning s as the inverse 

of a mod m. 

  

Uses the Euclidean algorithm for exact rings, and solves a linear 

system for the coefficients of s and t for inexact rings (as the 

Euclidean algorithm may not converge in that case). 

  

AUTHORS: 

  

- Robert Bradshaw (2007-05-31) 

""" 

from sage.rings.ideal import is_Ideal 

if is_Ideal(m): 

v = m.gens_reduced() 

if len(v) > 1: 

raise NotImplementedError("Don't know how to invert modulo non-principal ideal %s" % m) 

m = v[0] 

if m.degree() == 1 and m[1].is_unit(): 

# a(x) mod (x-r) = a(r) 

r = -m[0] 

if not m[1].is_one(): 

r *= m.base_ring()(~m[1]) 

u = a(r) 

if u.is_unit(): 

return a.parent()(~u) 

if a.parent().is_exact(): 

# use xgcd 

g, s, _ = a.xgcd(m) 

if g == 1: 

return s 

elif g.is_unit(): 

return g.inverse_of_unit() * s 

else: 

raise ValueError("Impossible inverse modulo") 

else: 

# xgcd may not converge for inexact rings. 

# Instead solve for the coefficients of 

# s (degree n-1) and t (degree n-2) in 

# as + mt = 1 

# as a linear system. 

from sage.matrix.constructor import matrix 

from sage.modules.free_module_element import vector 

a %= m 

n = m.degree() 

R = a.parent().base_ring() 

M = matrix(R, 2*n-1) 

# a_i s_j x^{i+j} terms 

for i in range(n): 

for j in range(n): 

M[i+j, j] = a[i] 

# m_i t_j x^{i+j} terms 

for i in range(n+1): 

for j in range(n-1): 

M[i+j, j+n] = m[i] 

v = vector(R, [R.one()] + [R.zero()]*(2*n-2)) # the constant polynomial 1 

if M.is_invertible(): 

x = M.solve_right(v) # there has to be a better way to solve 

return a.parent()(list(x)[0:n]) 

else: 

raise ValueError("Impossible inverse modulo") 

  

cpdef Polynomial inverse_series_trunc(self, long prec): 

r""" 

Return a polynomial approximation of precision ``prec`` of the inverse 

series of this polynomial. 

  

.. SEEALSO:: 

  

The method :meth:`inverse_mod` allows more generally to invert this 

polynomial with respect to any ideal. 

  

EXAMPLES:: 

  

sage: x = polygen(ZZ) 

sage: s = (1+x).inverse_series_trunc(5) 

sage: s 

x^4 - x^3 + x^2 - x + 1 

sage: s * (1+x) 

x^5 + 1 

  

Note that the constant coefficient needs to be a unit:: 

  

sage: ZZx.<x> = ZZ[] 

sage: ZZxy.<y> = ZZx[] 

sage: (1+x + y**2).inverse_series_trunc(4) 

Traceback (most recent call last): 

... 

ValueError: constant term x + 1 is not a unit 

sage: (1+x + y**2).change_ring(ZZx.fraction_field()).inverse_series_trunc(4) 

(-1/(x^2 + 2*x + 1))*y^2 + 1/(x + 1) 

  

The method works over any polynomial ring:: 

  

sage: R = Zmod(4) 

sage: Rx.<x> = R[] 

sage: Rxy.<y> = Rx[] 

  

sage: p = 1 + (1+2*x)*y + x**2*y**4 

sage: q = p.inverse_series_trunc(10) 

sage: (p*q).truncate(11) 

(2*x^4 + 3*x^2 + 3)*y^10 + 1 

  

Even noncommutative ones:: 

  

sage: M = MatrixSpace(ZZ,2) 

sage: x = polygen(M) 

sage: p = M([1,2,3,4])*x^3 + M([-1,0,0,1])*x^2 + M([1,3,-1,0])*x + M.one() 

sage: q = p.inverse_series_trunc(5) 

sage: (p*q).truncate(5) == M.one() 

True 

sage: q = p.inverse_series_trunc(13) 

sage: (p*q).truncate(13) == M.one() 

True 

  

TESTS:: 

  

sage: x = polygen(ZZ['a','b']) 

sage: (x+1).inverse_series_trunc(0) 

Traceback (most recent call last): 

... 

ValueError: the precision must be positive, got 0 

  

AUTHORS: 

  

- David Harvey (2006-09-09): Newton's method implementation for power 

series 

  

- Vincent Delecroix (2014-2015): move the implementation directly in 

polynomial 

""" 

if prec <= 0: 

raise ValueError("the precision must be positive, got {}".format(prec)) 

  

if not self[0].is_unit(): 

raise ValueError("constant term {} is not a unit".format(self[0])) 

  

R = self._parent 

A = R.base_ring() 

try: 

first_coeff = self[0].inverse_of_unit() 

except AttributeError: 

first_coeff = A(~self[0]) 

  

current = R(first_coeff) 

for next_prec in sage.misc.misc.newton_method_sizes(prec)[1:]: 

z = current._mul_trunc_(self, next_prec)._mul_trunc_(current, next_prec) 

current = current + current - z 

return current 

  

def revert_series(self, n): 

r""" 

Return a polynomial ``f`` such that 

``f(self(x)) = self(f(x)) = x mod x^n``. 

  

Currently, this is only implemented over some coefficient rings. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: (x + x^3/6 + x^5/120).revert_series(6) 

3/40*x^5 - 1/6*x^3 + x 

sage: Pol.<x> = CBF[] 

sage: (x + x^3/6 + x^5/120).revert_series(6) 

([0.075000000000000 +/- 9.75e-17])*x^5 + ([-0.166666666666667 +/- 4.45e-16])*x^3 + x 

sage: Pol.<x> = SR[] 

sage: x.revert_series(6) 

Traceback (most recent call last): 

... 

NotImplementedError: only implemented for certain base rings 

""" 

raise NotImplementedError("only implemented for certain base rings") 

  

def __long__(self): 

""" 

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = x - 902384 

sage: long(f) 

Traceback (most recent call last): 

... 

TypeError: cannot coerce nonconstant polynomial to long 

sage: long(R(939392920202)) 

939392920202L 

""" 

if self.degree() > 0: 

raise TypeError("cannot coerce nonconstant polynomial to long") 

return long(self[0]) 

  

cpdef _mul_(self, right): 

""" 

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: (x - 4)*(x^2 - 8*x + 16) 

x^3 - 12*x^2 + 48*x - 64 

sage: C.<t> = PowerSeriesRing(ZZ) 

sage: D.<s> = PolynomialRing(C) 

sage: z = (1 + O(t)) + t*s^2 

sage: z*z 

t^2*s^4 + (2*t + O(t^2))*s^2 + 1 + O(t) 

  

## More examples from trac 2943, added by Kiran S. Kedlaya 2 Dec 09 

sage: C.<t> = PowerSeriesRing(Integers()) 

sage: D.<s> = PolynomialRing(C) 

sage: z = 1 + (t + O(t^2))*s + (t^2 + O(t^3))*s^2 

sage: z*z 

(t^4 + O(t^5))*s^4 + (2*t^3 + O(t^4))*s^3 + (3*t^2 + O(t^3))*s^2 + (2*t + O(t^2))*s + 1 

""" 

if not self or not right: 

return self._parent.zero() 

  

if self._parent.is_exact(): 

return self._mul_karatsuba(right) 

else: 

return self._mul_generic(right) 

  

def _mul_trunc(self, right, n): 

r""" 

Deprecated alias of :meth:`_mul_trunc_` 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: x._mul_trunc(x, 1) 

doctest:...: DeprecationWarning: _mul_trunc is deprecated, use 

_mul_trunc_ instead 

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

0 

""" 

deprecation(18420, "_mul_trunc is deprecated, use _mul_trunc_ instead") 

return self._mul_trunc_(right, n) 

  

cpdef Polynomial _mul_trunc_(self, Polynomial right, long n): 

r""" 

Return the truncated multiplication of two polynomials up to ``n``. 

  

This is the default implementation that does the multiplication and then 

truncate! There are custom implementations in several subclasses: 

  

- :meth:`on dense polynomial over integers (via FLINT) <sage.rings.polynomial.polynomial_integer_dense_flint.Polynomial_integer_dense_flint._mul_trunc_>` 

  

- :meth:`on dense polynomial over Z/nZ (via FLINT) 

<sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint._mul_trunc_>` 

  

- :meth:`on dense rational polynomial (via FLINT) 

<sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint._mul_trunc_>` 

  

- :meth:`on dense polynomial on Z/nZ (via NTL) 

<sage.rings.polynomial.polynomial_modn_dense_ntl.Polynomial_dense_modn_ntl_zz._mul_trunc_>` 

  

EXAMPLES:: 

  

sage: R = QQ['x']['y'] 

sage: y = R.gen() 

sage: x = R.base_ring().gen() 

sage: p1 = 1 - x*y + 2*y**3 

sage: p2 = -1/3 + y**5 

sage: p1._mul_trunc_(p2, 5) 

-2/3*y^3 + 1/3*x*y - 1/3 

  

.. TODO:: 

  

implement a generic truncated Karatsuba and use it here. 

""" 

cdef Polynomial pol 

cdef list x, y 

if not self or not right: 

return self._parent.zero() 

elif n < self._parent._Karatsuba_threshold: 

x = self.list(copy=False) 

y = right.list(copy=False) 

return self._new_generic(do_schoolbook_product(x, y, n)) 

else: 

pol = self.truncate(n) * right.truncate(n) 

return pol._inplace_truncate(n) 

  

def multiplication_trunc(self, other, n): 

r""" 

Truncated multiplication 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: (x^10 + 5*x^5 + x^2 - 3).multiplication_trunc(x^7 - 3*x^3 + 1, 11) 

x^10 + x^9 - 15*x^8 - 3*x^7 + 2*x^5 + 9*x^3 + x^2 - 3 

  

Check that coercion is working:: 

  

sage: R2 = QQ['x'] 

sage: x2 = R2.gen() 

sage: p1 = (x^3 + 1).multiplication_trunc(x2^3 - 2, 5); p1 

-x^3 - 2 

sage: p2 = (x2^3 + 1).multiplication_trunc(x^3 - 2, 5); p2 

-x^3 - 2 

sage: parent(p1) == parent(p2) == R2 

True 

""" 

if not have_same_parent(self, other): 

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

return self._mul_trunc_(other, pyobject_to_long(n)) 

  

def square(self): 

""" 

Returns the square of this polynomial. 

  

.. TODO:: 

  

- This is just a placeholder; for now it just uses ordinary 

multiplication. But generally speaking, squaring is faster than 

ordinary multiplication, and it's frequently used, so subclasses 

may choose to provide a specialised squaring routine. 

  

- Perhaps this even belongs at a lower level? RingElement or 

something? 

  

AUTHORS: 

  

- David Harvey (2006-09-09) 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x^3 + 1 

sage: f.square() 

x^6 + 2*x^3 + 1 

sage: f*f 

x^6 + 2*x^3 + 1 

""" 

return self * self 

  

def squarefree_decomposition(self): 

""" 

Return the square-free decomposition of this polynomial. This is a 

partial factorization into square-free, coprime polynomials. 

  

EXAMPLES:: 

  

sage: x = polygen(QQ) 

sage: p = 37 * (x-1)^3 * (x-2)^3 * (x-1/3)^7 * (x-3/7) 

sage: p.squarefree_decomposition() 

(37*x - 111/7) * (x^2 - 3*x + 2)^3 * (x - 1/3)^7 

sage: p = 37 * (x-2/3)^2 

sage: p.squarefree_decomposition() 

(37) * (x - 2/3)^2 

sage: x = polygen(GF(3)) 

sage: x.squarefree_decomposition() 

x 

sage: f = QQbar['x'](1) 

sage: f.squarefree_decomposition() 

1 

  

""" 

if self.degree() < 0: 

raise ValueError("square-free decomposition not defined for zero polynomial") 

if hasattr(self.base_ring(),'_squarefree_decomposition_univariate_polynomial'): 

return self.base_ring()._squarefree_decomposition_univariate_polynomial(self) 

raise NotImplementedError("square-free decomposition not implemented for this polynomial") 

  

def is_square(self, root=False): 

""" 

Returns whether or not polynomial is square. If the optional 

argument ``root`` is set to ``True``, then also returns the square root 

(or ``None``, if the polynomial is not square). 

  

INPUT: 

  

- ``root`` - whether or not to also return a square 

root (default: ``False``) 

  

OUTPUT: 

  

- ``bool`` - whether or not a square 

  

- ``root`` - (optional) an actual square root if 

found, and ``None`` otherwise. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: (x^2 + 2*x + 1).is_square() 

True 

sage: (x^4 + 2*x^3 - x^2 - 2*x + 1).is_square(root=True) 

(True, x^2 + x - 1) 

  

sage: f = 12*(x+1)^2 * (x+3)^2 

sage: f.is_square() 

False 

sage: f.is_square(root=True) 

(False, None) 

  

sage: h = f/3; h 

4*x^4 + 32*x^3 + 88*x^2 + 96*x + 36 

sage: h.is_square(root=True) 

(True, 2*x^2 + 8*x + 6) 

  

sage: S.<y> = PolynomialRing(RR) 

sage: g = 12*(y+1)^2 * (y+3)^2 

  

sage: g.is_square() 

True 

  

TESTS: 

  

Make sure :trac:`9093` is fixed:: 

  

sage: R(1).is_square() 

True 

sage: R(4/9).is_square(root=True) 

(True, 2/3) 

sage: R(-1/3).is_square() 

False 

sage: R(0).is_square() 

True 

""" 

if self.is_zero(): 

return (True, self) if root else True 

  

try: 

f = self.squarefree_decomposition() 

except NotImplementedError: 

f = self.factor() 

  

u = self._parent.base_ring()(f.unit()) 

  

if all(a[1] % 2 == 0 for a in f) and u.is_square(): 

g = u.sqrt() 

for a in f: 

g *= a[0] ** (a[1] / 2) 

return (True, g) if root else True 

else: 

return (False, None) if root else False 

  

def any_root(self, ring=None, degree=None, assume_squarefree=False): 

""" 

Return a root of this polynomial in the given ring. 

  

INPUT: 

  

- ``ring`` -- The ring in which a root is sought. By default 

this is the coefficient ring. 

  

- ``degree`` (None or nonzero integer) -- Used for polynomials 

over finite fields. Returns a root of degree 

``abs(degree)`` over the ground field. If negative, also 

assumes that all factors of this polynomial are of degree 

``abs(degree)``. If None, returns a root of minimal degree 

contained within the given ring. 

  

- ``assume_squarefree`` (bool) -- Used for polynomials over 

finite fields. If True, this polynomial is assumed to be 

squarefree. 

  

EXAMPLES:: 

  

sage: R.<x> = GF(11)[] 

sage: f = 7*x^7 + 8*x^6 + 4*x^5 + x^4 + 6*x^3 + 10*x^2 + 8*x + 5 

sage: f.any_root() 

2 

sage: f.factor() 

(7) * (x + 9) * (x^6 + 10*x^4 + 6*x^3 + 5*x^2 + 2*x + 2) 

sage: f = x^6 + 10*x^4 + 6*x^3 + 5*x^2 + 2*x + 2 

sage: f.any_root(GF(11^6, 'a')) 

a^5 + a^4 + 7*a^3 + 2*a^2 + 10*a 

sage: sorted(f.roots(GF(11^6, 'a'))) 

[(10*a^5 + 2*a^4 + 8*a^3 + 9*a^2 + a, 1), (a^5 + a^4 + 7*a^3 + 2*a^2 + 10*a, 1), (9*a^5 + 5*a^4 + 10*a^3 + 8*a^2 + 3*a + 1, 1), (2*a^5 + 8*a^4 + 3*a^3 + 6*a + 2, 1), (a^5 + 3*a^4 + 8*a^3 + 2*a^2 + 3*a + 4, 1), (10*a^5 + 3*a^4 + 8*a^3 + a^2 + 10*a + 4, 1)] 

sage: f.any_root(GF(11^6, 'a')) 

a^5 + a^4 + 7*a^3 + 2*a^2 + 10*a 

  

sage: g = (x-1)*(x^2 + 3*x + 9) * (x^5 + 5*x^4 + 8*x^3 + 5*x^2 + 3*x + 5) 

sage: g.any_root(ring=GF(11^10, 'b'), degree=1) 

1 

sage: g.any_root(ring=GF(11^10, 'b'), degree=2) 

5*b^9 + 4*b^7 + 4*b^6 + 8*b^5 + 10*b^2 + 10*b + 5 

sage: g.any_root(ring=GF(11^10, 'b'), degree=5) 

5*b^9 + b^8 + 3*b^7 + 2*b^6 + b^5 + 4*b^4 + 3*b^3 + 7*b^2 + 10*b 

  

TESTS:: 

  

sage: R.<x> = GF(5)[] 

sage: K.<a> = GF(5^12) 

sage: for _ in range(40): 

....: f = R.random_element(degree=4) 

....: assert f(f.any_root(K)) == 0 

  

Check that our Cantor-Zassenhaus implementation does not loop 

over finite fields of even characteristic (see :trac:`16162`):: 

  

sage: K.<a> = GF(2**8) 

sage: x = polygen(K) 

sage: (x**2+x+1).any_root() # used to loop 

a^7 + a^6 + a^4 + a^2 + a + 1 

sage: (x**2+a+1).any_root() 

a^7 + a^2 

  

Also check that such computations can be interrupted:: 

  

sage: K.<a> = GF(2^8) 

sage: x = polygen(K) 

sage: pol = x^1000000 + x + a 

sage: alarm(0.5); pol.any_root() 

Traceback (most recent call last): 

... 

AlarmInterrupt 

  

Check root computation over large finite fields:: 

  

sage: K.<a> = GF(2**50) 

sage: x = polygen(K) 

sage: (x**10+x+a).any_root() 

a^49 + a^47 + a^44 + a^42 + a^41 + a^39 + a^38 + a^37 + a^36 + a^34 + a^33 + a^29 + a^27 + a^26 + a^25 + a^23 + a^18 + a^13 + a^7 + a^5 + a^4 + a^3 + a^2 + a 

sage: K.<a> = GF(2**150) 

sage: x = polygen(K) 

sage: (x**10+x+a).any_root() 

a^149 + a^148 + a^146 + a^144 + a^143 + a^140 + a^138 + a^136 + a^134 + a^132 + a^131 + a^130 + a^129 + a^127 + a^123 + a^120 + a^118 + a^114 + a^113 + a^112 + a^111 + a^108 + a^104 + a^103 + a^102 + a^99 + a^98 + a^94 + a^91 + a^90 + a^88 + a^79 + a^78 + a^75 + a^73 + a^72 + a^67 + a^65 + a^64 + a^63 + a^62 + a^61 + a^59 + a^57 + a^52 + a^50 + a^48 + a^47 + a^46 + a^45 + a^43 + a^41 + a^39 + a^37 + a^34 + a^31 + a^29 + a^27 + a^25 + a^23 + a^22 + a^20 + a^18 + a^16 + a^14 + a^11 + a^10 + a^8 + a^6 + a^5 + a^4 + a + 1 

  

Check that :trac:`21998` has been resolved:: 

  

sage: K.<a> = GF(2^4) 

sage: R.<x> = K[] 

sage: f = x^2 + x + a^2 + a 

sage: f.any_root() 

a + 1 

  

""" 

if self.base_ring().is_finite() and self.base_ring().is_field(): 

if self.degree() < 0: 

return ring(0) 

if self.degree() == 0: 

raise ValueError("no roots A %s" % self) 

if not assume_squarefree: 

SFD = self.squarefree_decomposition() 

SFD.sort() 

for f, e in SFD: 

try: 

return f.any_root(ring, degree, True) 

except ValueError: 

pass 

if self.degree() == 1 and (degree is None or degree == 1): 

if ring is None: 

return -self[0]/self[1] 

else: 

return ring(-self[0]/self[1]) 

q = self.base_ring().order() 

if ring is None: 

allowed_deg_mult = Integer(1) 

else: 

if not (self.base_ring().is_field() and self.base_ring().is_finite()): 

raise NotImplementedError 

if ring.characteristic() != self.base_ring().characteristic(): 

raise ValueError("ring must be an extension of the base ring") 

if not (ring.is_field() and ring.is_finite()): 

raise NotImplementedError 

allowed_deg_mult = Integer(ring.factored_order()[0][1]) # generally it will be the quotient of this by the degree of the base ring. 

if degree is None: 

x = self._parent.gen() 

if allowed_deg_mult == 1: 

xq = pow(x,q,self) 

self = self.gcd(xq-x) 

degree = -1 

if self.degree() == 0: 

raise ValueError("no roots B %s" % self) 

else: 

xq = x 

d = Integer(0) 

while True: 

# one pass for roots that actually lie within ring. 

e = self.degree() 

if 2*d+2 > e: 

# this polynomial has no factors dividing allowed_deg_mult 

if allowed_deg_mult % e == 0: 

degree = -e 

break 

while d < allowed_deg_mult: 

d = d+1 

xq = pow(xq,q,self) 

if d.divides(allowed_deg_mult): 

break 

A = self.gcd(xq-x) 

if A != 1: 

self = A 

degree = -d 

break 

if d == allowed_deg_mult: 

break 

if degree is None: 

if allowed_deg_mult == 1: 

raise ValueError("no roots C %s" % self) 

xq = x 

d = Integer(0) 

while True: 

# now another for roots that will lie in an extension. 

e = self.degree() 

if 2*d+2 > e: 

# this polynomial is irreducible. 

degree = -e 

break 

while True: 

# we waste a little effort here in computing the xq again. 

d = d+1 

xq = pow(xq,q,self) 

if allowed_deg_mult.divides(d): 

break 

A = self.gcd(xq-x) 

if A != 1: 

self = A 

degree = -d 

break 

if degree == 0: 

raise ValueError("degree should be nonzero") 

R = self._parent 

x = R.gen() 

if degree > 0: 

xq = x 

d = 0 

while True: 

e = self.degree() 

if 2*d > e: 

if degree != e: 

raise ValueError("no roots D %s" % self) 

break 

d = d+1 

xq = pow(xq,q,self) 

if d == degree: 

break 

A = self.gcd(xq-x) 

if A != 1: 

self = self // A 

if d == degree: 

self = self.gcd(xq-x) 

if self.degree() == 0: 

raise ValueError("no roots E %s" % self) 

else: 

degree = -degree 

if ring is None: 

if degree == 1: 

ring = self.base_ring() 

else: 

ring = self.base_ring().extension(degree) # this won't work yet. 

# now self has only roots of degree ``degree``. 

# for now, we only implement the Cantor-Zassenhaus split 

k = self.degree() // degree 

if k == 1: 

try: 

return self.roots(ring, multiplicities=False)[0] # is there something better to do here? 

except IndexError: 

raise ValueError("no roots F %s" % self) 

if q % 2 == 0: 

while True: 

T = R.random_element(2*degree-1) 

if T == 0: 

continue 

T = T.monic() 

C = T 

for i in range(degree-1): 

C = T + pow(C,q,self) 

h = self.gcd(C) 

hd = h.degree() 

if hd != 0 and hd != self.degree(): 

if 2*hd <= self.degree(): 

return h.any_root(ring, -degree, True) 

else: 

return (self//h).any_root(ring, -degree, True) 

else: 

while True: 

T = R.random_element(2*degree-1) 

if T == 0: 

continue 

T = T.monic() 

h = self.gcd(pow(T, Integer((q**degree-1)/2), self)-1) 

hd = h.degree() 

if hd != 0 and hd != self.degree(): 

if 2*hd <= self.degree(): 

return h.any_root(ring, -degree, True) 

else: 

return (self//h).any_root(ring, -degree, True) 

else: 

return self.roots(ring=ring, multiplicities=False)[0] 

  

def __truediv__(left, right): 

""" 

EXAMPLES:: 

  

sage: x = QQ['x'].0 

sage: f = (x^3 + 5)/3; f 

1/3*x^3 + 5/3 

sage: f.parent() 

Univariate Polynomial Ring in x over Rational Field 

  

If we do the same over `\ZZ` the result is in the 

polynomial ring over `\QQ`. 

  

:: 

  

sage: x = ZZ['x'].0 

sage: f = (x^3 + 5)/3; f 

1/3*x^3 + 5/3 

sage: f.parent() 

Univariate Polynomial Ring in x over Rational Field 

  

Divides can make elements of the fraction field:: 

  

sage: R.<x> = QQ['x'] 

sage: f = x^3 + 5 

sage: g = R(3) 

sage: h = f/g; h 

1/3*x^3 + 5/3 

sage: h.parent() 

Fraction Field of Univariate Polynomial Ring in x over Rational Field 

  

This is another example over a non-prime finite field (submitted by 

a student of Jon Hanke). It illustrates cancellation between the 

numerator and denominator over a non-prime finite field. 

  

:: 

  

sage: R.<x> = PolynomialRing(GF(5^2, 'a'), 'x') 

sage: f = x^3 + 4*x 

sage: f / (x - 1) 

x^2 + x 

  

Be careful about coercions (this used to be broken):: 

  

sage: R.<x> = ZZ['x'] 

sage: f = x / Mod(2,5); f 

3*x 

sage: f.parent() 

Univariate Polynomial Ring in x over Ring of integers modulo 5 

  

TESTS: 

  

Check that :trac:`12217` is fixed:: 

  

sage: P.<x> = GF(5)[] 

sage: x/0 

Traceback (most recent call last): 

... 

ZeroDivisionError: Inverse does not exist. 

  

sage: P.<x> = GF(25, 'a')[] 

sage: x/5 

Traceback (most recent call last): 

... 

ZeroDivisionError: division by zero in finite field 

  

Check that :trac:`23611` is fixed:: 

  

sage: int(1) / x 

1/x 

""" 

# Same parents => bypass coercion 

if have_same_parent(left, right): 

return (<Element>left)._div_(right) 

  

# Try division of polynomial by a scalar 

if isinstance(left, Polynomial): 

R = (<Polynomial>left)._parent._base 

try: 

x = R._coerce_(right) 

return left * ~x 

except TypeError: 

pass 

  

# Delegate to coercion model. The line below is basically 

# RingElement.__truediv__(left, right), except that it also 

# works if left is not of type RingElement. 

return wrapperdescr_fastcall(RingElement.__truediv__, 

left, (right,), <object>NULL) 

  

def __div__(left, right): 

return PyNumber_TrueDivide(left, right) 

  

def __pow__(left, right, modulus): 

""" 

EXAMPLES:: 

  

sage: x = polygen(QQ['u']['v']) 

sage: f = x - 1 

sage: f._pow(3) 

x^3 - 3*x^2 + 3*x - 1 

sage: f^3 

x^3 - 3*x^2 + 3*x - 1 

  

sage: R = PolynomialRing(GF(2), 'x') 

sage: f = R(x^9 + x^7 + x^6 + x^5 + x^4 + x^2 + x) 

sage: h = R(x^10 + x^7 + x^6 + x^5 + x^4 + x^3 + x^2 + 1) 

sage: pow(f, 2, h) 

x^9 + x^8 + x^7 + x^5 + x^3 

  

TESTS:: 

  

sage: x = polygen(QQ['u']['v']) 

sage: x^(1/2) 

Traceback (most recent call last): 

... 

TypeError: non-integral exponents not supported 

  

:: 

  

sage: int(1)^x 

Traceback (most recent call last): 

... 

TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense' 

  

:: 

  

sage: x^x 

Traceback (most recent call last): 

... 

TypeError: non-integral exponents not supported 

  

:: 

  

sage: k = GF(5) 

sage: D.<x> = k[] 

sage: l.<x> = k.extension(x^2 + 2) 

sage: R.<t> = l[] 

sage: f = t^4 + (2*x - 1)*t^3 + (2*x + 1)*t^2 + 3 

sage: h = t^4 - x*t^3 + (3*x + 1)*t^2 + 2*t + 2*x - 1 

sage: pow(f, 2, h) 

3*t^3 + (2*x + 3)*t^2 + (2*x + 2)*t + 2*x + 2 

sage: pow(f, 10**7, h) 

4*x*t^3 + 2*x*t^2 + 4*x*t + 4 

  

Check that :trac:`18457` is fixed:: 

  

sage: R.<x> = PolynomialRing(GF(5), sparse=True) 

sage: (1+x)^(5^10) # used to hang forever 

x^9765625 + 1 

sage: S.<t> = GF(3)[] 

sage: R1.<x> = PolynomialRing(S, sparse=True) 

sage: (1+x+t)^(3^10) 

x^59049 + t^59049 + 1 

sage: R2.<x> = PolynomialRing(S, sparse=False) 

sage: (1+x+t)^(3^10) 

x^59049 + t^59049 + 1 

  

Check that the algorithm used is indeed correct:: 

  

sage: from sage.arith.power import generic_power 

sage: R1 = PolynomialRing(GF(8,'a'), 'x') 

sage: R2 = PolynomialRing(GF(9,'b'), 'x', sparse=True) 

sage: R3 = PolynomialRing(R2, 'y') 

sage: R4 = PolynomialRing(R1, 'y', sparse=True) 

sage: for d in range(20,40): # long time 

....: for R in [R1, R2, R3, R3]: 

....: a = R.random_element() 

....: assert a^d == generic_power(a, d) 

  

Test the powering modulo ``x^n`` (calling :meth:`power_trunc`):: 

  

sage: R.<x> = GF(3)[] 

sage: pow(x + 1, 51, x^7) 

x^6 + 2*x^3 + 1 

  

sage: S.<y> = QQ[] 

sage: R.<x> = S[] 

sage: pow(y*x+1, 51, x^7) 

18009460*y^6*x^6 + 2349060*y^5*x^5 + ... + 51*y*x + 1 

  

Check that fallback method is used when it is not possible to compute 

the characteristic of the base ring (trac:`24308`):: 

  

sage: kk.<a,b> = GF(2)[] 

sage: k.<y,w> = kk.quo(a^2+a+1) 

sage: K.<T> = k[]  

sage: (T*y)^21 

T^21 

""" 

if not isinstance(left, Polynomial): 

return NotImplemented 

cdef Polynomial self = <Polynomial>left 

  

if type(right) is not Integer: 

try: 

right = Integer(right) 

except TypeError: 

raise TypeError("non-integral exponents not supported") 

  

if self.degree() <= 0: 

return self.parent()(self[0]**right) 

if right < 0: 

return (~self)**(-right) 

if modulus: 

if right > 0 and \ 

parent(modulus) == self.parent() and \ 

modulus.number_of_terms() == 1 and \ 

modulus.leading_coefficient().is_one(): 

return self.power_trunc(right, modulus.degree()) 

return power_mod(self, right, modulus) 

if self.is_gen(): # special case x**n should be faster! 

P = self.parent() 

R = P.base_ring() 

if P.is_sparse(): 

v = {right:R.one()} 

else: 

v = [R.zero()]*right + [R.one()] 

return self.parent()(v, check=False) 

if right > 20: # no gain below 

try: 

p = self.parent().characteristic() 

except (AttributeError, NotImplementedError): 

# some quotients do not implement characteristic 

# see trac ticket 24308 

p = -1 

if 0 < p <= right and (self.base_ring() in sage.categories.integral_domains.IntegralDomains() or p.is_prime()): 

x = self.parent().gen() 

ret = self.parent().one() 

e = 1 

q = right 

sparse = self.parent().is_sparse() 

if sparse: 

d = self.dict() 

else: 

c = self.list(copy=False) 

while q > 0: 

q, r = q.quo_rem(p) 

if r != 0: 

if sparse: 

tmp = self.parent()({e*k : d[k]**e for k in d}) 

else: 

tmp = [0] * (e * len(c) - e + 1) 

for i in range(len(c)): 

tmp[e*i] = c[i]**e 

tmp = self.parent()(tmp) 

ret *= generic_power(tmp, r) 

e *= p 

return ret 

  

return generic_power(self, right) 

  

def power_trunc(self, n, prec): 

r""" 

Truncated ``n``-th power of this polynomial up to precision ``prec`` 

  

INPUT: 

  

- ``n`` -- (non-negative integer) power to be taken 

  

- ``prec`` -- (integer) the precision 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: (3*x^2 - 2*x + 1).power_trunc(5, 8) 

-1800*x^7 + 1590*x^6 - 1052*x^5 + 530*x^4 - 200*x^3 + 55*x^2 - 10*x + 1 

sage: ((3*x^2 - 2*x + 1)^5).truncate(8) 

-1800*x^7 + 1590*x^6 - 1052*x^5 + 530*x^4 - 200*x^3 + 55*x^2 - 10*x + 1 

  

sage: S.<y> = R[] 

sage: (x+y).power_trunc(5,5) 

5*x*y^4 + 10*x^2*y^3 + 10*x^3*y^2 + 5*x^4*y + x^5 

sage: ((x+y)^5).truncate(5) 

5*x*y^4 + 10*x^2*y^3 + 10*x^3*y^2 + 5*x^4*y + x^5 

  

sage: R.<x> = GF(3)[] 

sage: p = x^2 - x + 1 

sage: q = p.power_trunc(80, 20) 

sage: q 

x^19 + x^18 + ... + 2*x^4 + 2*x^3 + x + 1 

sage: (p^80).truncate(20) == q 

True 

  

sage: R.<x> = GF(7)[] 

sage: p = (x^2 + x + 1).power_trunc(2^100, 100) 

sage: p 

2*x^99 + x^98 + x^95 + 2*x^94 + ... + 3*x^2 + 2*x + 1 

  

sage: for i in range(100): 

....: q1 = (x^2 + x + 1).power_trunc(2^100 + i, 100) 

....: q2 = p * (x^2 + x + 1).power_trunc(i, 100) 

....: q2 = q2.truncate(100) 

....: assert q1 == q2, "i = {}".format(i) 

  

TESTS:: 

  

sage: x = polygen(QQ) 

sage: (3*x-5).power_trunc(2^200, 0) 

0 

sage: x.power_trunc(-1, 10) 

Traceback (most recent call last): 

... 

ValueError: n must be a non-negative integer 

sage: R.<y> = QQ['x'] 

sage: y.power_trunc(2**32-1, 2) 

0 

sage: y.power_trunc(2**64-1, 2) 

0 

""" 

cdef Integer ZZn = ZZ(n) 

if mpz_fits_ulong_p(ZZn.value): 

return self._power_trunc(mpz_get_ui(ZZn.value), prec) 

return generic_power_trunc(self, ZZn, pyobject_to_long(prec)) 

  

cpdef Polynomial _power_trunc(self, unsigned long n, long prec): 

r""" 

Truncated ``n``-th power of this polynomial up to precision ``prec`` 

  

This method is overriden for certain subclasses when a library function 

is available. 

  

INPUT: 

  

- ``n`` -- (non-negative integer) power to be taken 

  

- ``prec`` -- (integer) the precision 

  

TESTS:: 

  

sage: R.<x> = QQ['y'][] 

sage: for p in [R.one(), x, x+1, x-1, x^2 - 1]: 

....: for n in range(0, 20): 

....: for prec in [1, 2, 3, 10]: 

....: assert p._power_trunc(n, prec) == (p**n).truncate(prec) 

""" 

return generic_power_trunc(self, Integer(n), prec) 

  

def _pow(self, right): 

# TODO: fit __pow__ into the arithmetic structure 

if self.degree() <= 0: 

return self._parent(self[0]**right) 

if right < 0: 

return (~self)**(-right) 

if (<Polynomial>self) == self._parent.gen(): # special case x**n should be faster! 

v = [0]*right + [1] 

return self._parent(v, check=True) 

return generic_power(self, right) 

  

def _repr(self, name=None): 

""" 

Return the string representation of this polynomial. 

  

INPUT: 

  

- ``name`` - None or a string; used for printing the variable. 

  

EXAMPLES:: 

  

sage: S.<t> = QQ[] 

sage: R.<x> = S[] 

sage: f = (1 - t^3)*x^3 - t^2*x^2 - x + 1 

sage: f._repr() 

'(-t^3 + 1)*x^3 - t^2*x^2 - x + 1' 

sage: f._repr('z') 

'(-t^3 + 1)*z^3 - t^2*z^2 - z + 1' 

sage: P.<y> = RR[] 

sage: y, -y 

(y, -y) 

  

TESTS: 

  

We verify that :trac:`23020` has been resolved. (There are no elements 

in the Sage library yet that do not implement ``__nonzero__``, so we 

have to create one artificially.):: 

  

sage: class PatchedAlgebraicNumber(sage.rings.qqbar.AlgebraicNumber): 

....: def __nonzero__(self): raise NotImplementedError() 

sage: R.<x> = QQbar[] 

sage: R([PatchedAlgebraicNumber(0), 1]) 

x + 0 

  

""" 

s = " " 

m = self.degree() + 1 

if name is None: 

name = self._parent.variable_name() 

atomic_repr = self._parent.base_ring()._repr_option('element_is_atomic') 

coeffs = self.list(copy=False) 

for n in reversed(xrange(m)): 

x = coeffs[n] 

is_nonzero = False 

try: 

is_nonzero = bool(x) 

except NotImplementedError: 

# for some elements it is not possible/feasible to determine 

# whether they are zero or not; we just print them anyway in 

# such cases 

is_nonzero = True 

if is_nonzero: 

if n != m-1: 

s += " + " 

x = y = repr(x) 

if y.find("-") == 0: 

y = y[1:] 

if not atomic_repr and n > 0 and (y.find("+") != -1 or y.find("-") != -1): 

x = "(%s)"%x 

if n > 1: 

var = "*%s^%s"%(name,n) 

elif n==1: 

var = "*%s"%name 

else: 

var = "" 

s += "%s%s"%(x,var) 

s = s.replace(" + -", " - ") 

s = re.sub(r' 1(\.0+)?\*',' ', s) 

s = re.sub(r' -1(\.0+)?\*',' -', s) 

if s == " ": 

return "0" 

return s[1:] 

  

def _repr_(self): 

r""" 

Return string representation of this polynomial. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: f = x^3+2/3*x^2 - 5/3 

sage: f._repr_() 

'x^3 + 2/3*x^2 - 5/3' 

sage: f.rename('vaughn') 

Traceback (most recent call last): 

... 

NotImplementedError: object does not support renaming: x^3 + 2/3*x^2 - 5/3 

""" 

return self._repr() 

  

def _latex_(self, name=None): 

r""" 

Return the latex representation of this polynomial. 

  

EXAMPLES: 

  

A fairly simple example over `\QQ`. 

  

:: 

  

sage: C3.<omega> = CyclotomicField(3) 

sage: R.<X> = C3[] 

sage: f = X^3 - omega*X 

sage: latex(f) 

X^{3} - \omega X 

sage: R.<x> = RDF[] 

sage: latex(x+2) 

x + 2.0 

  

The following illustrates the fix of :trac:`2586`:: 

  

sage: latex(ZZ['alpha']['b']([0, ZZ['alpha'].0])) 

\alpha b 

  

The following illustrates a (non-intentional) superfluity of parentheses 

  

sage: K.<I>=QuadraticField(-1) 

sage: R.<x>=K[] 

sage: latex(I*x^2-I*x) 

\left(\sqrt{-1}\right) x^{2} + \left(-\sqrt{-1}\right) x 

""" 

s = " " 

coeffs = self.list(copy=False) 

m = len(coeffs) 

if name is None: 

name = self._parent.latex_variable_names()[0] 

atomic_repr = self._parent.base_ring()._repr_option('element_is_atomic') 

for n in reversed(xrange(m)): 

x = coeffs[n] 

x = y = latex(x) 

if x != '0': 

if n != m-1: 

s += " + " 

if y.find("-") == 0: 

y = y[1:] 

if not atomic_repr and n > 0 and (y.find("+") != -1 or y.find("-") != -1): 

x = "\\left(%s\\right)"%x 

if n > 1: 

var = "|%s^{%s}"%(name,n) 

elif n==1: 

var = "|%s"%name 

else: 

var = "" 

s += "%s %s"%(x,var) 

s = s.replace(" + -", " - ") 

s = re.sub(" 1(\.0+)? \|"," ", s) 

s = re.sub(" -1(\.0+)? \|", " -", s) 

s = s.replace("|","") 

if s==" ": 

return "0" 

return s[1:].lstrip().rstrip() 

  

def _sage_input_(self, sib, coerced): 

r""" 

Produce an expression which will reproduce this value when 

evaluated. 

  

EXAMPLES:: 

  

sage: K.<x> = ZZ[] 

sage: sage_input(K(0), verify=True) 

# Verified 

ZZ['x'](0) 

sage: sage_input(K(-54321), preparse=False, verify=True) 

# Verified 

ZZ['x'](-54321) 

sage: sage_input(x, verify=True) 

# Verified 

R.<x> = ZZ[] 

x 

sage: sage_input(x, preparse=False) 

R = ZZ['x'] 

x = R.gen() 

x 

sage: sage_input((3*x-2)^3, verify=True) 

# Verified 

R.<x> = ZZ[] 

27*x^3 - 54*x^2 + 36*x - 8 

sage: L.<y> = K[] 

sage: sage_input(L(0), verify=True) 

# Verified 

ZZ['x']['y'](0) 

sage: sage_input((x+y+1)^2, verify=True) 

# Verified 

R1.<x> = ZZ[] 

R2.<y> = R1[] 

y^2 + (2*x + 2)*y + (x^2 + 2*x + 1) 

sage: sage_input(RR(pi) * polygen(RR), verify=True) 

# Verified 

R.<x> = RR[] 

3.1415926535897931*x 

sage: sage_input(polygen(GF(7)) + 12, verify=True) 

# Verified 

R.<x> = GF(7)[] 

x + 5 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: K(0)._sage_input_(SageInputBuilder(), True) 

{atomic:0} 

sage: (x^2 - 1)._sage_input_(SageInputBuilder(), False) 

{binop:- {binop:** {gen:x {constr_parent: {subscr: {atomic:ZZ}[{atomic:'x'}]} with gens: ('x',)}} {atomic:2}} {atomic:1}} 

""" 

if self.degree() > 0: 

gen = sib.gen(self._parent) 

coeffs = self.list(copy=False) 

terms = [] 

for i in range(len(coeffs)-1, -1, -1): 

if i > 0: 

if i > 1: 

gen_pow = gen**sib.int(i) 

else: 

gen_pow = gen 

terms.append(sib.prod((sib(coeffs[i], True), gen_pow), simplify=True)) 

else: 

terms.append(sib(coeffs[i], True)) 

return sib.sum(terms, simplify=True) 

elif coerced: 

return sib(self.constant_coefficient(), True) 

else: 

return sib(self._parent)(sib(self.constant_coefficient(), True)) 

  

def __setitem__(self, n, value): 

""" 

Set the n-th coefficient of this polynomial. This always raises an 

IndexError, since in Sage polynomials are immutable. 

  

INPUT: 

  

  

- ``n`` - an integer 

  

- ``value`` - value to set the n-th coefficient to 

  

  

OUTPUT: an IndexError is always raised. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^3 + x + 1 

sage: f[2] = 3 

Traceback (most recent call last): 

... 

IndexError: polynomials are immutable 

""" 

raise IndexError("polynomials are immutable") 

  

cpdef _floordiv_(self, right): 

""" 

Quotient of division of self by other. This is denoted //. 

  

If self = quotient \* right + remainder, this function returns 

quotient. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^3 + x + 1 

sage: g = f*(x^2-2) + x 

sage: g.__floordiv__(f) 

x^2 - 2 

sage: g//f 

x^2 - 2 

""" 

Q, _ = self.quo_rem(right) 

return Q 

  

def __mod__(self, other): 

""" 

Remainder of division of self by other. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: x % (x+1) 

-1 

sage: (x^3 + x - 1) % (x^2 - 1) 

2*x - 1 

""" 

_, R = self.quo_rem(other) 

return R 

  

def mod(self, other): 

""" 

Remainder of division of self by other. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: x % (x+1) 

-1 

sage: (x^3 + x - 1) % (x^2 - 1) 

2*x - 1 

""" 

return self % other 

  

def _is_atomic(self): 

""" 

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: S.<y> = R[] 

sage: S(x+2) 

x + 2 

sage: S(x+2)._is_atomic() 

False 

sage: S(x)._is_atomic() 

True 

""" 

return (self.degree() == self.valuation() and 

self.leading_coefficient()._is_atomic()) 

  

cpdef _mul_generic(self, right): 

""" 

Compute the product of self and right using the classical quadratic 

algorithm. This method is the default for inexact rings. 

  

For two polynomials of degree n and m this method needs 

(m+1)*(n+1) products and n*m additions 

  

EXAMPLES:: 

  

sage: K.<x> = QQ[] 

sage: f = 1+3*x+4*x^2+x^3 

sage: g = x^2+3*x^5 

sage: f._mul_generic(g) 

3*x^8 + 12*x^7 + 9*x^6 + 4*x^5 + 4*x^4 + 3*x^3 + x^2 

  

Show the product in the symbolic ring:: 

  

sage: L = SR['x'] 

sage: var('a0,a1,b0,b1') 

(a0, a1, b0, b1) 

sage: L([a0,a1])._mul_generic(L([b0,b1])) 

a1*b1*x^2 + (a1*b0 + a0*b1)*x + a0*b0 

  

A non-commutative example:: 

  

sage: A.<i,j,k> = QuaternionAlgebra(QQ, -1,-1) 

sage: R.<w> = PolynomialRing(A) 

sage: f = i*w + j 

sage: g = k*w + 1 

sage: f._mul_generic(g) 

-j*w^2 + 2*i*w + j 

sage: g._mul_generic(f) 

j*w^2 + j 

  

  

TESTS:: 

  

sage: K.<x> = QQ[] 

sage: f = K(0) 

sage: g = K.random_element(10) 

sage: f._mul_generic(g) 

0 

sage: g._mul_generic(f) 

0 

sage: f._mul_generic(K(0)) 

0 

sage: g._mul_generic(g) - g._mul_karatsuba(g) 

0 

sage: h = K(QQ.random_element(100,100)) 

sage: f._mul_generic(h) 

0 

sage: K([h*c for c in g.list()]) - g._mul_generic(h) 

0 

sage: g._mul_generic(h) - K([h*c for c in g.list()]) 

0 

""" 

if self is right: 

return self._square_generic() 

cdef list x = self.list(copy=False) 

cdef list y = right.list(copy=False) 

return self._new_generic(do_schoolbook_product(x, y, -1)) 

  

cdef _square_generic(self): 

cdef list x = self.list(copy=False) 

cdef Py_ssize_t i, j 

cdef Py_ssize_t d = len(x)-1 

zero = self._parent.base_ring().zero() 

two = self._parent.base_ring()(2) 

cdef list coeffs = [zero] * (2 * d + 1) 

for i from 0 <= i <= d: 

coeffs[2*i] = x[i] * x[i] 

for j from 0 <= j < i: 

coeffs[i+j] += two * x[i] * x[j] 

return self._new_generic(coeffs) 

  

def _mul_fateman(self, right): 

r""" 

Returns the product of two polynomials using Kronecker's trick to 

do the multiplication. This could be used over a generic base 

ring. 

  

.. NOTE:: 

  

- Since this is implemented in interpreted Python, it could be 

hugely sped up by reimplementing it in Pyrex. 

  

- Over the reals there is precision loss, at least in the current 

implementation. 

  

  

INPUT: 

  

- ``self`` - Polynomial 

  

- ``right`` - Polynomial (over same base ring as 

self) 

  

  

OUTPUT: Polynomial - The product self\*right. 

  

ALGORITHM: Based on a paper by R. Fateman 

  

http://www.cs.berkeley.edu/~fateman/papers/polysbyGMP.pdf 

  

The idea is to encode dense univariate polynomials as big integers, 

instead of sequences of coefficients. The paper argues that because 

integer multiplication is so cheap, that encoding 2 polynomials to 

big numbers and then decoding the result might be faster than 

popular multiplication algorithms. This seems true when the degree 

is larger than 200. 

  

EXAMPLES:: 

  

sage: S.<y> = PolynomialRing(RR) 

sage: f = y^10 - 1.393493*y + 0.3 

sage: f._mul_karatsuba(f,0) 

y^20 - 2.78698600000000*y^11 + 0.600000000000000*y^10 + 1.11022302462516e-16*y^8 - 1.11022302462516e-16*y^6 - 1.11022302462516e-16*y^3 + 1.94182274104900*y^2 - 0.836095800000000*y + 0.0900000000000000 

sage: f._mul_fateman(f) 

y^20 - 2.78698600000000*y^11 + 0.600000000000000*y^10 + 1.94182274104900*y^2 - 0.836095800000000*y + 0.0900000000000000 

  

Advantages: 

  

  

- Faster than Karatsuba over `\QQ` and 

`\ZZ` (but much slower still than calling NTL's 

optimized C++ implementation, which is the default over 

`\ZZ`) 

  

- Potentially less complicated. 

  

  

Drawbacks: 

  

  

- Slower over R when the degree of both of polynomials is less 

than 250 (roughly). 

  

- Over R, results may not be as accurate as the Karatsuba case. 

This is because we represent coefficients of polynomials over R as 

fractions, then convert them back to floating-point numbers. 

  

  

AUTHORS: 

  

- Didier Deshommes (2006-05-25) 

""" 

return self._parent(polynomial_fateman._mul_fateman_mul(self,right)) 

  

@cython.boundscheck(False) 

@cython.wraparound(False) 

@cython.overflowcheck(False) 

def _mul_karatsuba(self, right, K_threshold = None): 

r""" 

Compute the product of two polynomials using the Karatsuba divide 

and conquer multiplication algorithm. This is only used over a 

generic base ring. (Special libraries like Flint are used, e.g., for 

the integers and rationals, which are much faster.) 

  

INPUT: 

  

- ``self`` - Polynomial 

- ``right`` - Polynomial (over same base ring as self) 

- ``K_threshold`` - (optional) Integer. A threshold to fall back to 

schoolbook algorithm. In the recursion, if one of the polynomials is 

of degree less that K_threshold then the classic quadratic polynomial 

is used. 

  

OUTPUT: Polynomial - The product self\*right. 

  

ALGORITHM: The basic idea is to use that 

  

.. MATH:: 

  

(aX + b) (cX + d) = acX^2 + ((a+b)(c+d)-ac-bd)X + bd 

  

  

where ac=a\*c and bd=b\*d, which requires three multiplications 

instead of the naive four. Given f and g of arbitrary degree bigger 

than one, let e be min(deg(f),deg(g))/2. Write 

  

.. MATH:: 

  

f = a X^e + b \text{ and } g = c X^e + d 

  

  

and use the identity 

  

.. MATH:: 

  

(aX^e + b) (cX^e + d) = ac X^{2e} +((a+b)(c+d) - ac - bd)X^e + bd 

  

  

to recursively compute `fg`. 

  

If `self` is a polynomial of degree n and `right` is a polynomial of 

degree m with n < m, then we interpret `right` as 

  

.. MATH:: 

  

g0 + g1 * x^n + g2 * x^{2n} + ... + gq * x^{nq} 

  

where `gi` are polynomials of degree <= n. We then compute each product 

`gi*right` with Karatsuba multiplication and reconstruct `self*right` 

from the partial products. 

  

The theoretical complexity for multiplying two polynomials of the same 

degree n is O(n^log(3,2)). Through testing of polynomials of degree up 

to 5000 we get that the number of operations for two polynomials of 

degree up to n-1 is bounded by: 

  

7.53*n**1.59 additions and 1.46*n**1.59 products on the base ring. 

  

For polynomials of degree m-1 and n-1 with m<n the number of operations 

is bounded by: 

  

8.11*m**0.59*n additions and 1.56*m**0.59*n products. 

  

(The bound might be worse for larger degrees.) 

  

EXAMPLES:: 

  

sage: K.<x> = QQ[] 

sage: f = 1+3*x+4*x^2+x^3 

sage: g = x^2+3*x^5 

sage: f._mul_karatsuba(g,0) 

3*x^8 + 12*x^7 + 9*x^6 + 4*x^5 + 4*x^4 + 3*x^3 + x^2 

sage: f._mul_karatsuba(g,2) 

3*x^8 + 12*x^7 + 9*x^6 + 4*x^5 + 4*x^4 + 3*x^3 + x^2 

  

Show the product in the symbolic ring:: 

  

sage: L = SR['x'] 

sage: var('a0,a1,b0,b1') 

(a0, a1, b0, b1) 

sage: L([a0,a1])._mul_karatsuba(L([b0,b1]),0) 

a1*b1*x^2 + ((a0 + a1)*(b0 + b1) - a0*b0 - a1*b1)*x + a0*b0 

sage: L([a0,a1])._mul_karatsuba(L([b0,b1]),2) 

a1*b1*x^2 + (a1*b0 + a0*b1)*x + a0*b0 

  

A noncommutative example:: 

  

sage: A.<i,j,k> = QuaternionAlgebra(QQ, -1,-1) 

sage: R.<w> = PolynomialRing(A) 

sage: f = i*w + j 

sage: g = k*w + 1 

sage: f._mul_karatsuba(g,0) 

-j*w^2 + 2*i*w + j 

sage: g._mul_karatsuba(f,0) 

j*w^2 + j 

  

TESTS:: 

  

sage: K.<x> = QQ[] 

sage: f = K(0) 

sage: g = K.random_element(10) 

sage: f._mul_karatsuba(g,0) 

0 

sage: g._mul_karatsuba(f,0) 

0 

sage: f._mul_karatsuba(K(0),0) 

0 

sage: g._mul_generic(g) - g._mul_karatsuba(g,0) 

0 

sage: h = K(QQ.random_element(100,100)) 

sage: f._mul_karatsuba(h) 

0 

sage: K([h*c for c in g.list()]) - g._mul_generic(h) 

0 

sage: g._mul_karatsuba(h) - K([h*c for c in g.list()]) 

0 

  

Random tests for noncommutative rings:: 

  

sage: A.<i,j,k> = QuaternionAlgebra(QQ, -1,-1) 

sage: R.<w> = PolynomialRing(A) 

sage: f = R.random_element(randint(10,100)) 

sage: g = R.random_element(randint(10,100)) 

sage: f._mul_generic(g) == f._mul_karatsuba(g,0) 

True 

sage: f._mul_generic(g) == f._mul_karatsuba(g,16) 

True 

sage: g = R.random_element(0) 

sage: f._mul_karatsuba(g,0) == f._mul_generic(g) 

True 

sage: g._mul_karatsuba(f,0) == g._mul_generic(f) 

True 

  

Polynomials over matrices:: 

  

sage: K = PolynomialRing(MatrixSpace(QQ,2),'x') 

sage: f = K.random_element(randint(5,10)) 

sage: g = K.random_element(randint(5,10)) 

sage: h1 = f._mul_generic(g) 

sage: h2 = f._mul_karatsuba(g,randint(0,10)) 

sage: h1 == h2 

True 

""" 

if self.is_zero(): 

return self 

elif right.is_zero(): 

return right 

cdef list f = self.list(copy=False) 

cdef list g = right.list(copy=False) 

n = len(f) 

m = len(g) 

if n == 1: 

c = f[0] 

return self._new_generic([c*a for a in g]) 

if m == 1: 

c = g[0] 

return self._new_generic([a*c for a in f]) 

if K_threshold is None: 

K_threshold = self._parent._Karatsuba_threshold 

if n <= K_threshold or m <= K_threshold: 

return self._new_generic(do_schoolbook_product(f, g, -1)) 

if n == m: 

return self._new_generic(do_karatsuba(f,g, K_threshold, 0, 0, n)) 

return self._new_generic(do_karatsuba_different_size(f,g, K_threshold)) 

  

def base_ring(self): 

""" 

Return the base ring of the parent of self. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: x.base_ring() 

Integer Ring 

sage: (2*x+3).base_ring() 

Integer Ring 

""" 

return self._parent.base_ring() 

  

cpdef base_extend(self, R): 

""" 

Return a copy of this polynomial but with coefficients in R, if 

there is a natural map from coefficient ring of self to R. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x^3 - 17*x + 3 

sage: f.base_extend(GF(7)) 

Traceback (most recent call last): 

... 

TypeError: no such base extension 

sage: f.change_ring(GF(7)) 

x^3 + 4*x + 3 

""" 

S = self._parent.base_extend(R) 

return S(self) 

  

def change_variable_name(self, var): 

""" 

Return a new polynomial over the same base ring but in a different 

variable. 

  

EXAMPLES:: 

  

sage: x = polygen(QQ,'x') 

sage: f = -2/7*x^3 + (2/3)*x - 19/993; f 

-2/7*x^3 + 2/3*x - 19/993 

sage: f.change_variable_name('theta') 

-2/7*theta^3 + 2/3*theta - 19/993 

""" 

R = self._parent.base_ring()[var] 

return R(self.list()) 

  

def change_ring(self, R): 

""" 

Return a copy of this polynomial but with coefficients in ``R``, if at 

all possible. 

  

INPUT: 

  

- ``R`` - a ring or morphism. 

  

EXAMPLES:: 

  

sage: K.<z> = CyclotomicField(3) 

sage: f = K.defining_polynomial() 

sage: f.change_ring(GF(7)) 

x^2 + x + 1 

  

:: 

  

sage: K.<z> = CyclotomicField(3) 

sage: R.<x> = K[] 

sage: f = x^2 + z 

sage: f.change_ring(K.embeddings(CC)[0]) 

x^2 - 0.500000000000000 - 0.866025403784439*I 

""" 

if isinstance(R, Morphism): 

# we're given a hom of the base ring extend to a poly hom 

if R.domain() == self.base_ring(): 

R = self._parent.hom(R, self._parent.change_ring(R.codomain())) 

return R(self) 

else: 

return self._parent.change_ring(R)(self) 

  

def _mpoly_dict_recursive(self, variables=None, base_ring=None): 

""" 

Return a dict of coefficient entries suitable for construction of a 

MPolynomial_polydict with the given variables. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: R(0)._mpoly_dict_recursive() 

{} 

sage: f = 7*x^5 + x^2 - 2*x - 3 

sage: f._mpoly_dict_recursive() 

{(0,): -3, (1,): -2, (2,): 1, (5,): 7} 

""" 

if not self: 

return {} 

  

var = self._parent.variable_name() 

if variables is None: 

variables = self._parent.variable_names_recursive() 

if not var in variables: 

x = base_ring(self) if base_ring else self 

const_ix = ETuple((0,)*len(variables)) 

return { const_ix: x } 

  

prev_variables = variables[:list(variables).index(var)] 

const_ix = ETuple((0,)*len(prev_variables)) 

mpolys = None 

  

if len(prev_variables) > 0: 

try: 

mpolys = [a._mpoly_dict_recursive(prev_variables, base_ring) for a in self] 

except AttributeError as msg: 

pass 

  

if mpolys is None: 

if base_ring is not None and base_ring is not self.base_ring(): 

mpolys = [{const_ix:base_ring(a)} if a else {} for a in self] 

else: 

mpolys = [{const_ix:a} if a else {} for a in self] 

  

D = {} 

leftovers = (0,) * (len(variables) - len(prev_variables) - 1) 

for k in range(len(mpolys)): 

for i,a in mpolys[k].iteritems(): 

j = ETuple((k,) + leftovers) 

D[i + j] = a 

  

return D 

  

def __copy__(self): 

""" 

Return a "copy" of self. This is just self, since in Sage 

polynomials are immutable this just returns self again. 

  

EXAMPLES: 

  

We create the polynomial `f=x+3`, then note that 

the copy is just the same polynomial again, which is fine since 

polynomials are immutable. 

  

:: 

  

sage: x = ZZ['x'].0 

sage: f = x + 3 

sage: g = copy(f) 

sage: g is f 

True 

""" 

return self 

  

def degree(self, gen=None): 

""" 

Return the degree of this polynomial. The zero polynomial has 

degree -1. 

  

EXAMPLES:: 

  

sage: x = ZZ['x'].0 

sage: f = x^93 + 2*x + 1 

sage: f.degree() 

93 

sage: x = PolynomialRing(QQ, 'x', sparse=True).0 

sage: f = x^100000 

sage: f.degree() 

100000 

  

:: 

  

sage: x = QQ['x'].0 

sage: f = 2006*x^2006 - x^2 + 3 

sage: f.degree() 

2006 

sage: f = 0*x 

sage: f.degree() 

-1 

sage: f = x + 33 

sage: f.degree() 

1 

  

AUTHORS: 

  

- Naqi Jaffery (2006-01-24): examples 

""" 

raise NotImplementedError 

  

def euclidean_degree(self): 

r""" 

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

  

If this polynomial is defined over a field, this is simply its :meth:`degree`. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: x.euclidean_degree() 

1 

sage: R.<x> = ZZ[] 

sage: x.euclidean_degree() 

Traceback (most recent call last): 

... 

NotImplementedError 

  

""" 

from sage.categories.fields import Fields 

if self.base_ring() in Fields(): 

return self.degree() 

raise NotImplementedError 

  

def denominator(self): 

""" 

Return a denominator of self. 

  

First, the lcm of the denominators of the entries of self 

is computed and returned. If this computation fails, the 

unit of the parent of self is returned. 

  

Note that some subclasses may implement their own 

denominator function. For example, see 

:class:`sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint` 

  

.. warning:: 

  

This is not the denominator of the rational function 

defined by self, which would always be 1 since self is a 

polynomial. 

  

EXAMPLES: 

  

First we compute the denominator of a polynomial with 

integer coefficients, which is of course 1. 

  

:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^3 + 17*x + 1 

sage: f.denominator() 

1 

  

Next we compute the denominator of a polynomial with rational 

coefficients. 

  

:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: f = (1/17)*x^19 - (2/3)*x + 1/3; f 

1/17*x^19 - 2/3*x + 1/3 

sage: f.denominator() 

51 

  

Finally, we try to compute the denominator of a polynomial with 

coefficients in the real numbers, which is a ring whose elements do 

not have a denominator method. 

  

:: 

  

sage: R.<x> = RR[] 

sage: f = x + RR('0.3'); f 

x + 0.300000000000000 

sage: f.denominator() 

1.00000000000000 

  

Check that the denominator is an element over the base whenever the base 

has no denominator function. This closes :trac:`9063`. :: 

  

sage: R.<a> = GF(5)[] 

sage: x = R(0) 

sage: x.denominator() 

1 

sage: type(x.denominator()) 

<type 'sage.rings.finite_rings.integer_mod.IntegerMod_int'> 

sage: isinstance(x.numerator() / x.denominator(), Polynomial) 

True 

sage: isinstance(x.numerator() / R(1), Polynomial) 

False 

  

TESTS: 

  

Check that :trac:`18518` is fixed:: 

  

sage: R.<x> = PolynomialRing(QQ, sparse=True) 

sage: p = x^(2^100) - 1/2 

sage: p.denominator() 

2 

""" 

  

if self.degree() == -1: 

return self.base_ring().one() 

x = self.coefficients() 

try: 

d = x[0].denominator() 

for y in x: 

d = d.lcm(y.denominator()) 

return d 

except(AttributeError): 

return self.base_ring().one() 

  

def numerator(self): 

""" 

Return a numerator of self computed as self * self.denominator() 

  

Note that some subclases may implement its own numerator 

function. For example, see 

:class:`sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint` 

  

.. warning:: 

  

This is not the numerator of the rational function 

defined by self, which would always be self since self is a 

polynomial. 

  

EXAMPLES: 

  

First we compute the numerator of a polynomial with 

integer coefficients, which is of course self. 

  

:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^3 + 17*x + 1 

sage: f.numerator() 

x^3 + 17*x + 1 

sage: f == f.numerator() 

True 

  

Next we compute the numerator of a polynomial with rational 

coefficients. 

  

:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: f = (1/17)*x^19 - (2/3)*x + 1/3; f 

1/17*x^19 - 2/3*x + 1/3 

sage: f.numerator() 

3*x^19 - 34*x + 17 

sage: f == f.numerator() 

False 

  

We try to compute the denominator of a polynomial with 

coefficients in the real numbers, which is a ring whose elements do 

not have a denominator method. 

  

:: 

  

sage: R.<x> = RR[] 

sage: f = x + RR('0.3'); f 

x + 0.300000000000000 

sage: f.numerator() 

x + 0.300000000000000 

  

We check that the computation the numerator and denominator 

are valid 

  

:: 

  

sage: K=NumberField(symbolic_expression('x^3+2'),'a')['s,t']['x'] 

sage: f=K.random_element() 

sage: f.numerator() / f.denominator() == f 

True 

sage: R=RR['x'] 

sage: f=R.random_element() 

sage: f.numerator() / f.denominator() == f 

True 

""" 

return self * self.denominator() 

  

def derivative(self, *args): 

r""" 

The formal derivative of this polynomial, with respect to variables 

supplied in args. 

  

Multiple variables and iteration counts may be supplied; see 

documentation for the global derivative() function for more 

details. 

  

.. SEEALSO:: 

  

:meth:`_derivative` 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(QQ) 

sage: g = -x^4 + x^2/2 - x 

sage: g.derivative() 

-4*x^3 + x - 1 

sage: g.derivative(x) 

-4*x^3 + x - 1 

sage: g.derivative(x, x) 

-12*x^2 + 1 

sage: g.derivative(x, 2) 

-12*x^2 + 1 

  

:: 

  

sage: R.<t> = PolynomialRing(ZZ) 

sage: S.<x> = PolynomialRing(R) 

sage: f = t^3*x^2 + t^4*x^3 

sage: f.derivative() 

3*t^4*x^2 + 2*t^3*x 

sage: f.derivative(x) 

3*t^4*x^2 + 2*t^3*x 

sage: f.derivative(t) 

4*t^3*x^3 + 3*t^2*x^2 

""" 

return multi_derivative(self, args) 

  

# add .diff(), .differentiate() as aliases for .derivative() 

diff = differentiate = derivative 

  

def _derivative(self, var=None): 

r""" 

Return the formal derivative of this polynomial with respect to the 

variable var. 

  

If var is the generator of this polynomial ring (or the default 

value None), this is the usual formal derivative. 

  

Otherwise, _derivative(var) is called recursively for each of the 

coefficients of this polynomial. 

  

.. SEEALSO:: 

  

:meth:`derivative` 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: R(0)._derivative() 

0 

sage: parent(R(0)._derivative()) 

Univariate Polynomial Ring in x over Integer Ring 

  

:: 

  

sage: f = 7*x^5 + x^2 - 2*x - 3 

sage: f._derivative() 

35*x^4 + 2*x - 2 

sage: f._derivative(None) 

35*x^4 + 2*x - 2 

sage: f._derivative(x) 

35*x^4 + 2*x - 2 

  

In the following example, it doesn't recognise 2\*x as the 

generator, so it tries to differentiate each of the coefficients 

with respect to 2\*x, which doesn't work because the integer 

coefficients don't have a _derivative() method:: 

  

sage: f._derivative(2*x) 

Traceback (most recent call last): 

... 

AttributeError: 'sage.rings.integer.Integer' object has no attribute '_derivative' 

  

Examples illustrating recursive behaviour:: 

  

sage: R.<x> = ZZ[] 

sage: S.<y> = PolynomialRing(R) 

sage: f = x^3 + y^3 

sage: f._derivative() 

3*y^2 

sage: f._derivative(y) 

3*y^2 

sage: f._derivative(x) 

3*x^2 

  

:: 

  

sage: R = ZZ['x'] 

sage: S = R.fraction_field(); x = S.gen() 

sage: R(1).derivative(R(x)) 

0 

""" 

if var is not None and var != self._parent.gen(): 

# call _derivative() recursively on coefficients 

return self._parent([coeff._derivative(var) for coeff in self.list(copy=False)]) 

  

# compute formal derivative with respect to generator 

if self.is_zero(): 

return self 

cdef Py_ssize_t n, degree = self.degree() 

if degree == 0: 

return self._parent.zero() 

coeffs = self.list(copy=False) 

return self._new_generic([n*coeffs[n] for n from 1 <= n <= degree]) 

  

def gradient(self): 

""" 

Return a list of the partial derivative of ``self`` 

with respect to the variable of this univariate polynomial. 

  

There is only one partial derivative. 

  

EXAMPLES:: 

  

sage: P.<x> = QQ[] 

sage: f = x^2 + (2/3)*x + 1 

sage: f.gradient() 

[2*x + 2/3] 

sage: f = P(1) 

sage: f.gradient() 

[0] 

""" 

return [self.diff()] 

  

def integral(self,var=None): 

""" 

Return the integral of this polynomial. 

  

By default, the integration variable is the variable of the 

polynomial. 

  

Otherwise, the integration variable is the optional parameter ``var`` 

  

.. NOTE:: 

  

The integral is always chosen so that the constant term is 0. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: R(0).integral() 

0 

sage: f = R(2).integral(); f 

2*x 

  

Note that the integral lives over the fraction field of the 

scalar coefficients:: 

  

sage: f.parent() 

Univariate Polynomial Ring in x over Rational Field 

sage: R(0).integral().parent() 

Univariate Polynomial Ring in x over Rational Field 

  

sage: f = x^3 + x - 2 

sage: g = f.integral(); g 

1/4*x^4 + 1/2*x^2 - 2*x 

sage: g.parent() 

Univariate Polynomial Ring in x over Rational Field 

  

This shows that the issue at :trac:`7711` is resolved:: 

  

sage: P.<x,z> = PolynomialRing(GF(2147483647)) 

sage: Q.<y> = PolynomialRing(P) 

sage: p=x+y+z 

sage: p.integral() 

-1073741823*y^2 + (x + z)*y 

  

sage: P.<x,z> = PolynomialRing(GF(next_prime(2147483647))) 

sage: Q.<y> = PolynomialRing(P) 

sage: p=x+y+z 

sage: p.integral() 

1073741830*y^2 + (x + z)*y 

  

A truly convoluted example:: 

  

sage: A.<a1, a2> = PolynomialRing(ZZ) 

sage: B.<b> = PolynomialRing(A) 

sage: C.<c> = PowerSeriesRing(B) 

sage: R.<x> = PolynomialRing(C) 

sage: f = a2*x^2 + c*x - a1*b 

sage: f.parent() 

Univariate Polynomial Ring in x over Power Series Ring in c 

over Univariate Polynomial Ring in b over Multivariate Polynomial 

Ring in a1, a2 over Integer Ring 

sage: f.integral() 

1/3*a2*x^3 + 1/2*c*x^2 - a1*b*x 

sage: f.integral().parent() 

Univariate Polynomial Ring in x over Power Series Ring in c 

over Univariate Polynomial Ring in b over Multivariate Polynomial 

Ring in a1, a2 over Rational Field 

sage: g = 3*a2*x^2 + 2*c*x - a1*b 

sage: g.integral() 

a2*x^3 + c*x^2 - a1*b*x 

sage: g.integral().parent() 

Univariate Polynomial Ring in x over Power Series Ring in c 

over Univariate Polynomial Ring in b over Multivariate Polynomial 

Ring in a1, a2 over Rational Field 

  

Integration with respect to a variable in the base ring:: 

  

sage: R.<x> = QQ[] 

sage: t = PolynomialRing(R,'t').gen() 

sage: f = x*t +5*t^2 

sage: f.integral(x) 

5*x*t^2 + 1/2*x^2*t 

  

TESTS: 

  

Check that :trac:`18600` is fixed:: 

  

sage: Sx.<x> = ZZ[] 

sage: Sxy.<y> = Sx[] 

sage: Sxyz.<z> = Sxy[] 

sage: p = 1 + x*y + x*z + y*z^2 

sage: q = p.integral() 

sage: q 

1/3*y*z^3 + 1/2*x*z^2 + (x*y + 1)*z 

sage: q.parent() 

Univariate Polynomial Ring in z over Univariate Polynomial Ring in y 

over Univariate Polynomial Ring in x over Rational Field 

sage: q.derivative() == p 

True 

sage: p.integral(y) 

1/2*y^2*z^2 + x*y*z + 1/2*x*y^2 + y 

sage: p.integral(y).derivative(y) == p 

True 

sage: p.integral(x).derivative(x) == p 

True 

  

Check that it works with non-integral domains (:trac:`18600`):: 

  

sage: x = polygen(Zmod(4)) 

sage: p = x**4 + 1 

sage: p.integral() 

x^5 + x 

sage: p.integral().derivative() == p 

True 

""" 

R = self._parent 

  

# TODO: 

# calling the coercion model bin_op is much more accurate than using the 

# true division (which is bypassed by polynomials). But it does not work 

# in all cases!! 

cm = coercion_model 

try: 

S = cm.bin_op(R.one(), ZZ.one(), operator.truediv).parent() 

Q = S.base_ring() 

except TypeError: 

Q = (R.base_ring().one()/ZZ.one()).parent() 

S = R.change_ring(Q) 

if var is not None and var != R.gen(): 

# call integral() recursively on coefficients 

return S([coeff.integral(var) for coeff in self]) 

cdef Py_ssize_t n 

zero = Q.zero() 

p = [zero] + [cm.bin_op(Q(self[n]), n + 1, operator.truediv) 

if self[n] else zero for n in range(self.degree() + 1)] 

return S(p) 

  

def dict(self): 

""" 

Return a sparse dictionary representation of this univariate 

polynomial. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x^3 + -1/7*x + 13 

sage: f.dict() 

{0: 13, 1: -1/7, 3: 1} 

""" 

X = {} 

Y = self.list(copy=False) 

for i in xrange(len(Y)): 

c = Y[i] 

if c: 

X[i] = c 

return X 

  

def factor(self, **kwargs): 

r""" 

Return the factorization of ``self`` over its base ring. 

  

INPUT: 

  

- ``kwargs`` -- any keyword arguments are passed to the method 

``_factor_univariate_polynomial()`` of the base ring if it 

defines such a method. 

  

OUTPUT: 

  

- A factorization of ``self`` over its parent into a unit and 

irreducible factors. If the parent is a polynomial ring 

over a field, these factors are monic. 

  

EXAMPLES: 

  

Factorization is implemented over various rings. Over `\QQ`:: 

  

sage: x = QQ['x'].0 

sage: f = (x^3 - 1)^2 

sage: f.factor() 

(x - 1)^2 * (x^2 + x + 1)^2 

  

Since `\QQ` is a field, the irreducible factors are monic:: 

  

sage: f = 10*x^5 - 1 

sage: f.factor() 

(10) * (x^5 - 1/10) 

sage: f = 10*x^5 - 10 

sage: f.factor() 

(10) * (x - 1) * (x^4 + x^3 + x^2 + x + 1) 

  

Over `\ZZ` the irreducible factors need not be monic:: 

  

sage: x = ZZ['x'].0 

sage: f = 10*x^5 - 1 

sage: f.factor() 

10*x^5 - 1 

  

We factor a non-monic polynomial over a finite field of 25 

elements:: 

  

sage: k.<a> = GF(25) 

sage: R.<x> = k[] 

sage: f = 2*x^10 + 2*x + 2*a 

sage: F = f.factor(); F 

(2) * (x + a + 2) * (x^2 + 3*x + 4*a + 4) * (x^2 + (a + 1)*x + a + 2) * (x^5 + (3*a + 4)*x^4 + (3*a + 3)*x^3 + 2*a*x^2 + (3*a + 1)*x + 3*a + 1) 

  

Notice that the unit factor is included when we multiply `F` 

back out:: 

  

sage: expand(F) 

2*x^10 + 2*x + 2*a 

  

A new ring. In the example below, we set the special method 

``_factor_univariate_polynomial()`` in the base ring which is 

called to factor univariate polynomials. This facility can be 

used to easily extend polynomial factorization to work over 

new rings you introduce:: 

  

sage: R.<x> = PolynomialRing(IntegerModRing(4),implementation="NTL") 

sage: (x^2).factor() 

Traceback (most recent call last): 

... 

NotImplementedError: factorization of polynomials over rings with composite characteristic is not implemented 

sage: R.base_ring()._factor_univariate_polynomial = lambda f: f.change_ring(ZZ).factor() 

sage: (x^2).factor() 

x^2 

sage: del R.base_ring()._factor_univariate_polynomial # clean up 

  

Arbitrary precision real and complex factorization:: 

  

sage: R.<x> = RealField(100)[] 

sage: F = factor(x^2-3); F 

(x - 1.7320508075688772935274463415) * (x + 1.7320508075688772935274463415) 

sage: expand(F) 

x^2 - 3.0000000000000000000000000000 

sage: factor(x^2 + 1) 

x^2 + 1.0000000000000000000000000000 

  

sage: R.<x> = ComplexField(100)[] 

sage: F = factor(x^2+3); F 

(x - 1.7320508075688772935274463415*I) * (x + 1.7320508075688772935274463415*I) 

sage: expand(F) 

x^2 + 3.0000000000000000000000000000 

sage: factor(x^2+1) 

(x - I) * (x + I) 

sage: f = R(I) * (x^2 + 1) ; f 

I*x^2 + I 

sage: F = factor(f); F 

(1.0000000000000000000000000000*I) * (x - I) * (x + I) 

sage: expand(F) 

I*x^2 + I 

  

Over a number field:: 

  

sage: K.<z> = CyclotomicField(15) 

sage: x = polygen(K) 

sage: ((x^3 + z*x + 1)^3*(x - z)).factor() 

(x - z) * (x^3 + z*x + 1)^3 

sage: cyclotomic_polynomial(12).change_ring(K).factor() 

(x^2 - z^5 - 1) * (x^2 + z^5) 

sage: ((x^3 + z*x + 1)^3*(x/(z+2) - 1/3)).factor() 

(-1/331*z^7 + 3/331*z^6 - 6/331*z^5 + 11/331*z^4 - 21/331*z^3 + 41/331*z^2 - 82/331*z + 165/331) * (x - 1/3*z - 2/3) * (x^3 + z*x + 1)^3 

  

Over a relative number field:: 

  

sage: x = polygen(QQ) 

sage: K.<z> = CyclotomicField(3) 

sage: L.<a> = K.extension(x^3 - 2) 

sage: t = polygen(L, 't') 

sage: f = (t^3 + t + a)*(t^5 + t + z); f 

t^8 + t^6 + a*t^5 + t^4 + z*t^3 + t^2 + (a + z)*t + z*a 

sage: f.factor() 

(t^3 + t + a) * (t^5 + t + z) 

  

Over the real double field:: 

  

sage: R.<x> = RDF[] 

sage: (-2*x^2 - 1).factor() 

(-2.0) * (x^2 + 0.5000000000000001) 

sage: (-2*x^2 - 1).factor().expand() 

-2.0*x^2 - 1.0000000000000002 

sage: f = (x - 1)^3 

sage: f.factor() # abs tol 2e-5 

(x - 1.0000065719436413) * (x^2 - 1.9999934280563585*x + 0.9999934280995487) 

  

The above output is incorrect because it relies on the 

:meth:`.roots` method, which does not detect that all the roots 

are real:: 

  

sage: f.roots() # abs tol 2e-5 

[(1.0000065719436413, 1)] 

  

Over the complex double field the factors are approximate and 

therefore occur with multiplicity 1:: 

  

sage: R.<x> = CDF[] 

sage: f = (x^2 + 2*R(I))^3 

sage: F = f.factor() 

sage: F # abs tol 3e-5 

(x - 1.0000138879287663 + 1.0000013435286879*I) * (x - 0.9999942196864997 + 0.9999873009803959*I) * (x - 0.9999918923847313 + 1.0000113554909125*I) * (x + 0.9999908759550227 - 1.0000069659624138*I) * (x + 0.9999985293216753 - 0.9999886153831807*I) * (x + 1.0000105947233 - 1.0000044186544053*I) 

sage: [f(t[0][0]).abs() for t in F] # abs tol 1e-13 

[1.979365054e-14, 1.97936298566e-14, 1.97936990747e-14, 3.6812407475e-14, 3.65211563729e-14, 3.65220890052e-14] 

  

Factoring polynomials over `\ZZ/n\ZZ` for 

composite `n` is not implemented:: 

  

sage: R.<x> = PolynomialRing(Integers(35)) 

sage: f = (x^2+2*x+2)*(x^2+3*x+9) 

sage: f.factor() 

Traceback (most recent call last): 

... 

NotImplementedError: factorization of polynomials over rings with composite characteristic is not implemented 

  

Factoring polynomials over the algebraic numbers (see 

:trac:`8544`):: 

  

sage: R.<x> = QQbar[] 

sage: (x^8-1).factor() 

(x - 1) * (x - 0.7071067811865475? - 0.7071067811865475?*I) * (x - 0.7071067811865475? + 0.7071067811865475?*I) * (x - I) * (x + I) * (x + 0.7071067811865475? - 0.7071067811865475?*I) * (x + 0.7071067811865475? + 0.7071067811865475?*I) * (x + 1) 

  

Factoring polynomials over the algebraic reals (see 

:trac:`8544`):: 

  

sage: R.<x> = AA[] 

sage: (x^8+1).factor() 

(x^2 - 1.847759065022574?*x + 1.000000000000000?) * (x^2 - 0.7653668647301795?*x + 1.000000000000000?) * (x^2 + 0.7653668647301795?*x + 1.000000000000000?) * (x^2 + 1.847759065022574?*x + 1.000000000000000?) 

  

TESTS: 

  

This came up in :trac:`7088`:: 

  

sage: R.<x>=PolynomialRing(ZZ) 

sage: f = 12*x^10 + x^9 + 432*x^3 + 9011 

sage: g = 13*x^11 + 89*x^3 + 1 

sage: F = f^2 * g^3 

sage: F = f^2 * g^3; F.factor() 

(12*x^10 + x^9 + 432*x^3 + 9011)^2 * (13*x^11 + 89*x^3 + 1)^3 

sage: F = f^2 * g^3 * 7; F.factor() 

7 * (12*x^10 + x^9 + 432*x^3 + 9011)^2 * (13*x^11 + 89*x^3 + 1)^3 

  

This example came up in :trac:`7097`:: 

  

sage: x = polygen(QQ) 

sage: f = 8*x^9 + 42*x^6 + 6*x^3 - 1 

sage: g = x^24 - 12*x^23 + 72*x^22 - 286*x^21 + 849*x^20 - 2022*x^19 + 4034*x^18 - 6894*x^17 + 10182*x^16 - 13048*x^15 + 14532*x^14 - 13974*x^13 + 11365*x^12 - 7578*x^11 + 4038*x^10 - 1766*x^9 + 762*x^8 - 408*x^7 + 236*x^6 - 126*x^5 + 69*x^4 - 38*x^3 + 18*x^2 - 6*x + 1 

sage: assert g.is_irreducible() 

sage: K.<a> = NumberField(g) 

sage: len(f.roots(K)) 

9 

sage: f.factor() 

(8) * (x^3 + 1/4) * (x^6 + 5*x^3 - 1/2) 

sage: f.change_ring(K).factor() 

(8) * (x - 3260097/3158212*a^22 + 35861067/3158212*a^21 - 197810817/3158212*a^20 + 722970825/3158212*a^19 - 1980508347/3158212*a^18 + 4374189477/3158212*a^17 - 4059860553/1579106*a^16 + 6442403031/1579106*a^15 - 17542341771/3158212*a^14 + 20537782665/3158212*a^13 - 20658463789/3158212*a^12 + 17502836649/3158212*a^11 - 11908953451/3158212*a^10 + 6086953981/3158212*a^9 - 559822335/789553*a^8 + 194545353/789553*a^7 - 505969453/3158212*a^6 + 338959407/3158212*a^5 - 155204647/3158212*a^4 + 79628015/3158212*a^3 - 57339525/3158212*a^2 + 26692783/3158212*a - 1636338/789553) * ... 

sage: f = QQbar['x'](1) 

sage: f.factor() 

1 

  

Factorization also works even if the variable of the finite 

field is nefariously labeled "x":: 

  

sage: R.<x> = GF(3^2, 'x')[] 

sage: f = x^10 +7*x -13 

sage: G = f.factor(); G 

(x + x) * (x + 2*x + 1) * (x^4 + (x + 2)*x^3 + (2*x + 2)*x + 2) * (x^4 + 2*x*x^3 + (x + 1)*x + 2) 

sage: prod(G) == f 

True 

  

:: 

  

sage: R.<x0> = GF(9,'x')[] # purposely calling it x to test robustness 

sage: f = x0^3 + x0 + 1 

sage: f.factor() 

(x0 + 2) * (x0 + x) * (x0 + 2*x + 1) 

sage: f = 0*x0 

sage: f.factor() 

Traceback (most recent call last): 

... 

ArithmeticError: factorization of 0 is not defined 

  

:: 

  

sage: f = x0^0 

sage: f.factor() 

1 

  

Over a complicated number field:: 

  

sage: x = polygen(QQ, 'x') 

sage: f = x^6 + 10/7*x^5 - 867/49*x^4 - 76/245*x^3 + 3148/35*x^2 - 25944/245*x + 48771/1225 

sage: K.<a> = NumberField(f) 

sage: S.<T> = K[] 

sage: ff = S(f); ff 

T^6 + 10/7*T^5 - 867/49*T^4 - 76/245*T^3 + 3148/35*T^2 - 25944/245*T + 48771/1225 

sage: F = ff.factor() 

sage: len(F) 

4 

sage: F[:2] 

[(T - a, 1), (T - 40085763200/924556084127*a^5 - 145475769880/924556084127*a^4 + 527617096480/924556084127*a^3 + 1289745809920/924556084127*a^2 - 3227142391585/924556084127*a - 401502691578/924556084127, 1)] 

sage: expand(F) 

T^6 + 10/7*T^5 - 867/49*T^4 - 76/245*T^3 + 3148/35*T^2 - 25944/245*T + 48771/1225 

  

:: 

  

sage: f = x^2 - 1/3 

sage: K.<a> = NumberField(f) 

sage: A.<T> = K[] 

sage: A(x^2 - 1).factor() 

(T - 1) * (T + 1) 

  

  

:: 

  

sage: A(3*x^2 - 1).factor() 

(3) * (T - a) * (T + a) 

  

:: 

  

sage: A(x^2 - 1/3).factor() 

(T - a) * (T + a) 

  

Test that :trac:`10279` is fixed:: 

  

sage: R.<t> = PolynomialRing(QQ) 

sage: K.<a> = NumberField(t^4 - t^2 + 1) 

sage: pol = t^3 + (-4*a^3 + 2*a)*t^2 - 11/3*a^2*t + 2/3*a^3 - 4/3*a 

sage: pol.factor() 

(t - 2*a^3 + a) * (t - 4/3*a^3 + 2/3*a) * (t - 2/3*a^3 + 1/3*a) 

  

Test that this factorization really uses ``nffactor()`` internally:: 

  

sage: pari.default("debug", 3) 

sage: F = pol.factor() 

<BLANKLINE> 

Entering nffactor: 

... 

sage: pari.default("debug", 0) 

  

Test that :trac:`10369` is fixed:: 

  

sage: x = polygen(QQ) 

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

sage: R.<t> = PolynomialRing(K) 

  

sage: pol = (-1/7*a^5 - 1/7*a^4 - 1/7*a^3 - 1/7*a^2 - 2/7*a - 1/7)*t^10 + (4/7*a^5 - 2/7*a^4 - 2/7*a^3 - 2/7*a^2 - 2/7*a - 6/7)*t^9 + (90/49*a^5 + 152/49*a^4 + 18/49*a^3 + 24/49*a^2 + 30/49*a + 36/49)*t^8 + (-10/49*a^5 + 10/7*a^4 + 198/49*a^3 - 102/49*a^2 - 60/49*a - 26/49)*t^7 + (40/49*a^5 + 45/49*a^4 + 60/49*a^3 + 277/49*a^2 - 204/49*a - 78/49)*t^6 + (90/49*a^5 + 110/49*a^4 + 2*a^3 + 80/49*a^2 + 46/7*a - 30/7)*t^5 + (30/7*a^5 + 260/49*a^4 + 250/49*a^3 + 232/49*a^2 + 32/7*a + 8)*t^4 + (-184/49*a^5 - 58/49*a^4 - 52/49*a^3 - 66/49*a^2 - 72/49*a - 72/49)*t^3 + (18/49*a^5 - 32/49*a^4 + 10/49*a^3 + 4/49*a^2)*t^2 + (2/49*a^4 - 4/49*a^3 + 2/49*a^2)*t 

sage: pol.factor() 

(-1/7*a^5 - 1/7*a^4 - 1/7*a^3 - 1/7*a^2 - 2/7*a - 1/7) * t * (t - a^5 - a^4 - a^3 - a^2 - a - 1)^4 * (t^5 + (-12/7*a^5 - 10/7*a^4 - 8/7*a^3 - 6/7*a^2 - 4/7*a - 2/7)*t^4 + (12/7*a^5 - 8/7*a^3 + 16/7*a^2 + 2/7*a + 20/7)*t^3 + (-20/7*a^5 - 20/7*a^3 - 20/7*a^2 + 4/7*a - 2)*t^2 + (12/7*a^5 + 12/7*a^3 + 2/7*a + 16/7)*t - 4/7*a^5 - 4/7*a^3 - 4/7*a - 2/7) 

  

sage: pol = (1/7*a^2 - 1/7*a)*t^10 + (4/7*a - 6/7)*t^9 + (102/49*a^5 + 99/49*a^4 + 96/49*a^3 + 93/49*a^2 + 90/49*a + 150/49)*t^8 + (-160/49*a^5 - 36/49*a^4 - 48/49*a^3 - 8/7*a^2 - 60/49*a - 60/49)*t^7 + (30/49*a^5 - 55/49*a^4 + 20/49*a^3 + 5/49*a^2)*t^6 + (6/49*a^4 - 12/49*a^3 + 6/49*a^2)*t^5 

sage: pol.factor() 

(1/7*a^2 - 1/7*a) * t^5 * (t^5 + (-40/7*a^5 - 38/7*a^4 - 36/7*a^3 - 34/7*a^2 - 32/7*a - 30/7)*t^4 + (60/7*a^5 - 30/7*a^4 - 18/7*a^3 - 9/7*a^2 - 3/7*a)*t^3 + (60/7*a^4 - 40/7*a^3 - 16/7*a^2 - 4/7*a)*t^2 + (30/7*a^3 - 25/7*a^2 - 5/7*a)*t + 6/7*a^2 - 6/7*a) 

  

sage: pol = x^10 + (4/7*a - 6/7)*x^9 + (9/49*a^2 - 3/7*a + 15/49)*x^8 + (8/343*a^3 - 32/343*a^2 + 40/343*a - 20/343)*x^7 + (5/2401*a^4 - 20/2401*a^3 + 40/2401*a^2 - 5/343*a + 15/2401)*x^6 + (-6/16807*a^4 + 12/16807*a^3 - 18/16807*a^2 + 12/16807*a - 6/16807)*x^5 

sage: pol.factor() 

x^5 * (x^5 + (4/7*a - 6/7)*x^4 + (9/49*a^2 - 3/7*a + 15/49)*x^3 + (8/343*a^3 - 32/343*a^2 + 40/343*a - 20/343)*x^2 + (5/2401*a^4 - 20/2401*a^3 + 40/2401*a^2 - 5/343*a + 15/2401)*x - 6/16807*a^4 + 12/16807*a^3 - 18/16807*a^2 + 12/16807*a - 6/16807) 

  

Factoring over a number field over which we cannot factor the 

discriminant by trial division:: 

  

sage: x = polygen(QQ) 

sage: K.<a> = NumberField(x^16 - x - 6) 

sage: R.<x> = PolynomialRing(K) 

sage: f = (x+a)^50 - (a-1)^50 

sage: len(factor(f)) 

6 

sage: pari(K.discriminant()).factor(limit=10^6) 

[-1, 1; 3, 15; 23, 1; 887, 1; 12583, 1; 2354691439917211, 1] 

sage: factor(K.discriminant()) 

-1 * 3^15 * 23 * 887 * 12583 * 6335047 * 371692813 

  

Factoring over a number field over which we cannot factor the 

discriminant and over which `nffactor()` fails:: 

  

sage: p = next_prime(10^50); q = next_prime(10^51); n = p*q; 

sage: K.<a> = QuadraticField(p*q) 

sage: R.<x> = PolynomialRing(K) 

sage: K.pari_polynomial('a').nffactor("x^2+1") 

Mat([x^2 + 1, 1]) 

sage: factor(x^2 + 1) 

x^2 + 1 

sage: factor( (x - a) * (x + 2*a) ) 

(x - a) * (x + 2*a) 

  

A test where nffactor used to fail without a nf structure:: 

  

sage: x = polygen(QQ) 

sage: K = NumberField([x^2-1099511627777, x^3-3],'a') 

sage: x = polygen(K) 

sage: f = x^3 - 3 

sage: factor(f) 

(x - a1) * (x^2 + a1*x + a1^2) 

  

We check that :trac:`7554` is fixed:: 

  

sage: L.<q> = LaurentPolynomialRing(QQ) 

sage: F = L.fraction_field() 

sage: R.<x> = PolynomialRing(F) 

sage: factor(x) 

x 

sage: factor(x^2 - q^2) 

(x - q) * (x + q) 

sage: factor(x^2 - q^-2) 

(x - 1/q) * (x + 1/q) 

  

sage: P.<a,b,c> = PolynomialRing(ZZ) 

sage: R.<x> = PolynomialRing(FractionField(P)) 

sage: p = (x - a)*(b*x + c)*(a*b*x + a*c) / (a + 2) 

sage: factor(p) 

(a/(a + 2)) * (x - a) * (b*x + c)^2 

""" 

# PERFORMANCE NOTE: 

# In many tests with SMALL degree PARI is substantially 

# better than NTL. (And magma is better yet.) And the 

# timing difference has nothing to do with moving Python 

# data to NTL and back. 

# For large degree ( > 1500) in the one test I tried, NTL was 

# *much* better than MAGMA, and far better than PARI. So probably 

# NTL's implementation is asymptotically better. I could use 

# PARI for smaller degree over other rings besides Z, and use 

# NTL in general. 

# A remark from Bill Hart (2007-09-25) about the above observation: 

## NTL uses the Berlekamp-Zassenhaus method with van Hoeij's improvements. 

## But so does Magma since about Jul 2001. 

## 

## But here's the kicker. PARI also uses this algorithm. Even Maple uses 

## it! 

## 

## NTL's LLL algorithms are extremely well developed (van Hoeij uses 

## LLL). There is also a possible speed difference in whether one uses 

## quadratic convergence or not in the Hensel lift. But the right choice 

## is not always what one thinks. 

## 

## But more than likely NTL is just better for large problems because 

## Victor Shoup was very careful with the choice of strategies and 

## parameters he used. Paul Zimmerman supplied him with a pile of 

## polynomials to factor for comparison purposes and these seem to have 

## been used to tune the algorithm for a wide range of inputs, including 

## cases that van Hoeij's algorithm doesn't usually like. 

## 

## If you have a bound on the coefficients of the factors, one can surely 

## do better than a generic implementation, but probably not much better 

## if there are many factors. 

## 

  

## HUGE TODO, refactor the code below here such that this method will 

## have as only the following code 

## 

## R = self.parent().base_ring() 

## return R._factor_univariate_polynomial(self) 

## 

## in this way we can move the specific logic of factoring to the 

## self.parent().base_ring() and get rid of all the ugly 

## is_SomeType(R) checks and get way nicer structured code 

## 200 lines of spagetti code is just way to much! 

  

if self.degree() < 0: 

raise ArithmeticError("factorization of {!r} is not defined".format(self)) 

if self.degree() == 0: 

return Factorization([], unit=self[0]) 

  

# Use multivariate implementations for polynomials over polynomial rings 

variables = self._parent.variable_names_recursive() 

if len(variables) > 1: 

base = self._parent._mpoly_base_ring() 

ring = PolynomialRing(base, variables) 

if ring._has_singular: 

try: 

d = self._mpoly_dict_recursive() 

F = ring(d).factor(**kwargs) 

return Factorization([(self._parent(f),m) for (f,m) in F], unit = F.unit()) 

except NotImplementedError: 

pass 

  

R = self._parent.base_ring() 

if hasattr(R, '_factor_univariate_polynomial'): 

return R._factor_univariate_polynomial(self, **kwargs) 

  

G = None 

ch = R.characteristic() 

if not (ch == 0 or is_prime(ch)): 

raise NotImplementedError("factorization of polynomials over rings with composite characteristic is not implemented") 

  

from sage.rings.number_field.number_field_base import is_NumberField 

from sage.rings.number_field.number_field_rel import is_RelativeNumberField 

from sage.rings.number_field.all import NumberField 

from sage.rings.finite_rings.finite_field_constructor import is_FiniteField 

from sage.rings.finite_rings.integer_mod_ring import is_IntegerModRing 

from sage.rings.integer_ring import is_IntegerRing 

  

n = None 

  

if is_IntegerModRing(R) or is_IntegerRing(R): 

try: 

G = list(self._pari_with_name().factor()) 

except PariError: 

raise NotImplementedError 

  

elif is_RelativeNumberField(R): 

  

M = R.absolute_field('a') 

from_M, to_M = M.structure() 

g = M['x']([to_M(x) for x in self.list()]) 

F = g.factor() 

S = self._parent 

v = [(S([from_M(x) for x in f.list()]), e) for f, e in F] 

return Factorization(v, from_M(F.unit())) 

  

elif is_FiniteField(R): 

v = [x.__pari__("a") for x in self.list()] 

f = pari(v).Polrev() 

G = list(f.factor()) 

  

elif is_NumberField(R): 

if R.degree() == 1: 

factors = self.change_ring(QQ).factor() 

return Factorization([(self._parent(p), e) for p, e in factors], R(factors.unit())) 

  

# Convert the polynomial we want to factor to PARI 

f = self._pari_with_name() 

try: 

# Try to compute the PARI nf structure with important=False. 

# This will raise RuntimeError if the computation is too 

# difficult. 

Rpari = R.pari_nf(important=False) 

except RuntimeError: 

# Cannot easily compute the nf structure, use the defining 

# polynomial instead. 

Rpari = R.pari_polynomial("y") 

G = list(Rpari.nffactor(f)) 

# PARI's nffactor() ignores the unit, _factor_pari_helper() 

# adds back the unit of the factorization. 

return self._factor_pari_helper(G) 

  

if G is None: 

# See if we can do this as a singular polynomial as a fallback 

# This was copied from the general multivariate implementation 

try: 

if R.is_finite(): 

if R.characteristic() > 1<<29: 

raise NotImplementedError("Factorization of multivariate polynomials over prime fields with characteristic > 2^29 is not implemented.") 

  

P = self._parent 

P._singular_().set_ring() 

S = self._singular_().factorize() 

factors = S[1] 

exponents = S[2] 

v = sorted([( P(factors[i+1]), 

sage.rings.integer.Integer(exponents[i+1])) 

for i in range(len(factors))]) 

unit = P.one() 

for i in range(len(v)): 

if v[i][0].is_unit(): 

unit = unit * v[i][0] 

del v[i] 

break 

F = Factorization(v, unit=unit) 

F.sort() 

return F 

except (TypeError, AttributeError): 

raise NotImplementedError 

  

return self._factor_pari_helper(G, n) 

  

def _factor_pari_helper(self, G, n=None, unit=None): 

""" 

Fix up and normalize a factorization that came from PARI. 

  

TESTS:: 

  

sage: R.<x>=PolynomialRing(ZZ) 

sage: f = (2*x + 1) * (3*x^2 - 5)^2 

sage: f._factor_pari_helper(pari(f).factor()) 

(2*x + 1) * (3*x^2 - 5)^2 

sage: f._factor_pari_helper(pari(f).factor(), unit=11) 

11 * (2*x + 1) * (3*x^2 - 5)^2 

sage: (8*f)._factor_pari_helper(pari(f).factor()) 

8 * (2*x + 1) * (3*x^2 - 5)^2 

sage: (8*f)._factor_pari_helper(pari(f).factor(), unit=11) 

88 * (2*x + 1) * (3*x^2 - 5)^2 

sage: QQ['x'](f)._factor_pari_helper(pari(f).factor()) 

(18) * (x + 1/2) * (x^2 - 5/3)^2 

sage: QQ['x'](f)._factor_pari_helper(pari(f).factor(), unit=11) 

(198) * (x + 1/2) * (x^2 - 5/3)^2 

  

sage: f = prod((k^2*x^k + k)^(k-1) for k in primes(10)) 

sage: F = f._factor_pari_helper(pari(f).factor()); F 

1323551250 * (2*x^2 + 1) * (3*x^3 + 1)^2 * (5*x^5 + 1)^4 * (7*x^7 + 1)^6 

sage: F.prod() == f 

True 

sage: QQ['x'](f)._factor_pari_helper(pari(f).factor()) 

(1751787911376562500) * (x^2 + 1/2) * (x^3 + 1/3)^2 * (x^5 + 1/5)^4 * (x^7 + 1/7)^6 

  

sage: g = GF(19)['x'](f) 

sage: G = g._factor_pari_helper(pari(g).factor()); G 

(4) * (x + 3) * (x + 16)^5 * (x + 11)^6 * (x^2 + 7*x + 9)^4 * (x^2 + 15*x + 9)^4 * (x^3 + 13)^2 * (x^6 + 8*x^5 + 7*x^4 + 18*x^3 + 11*x^2 + 12*x + 1)^6 

sage: G.prod() == g 

True 

""" 

pols = G[0] 

exps = G[1] 

R = self._parent 

F = [(R(f), int(e)) for f, e in zip(pols, exps)] 

  

if unit is None: 

unit = self.leading_coefficient() 

else: 

unit *= self.leading_coefficient() 

  

if R.base_ring().is_field(): 

# When the base ring is a field we normalize 

# the irreducible factors so they have leading 

# coefficient 1. 

for i, (f, e) in enumerate(F): 

if not f.is_monic(): 

F[i] = (f.monic(), e) 

  

else: 

# Otherwise we have to adjust for 

# the content ignored by PARI. 

content_fix = R.base_ring().one() 

for f, e in F: 

if not f.is_monic(): 

content_fix *= f.leading_coefficient()**e 

unit //= content_fix 

if not unit.is_unit(): 

F.append((R(unit), ZZ(1))) 

unit = R.base_ring().one() 

  

if not n is None: 

pari.set_real_precision(n) # restore precision 

return Factorization(F, unit) 

  

def splitting_field(self, names=None, map=False, **kwds): 

""" 

Compute the absolute splitting field of a given polynomial. 

  

INPUT: 

  

- ``names`` -- (default: ``None``) a variable name for the splitting field. 

  

- ``map`` -- (default: ``False``) also return an embedding of 

``self`` into the resulting field. 

  

- ``kwds`` -- additional keywords depending on the type. 

Currently, only number fields are implemented. See 

:func:`sage.rings.number_field.splitting_field.splitting_field` 

for the documentation of these keywords. 

  

OUTPUT: 

  

If ``map`` is ``False``, the splitting field as an absolute field. 

If ``map`` is ``True``, a tuple ``(K, phi)`` where ``phi`` is an 

embedding of the base field of ``self`` in ``K``. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

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

Number Field in a with defining polynomial x^6 + 3*x^5 + 6*x^4 + 11*x^3 + 12*x^2 - 3*x + 1 

sage: K.<a> = (x^3 - 3*x + 1).splitting_field(); K 

Number Field in a with defining polynomial x^3 - 3*x + 1 

  

Relative situation:: 

  

sage: R.<x> = PolynomialRing(QQ) 

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

sage: S.<t> = PolynomialRing(K) 

sage: L.<b> = (t^2 - a).splitting_field() 

sage: L 

Number Field in b with defining polynomial t^6 + 2 

  

With ``map=True``, we also get the embedding of the base field 

into the splitting field:: 

  

sage: L.<b>, phi = (t^2 - a).splitting_field(map=True) 

sage: phi 

Ring morphism: 

From: Number Field in a with defining polynomial x^3 + 2 

To: Number Field in b with defining polynomial t^6 + 2 

Defn: a |--> b^2 

  

An example over a finite field:: 

  

sage: P.<x> = PolynomialRing(GF(7)) 

sage: t = x^2 + 1 

sage: t.splitting_field('b') 

Finite Field in b of size 7^2 

  

sage: P.<x> = PolynomialRing(GF(7^3, 'a')) 

sage: t = x^2 + 1 

sage: t.splitting_field('b', map=True) 

(Finite Field in b of size 7^6, 

Ring morphism: 

From: Finite Field in a of size 7^3 

To: Finite Field in b of size 7^6 

Defn: a |--> 2*b^4 + 6*b^3 + 2*b^2 + 3*b + 2) 

  

If the extension is trivial and the generators have the same 

name, the map will be the identity:: 

  

sage: t = 24*x^13 + 2*x^12 + 14 

sage: t.splitting_field('a', map=True) 

(Finite Field in a of size 7^3, 

Identity endomorphism of Finite Field in a of size 7^3) 

  

sage: t = x^56 - 14*x^3 

sage: t.splitting_field('b', map=True) 

(Finite Field in b of size 7^3, 

Ring morphism: 

From: Finite Field in a of size 7^3 

To: Finite Field in b of size 7^3 

Defn: a |--> b) 

  

.. SEEALSO:: 

  

:func:`sage.rings.number_field.splitting_field.splitting_field` for more examples over number fields 

  

TESTS:: 

  

sage: K.<a,b> = x.splitting_field() 

Traceback (most recent call last): 

... 

IndexError: the number of names must equal the number of generators 

sage: polygen(RR).splitting_field('x') 

Traceback (most recent call last): 

... 

NotImplementedError: splitting_field() is only implemented over number fields and finite fields 

  

sage: P.<x> = PolynomialRing(GF(11^5, 'a')) 

sage: t = x^2 + 1 

sage: t.splitting_field('b') 

Finite Field in b of size 11^10 

sage: t = 24*x^13 + 2*x^12 + 14 

sage: t.splitting_field('b') 

Finite Field in b of size 11^30 

sage: t = x^56 - 14*x^3 

sage: t.splitting_field('b') 

Finite Field in b of size 11^130 

  

sage: P.<x> = PolynomialRing(GF(19^6, 'a')) 

sage: t = -x^6 + x^2 + 1 

sage: t.splitting_field('b') 

Finite Field in b of size 19^6 

sage: t = 24*x^13 + 2*x^12 + 14 

sage: t.splitting_field('b') 

Finite Field in b of size 19^18 

sage: t = x^56 - 14*x^3 

sage: t.splitting_field('b') 

Finite Field in b of size 19^156 

  

sage: P.<x> = PolynomialRing(GF(83^6, 'a')) 

sage: t = 2*x^14 - 5 + 6*x 

sage: t.splitting_field('b') 

Finite Field in b of size 83^84 

sage: t = 24*x^13 + 2*x^12 + 14 

sage: t.splitting_field('b') 

Finite Field in b of size 83^78 

sage: t = x^56 - 14*x^3 

sage: t.splitting_field('b') 

Finite Field in b of size 83^12 

  

sage: P.<x> = PolynomialRing(GF(401^13, 'a')) 

sage: t = 2*x^14 - 5 + 6*x 

sage: t.splitting_field('b') 

Finite Field in b of size 401^104 

sage: t = 24*x^13 + 2*x^12 + 14 

sage: t.splitting_field('b') 

Finite Field in b of size 401^156 

sage: t = x^56 - 14*x^3 

sage: t.splitting_field('b') 

Finite Field in b of size 401^52 

  

sage: R.<x> = QQ[] 

sage: f = x^2 - 2 

sage: f.splitting_field() 

Traceback (most recent call last): 

... 

TypeError: You must specify the name of the generator. 

  

""" 

if names is None: 

raise TypeError("You must specify the name of the generator.") 

name = normalize_names(1, names)[0] 

  

from sage.rings.number_field.number_field_base import is_NumberField 

from sage.rings.finite_rings.finite_field_base import is_FiniteField 

  

f = self.monic() # Given polynomial, made monic 

F = f.parent().base_ring() # Base field 

if not F.is_field(): 

F = F.fraction_field() 

f = self.change_ring(F) 

  

if is_NumberField(F): 

from sage.rings.number_field.splitting_field import splitting_field 

return splitting_field(f, name, map, **kwds) 

elif is_FiniteField(F): 

degree = lcm([f.degree() for f, _ in self.factor()]) 

return F.extension(degree, name, map=map, **kwds) 

  

raise NotImplementedError("splitting_field() is only implemented over number fields and finite fields") 

  

def pseudo_quo_rem(self,other): 

""" 

Compute the pseudo-division of two polynomials. 

  

INPUT: 

  

- ``other`` -- a nonzero polynomial 

  

OUTPUT: 

  

`Q` and `R` such that `l^{m-n+1} \mathrm{self} = Q \cdot\mathrm{other} + R` 

where `m` is the degree of this polynomial, `n` is the degree of 

``other``, `l` is the leading coefficient of ``other``. The result is 

such that `\deg(R) < \deg(\mathrm{other})`. 

  

ALGORITHM: 

  

Algorithm 3.1.2 in [Coh1993]_. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(ZZ, sparse=True) 

sage: p = x^4 + 6*x^3 + x^2 - x + 2 

sage: q = 2*x^2 - 3*x - 1 

sage: (quo,rem)=p.pseudo_quo_rem(q); quo,rem 

(4*x^2 + 30*x + 51, 175*x + 67) 

sage: 2^(4-2+1)*p == quo*q + rem 

True 

  

sage: S.<T> = R[] 

sage: p = (-3*x^2 - x)*T^3 - 3*x*T^2 + (x^2 - x)*T + 2*x^2 + 3*x - 2 

sage: q = (-x^2 - 4*x - 5)*T^2 + (6*x^2 + x + 1)*T + 2*x^2 - x 

sage: quo,rem=p.pseudo_quo_rem(q); quo,rem 

((3*x^4 + 13*x^3 + 19*x^2 + 5*x)*T + 18*x^4 + 12*x^3 + 16*x^2 + 16*x, 

(-113*x^6 - 106*x^5 - 133*x^4 - 101*x^3 - 42*x^2 - 41*x)*T - 34*x^6 + 13*x^5 + 54*x^4 + 126*x^3 + 134*x^2 - 5*x - 50) 

sage: (-x^2 - 4*x - 5)^(3-2+1) * p == quo*q + rem 

True 

""" 

if other.is_zero(): 

raise ZeroDivisionError("Pseudo-division by zero is not possible") 

  

# if other is a constant, then R = 0 and Q = self * other^(deg(self)) 

if other in self._parent.base_ring(): 

return (self * other**(self.degree()), self._parent.zero()) 

  

R = self 

B = other 

Q = self._parent.zero() 

e = self.degree() - other.degree() + 1 

d = B.leading_coefficient() 

  

while not R.degree() < B.degree(): 

c = R.leading_coefficient() 

diffdeg = R.degree() - B.degree() 

Q = d*Q + self._parent(c).shift(diffdeg) 

R = d*R - c*B.shift(diffdeg) 

e -= 1 

  

q = d**e 

return (q*Q,q*R) 

  

@coerce_binop 

def gcd(self, other): 

""" 

Return a greatest common divisor of this polynomial and ``other``. 

  

INPUT: 

  

- ``other`` -- a polynomial in the same ring as this polynomial 

  

OUTPUT: 

  

A greatest common divisor as a polynomial in the same ring as 

this polynomial. If the base ring is a field, the return value 

is a monic polynomial. 

  

.. NOTE:: 

  

The actual algorithm for computing greatest common divisors depends 

on the base ring underlying the polynomial ring. If the base ring 

defines a method ``_gcd_univariate_polynomial``, then this method 

will be called (see examples below). 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: (2*x^2).gcd(2*x) 

x 

sage: R.zero().gcd(0) 

0 

sage: (2*x).gcd(0) 

x 

  

One can easily add gcd functionality to new rings by providing a method 

``_gcd_univariate_polynomial``:: 

  

sage: O = ZZ[-sqrt(5)] 

sage: R.<x> = O[] 

sage: a = O.1 

sage: p = x + a 

sage: q = x^2 - 5 

sage: p.gcd(q) 

Traceback (most recent call last): 

... 

NotImplementedError: Order in Number Field in a with defining polynomial x^2 - 5 does not provide a gcd implementation for univariate polynomials 

sage: S.<x> = O.number_field()[] 

sage: O._gcd_univariate_polynomial = lambda f,g : R(S(f).gcd(S(g))) 

sage: p.gcd(q) 

x + a 

sage: del O._gcd_univariate_polynomial 

  

Use multivariate implementation for polynomials over polynomials rings:: 

  

sage: R.<x> = ZZ[] 

sage: S.<y> = R[] 

sage: T.<z> = S[] 

sage: r = 2*x*y + z 

sage: p = r * (3*x*y*z - 1) 

sage: q = r * (x + y + z - 2) 

sage: p.gcd(q) 

z + 2*x*y 

  

sage: R.<x> = QQ[] 

sage: S.<y> = R[] 

sage: r = 2*x*y + 1 

sage: p = r * (x - 1/2 * y) 

sage: q = r * (x*y^2 - x + 1/3) 

sage: p.gcd(q) 

2*x*y + 1 

""" 

variables = self._parent.variable_names_recursive() 

if len(variables) > 1: 

base = self._parent._mpoly_base_ring() 

ring = PolynomialRing(base, variables) 

if ring._has_singular: 

try: 

d1 = self._mpoly_dict_recursive() 

d2 = other._mpoly_dict_recursive() 

return self._parent(ring(d1).gcd(ring(d2))) 

except NotImplementedError: 

pass 

  

if hasattr(self.base_ring(), '_gcd_univariate_polynomial'): 

return self.base_ring()._gcd_univariate_polynomial(self, other) 

else: 

raise NotImplementedError("%s does not provide a gcd implementation for univariate polynomials"%self.base_ring()) 

  

@coerce_binop 

def lcm(self, other): 

""" 

Let f and g be two polynomials. Then this function returns the 

monic least common multiple of f and g. 

""" 

f = self*other 

g = self.gcd(other) 

q = f//g 

return ~(q.leading_coefficient())*q 

  

def _lcm(self, other): 

""" 

Let f and g be two polynomials. Then this function returns the 

monic least common multiple of f and g. 

""" 

f = self*other 

g = self.gcd(other) 

q = f//g 

return ~(q.leading_coefficient())*q # make monic (~ is inverse in python) 

  

def is_primitive(self, n=None, n_prime_divs=None): 

""" 

Returns ``True`` if the polynomial is primitive. The semantics of 

"primitive" depend on the polynomial coefficients. 

  

- (field theory) A polynomial of degree `m` over a finite field 

`\GF{q}` is primitive if it is irreducible and its root in 

`\GF{q^m}` generates the multiplicative group `\GF{q^m}^*`. 

  

- (ring theory) A polynomial over a ring is primitive if its 

coefficients generate the unit ideal. 

  

Calling `is_primitive` on a polynomial over an infinite field will 

raise an error. 

  

The additional inputs to this function are to speed up computation for 

field semantics (see note). 

  

INPUT: 

  

- ``n`` (default: ``None``) - if provided, should equal 

`q-1` where ``self.parent()`` is the field with `q` 

elements; otherwise it will be computed. 

  

- ``n_prime_divs`` (default: ``None``) - if provided, should 

be a list of the prime divisors of ``n``; otherwise it 

will be computed. 

  

.. NOTE:: 

  

Computation of the prime divisors of ``n`` can dominate the running 

time of this method, so performing this computation externally 

(e.g. ``pdivs=n.prime_divisors()``) is a good idea for repeated calls 

to is_primitive for polynomials of the same degree. 

  

Results may be incorrect if the wrong ``n`` and/or factorization are 

provided. 

  

EXAMPLES:: 

  

Field semantics examples. 

  

:: 

  

sage: R.<x> = GF(2)['x'] 

sage: f = x^4+x^3+x^2+x+1 

sage: f.is_irreducible(), f.is_primitive() 

(True, False) 

sage: f = x^3+x+1 

sage: f.is_irreducible(), f.is_primitive() 

(True, True) 

sage: R.<x> = GF(3)[] 

sage: f = x^3-x+1 

sage: f.is_irreducible(), f.is_primitive() 

(True, True) 

sage: f = x^2+1 

sage: f.is_irreducible(), f.is_primitive() 

(True, False) 

sage: R.<x> = GF(5)[] 

sage: f = x^2+x+1 

sage: f.is_primitive() 

False 

sage: f = x^2-x+2 

sage: f.is_primitive() 

True 

sage: x=polygen(QQ); f=x^2+1 

sage: f.is_primitive() 

Traceback (most recent call last): 

... 

NotImplementedError: is_primitive() not defined for polynomials over infinite fields. 

  

Ring semantics examples. 

  

:: 

  

sage: x=polygen(ZZ) 

sage: f = 5*x^2+2 

sage: f.is_primitive() 

True 

sage: f = 5*x^2+5 

sage: f.is_primitive() 

False 

  

sage: K=NumberField(x^2+5,'a') 

sage: R=K.ring_of_integers() 

sage: a=R.gen(1) 

sage: a^2 

-5 

sage: f=a*x+2 

sage: f.is_primitive() 

True 

sage: f=(1+a)*x+2 

sage: f.is_primitive() 

False 

  

sage: x=polygen(Integers(10)); 

sage: f=5*x^2+2 

sage: #f.is_primitive() #BUG:: elsewhere in Sage, should return True 

sage: f=4*x^2+2 

sage: #f.is_primitive() #BUG:: elsewhere in Sage, should return False 

  

TESTS:: 

  

sage: R.<x> = GF(2)['x'] 

sage: f = x^4+x^3+x^2+x+1 

sage: f.is_primitive(15) 

False 

sage: f.is_primitive(15, [3,5]) 

False 

sage: f.is_primitive(n_prime_divs=[3,5]) 

False 

sage: f = x^3+x+1 

sage: f.is_primitive(7, [7]) 

True 

sage: R.<x> = GF(3)[] 

sage: f = x^3-x+1 

sage: f.is_primitive(26, [2,13]) 

True 

sage: f = x^2+1 

sage: f.is_primitive(8, [2]) 

False 

sage: R.<x> = GF(5)[] 

sage: f = x^2+x+1 

sage: f.is_primitive(24, [2,3]) 

False 

sage: f = x^2-x+2 

sage: f.is_primitive(24, [2,3]) 

True 

sage: x=polygen(Integers(103)); f=x^2+1 

sage: f.is_primitive() 

False 

""" 

R = self.base_ring() 

if R.is_field(): 

if not R.is_finite(): 

raise NotImplementedError("is_primitive() not defined for polynomials over infinite fields.") 

  

if not self.is_irreducible(): 

return False 

if n is None: 

q = self.base_ring().order() 

n = q ** self.degree() - 1 

y = self._parent.quo(self).gen() 

from sage.groups.generic import order_from_multiple 

return n == order_from_multiple(y, n, n_prime_divs, operation="*") 

else: 

return R.ideal(self.coefficients())==R.ideal(1) 

  

def is_constant(self): 

""" 

Return True if this is a constant polynomial. 

  

OUTPUT: 

  

  

- ``bool`` - True if and only if this polynomial is 

constant 

  

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: x.is_constant() 

False 

sage: R(2).is_constant() 

True 

sage: R(0).is_constant() 

True 

""" 

return self.degree() <= 0 

  

def is_monomial(self): 

""" 

Returns True if self is a monomial, i.e., a power of the generator. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: x.is_monomial() 

True 

sage: (x+1).is_monomial() 

False 

sage: (x^2).is_monomial() 

True 

sage: R(1).is_monomial() 

True 

  

The coefficient must be 1:: 

  

sage: (2*x^5).is_monomial() 

False 

  

To allow a non-1 leading coefficient, use is_term():: 

  

sage: (2*x^5).is_term() 

True 

  

.. warning:: 

  

The definition of is_monomial in Sage up to 4.7.1 was the 

same as is_term, i.e., it allowed a coefficient not equal 

to 1. 

""" 

return len(self.exponents()) == 1 and self.leading_coefficient() == 1 

  

def is_term(self): 

""" 

Return True if self is an element of the base ring times a 

power of the generator. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: x.is_term() 

True 

sage: R(1).is_term() 

True 

sage: (3*x^5).is_term() 

True 

sage: (1+3*x^5).is_term() 

False 

  

To require that the coefficient is 1, use is_monomial() instead:: 

  

sage: (3*x^5).is_monomial() 

False 

""" 

return len(self.exponents()) == 1 

  

def root_field(self, names, check_irreducible=True): 

""" 

Return the field generated by the roots of the irreducible 

polynomial self. The output is either a number field, relative 

number field, a quotient of a polynomial ring over a field, or the 

fraction field of the base ring. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ['x'] 

sage: f = x^3 + x + 17 

sage: f.root_field('a') 

Number Field in a with defining polynomial x^3 + x + 17 

  

:: 

  

sage: R.<x> = QQ['x'] 

sage: f = x - 3 

sage: f.root_field('b') 

Rational Field 

  

:: 

  

sage: R.<x> = ZZ['x'] 

sage: f = x^3 + x + 17 

sage: f.root_field('b') 

Number Field in b with defining polynomial x^3 + x + 17 

  

:: 

  

sage: y = QQ['x'].0 

sage: L.<a> = NumberField(y^3-2) 

sage: R.<x> = L['x'] 

sage: f = x^3 + x + 17 

sage: f.root_field('c') 

Number Field in c with defining polynomial x^3 + x + 17 over its base field 

  

:: 

  

sage: R.<x> = PolynomialRing(GF(9,'a')) 

sage: f = x^3 + x^2 + 8 

sage: K.<alpha> = f.root_field(); K 

Univariate Quotient Polynomial Ring in alpha over Finite Field in a of size 3^2 with modulus x^3 + x^2 + 2 

sage: alpha^2 + 1 

alpha^2 + 1 

sage: alpha^3 + alpha^2 

1 

  

:: 

  

sage: R.<x> = QQ[] 

sage: f = x^2 

sage: K.<alpha> = f.root_field() 

Traceback (most recent call last): 

... 

ValueError: polynomial must be irreducible 

  

TESTS:: 

  

sage: (PolynomialRing(Integers(31),name='x').0+5).root_field('a') 

Ring of integers modulo 31 

""" 

from sage.rings.number_field.number_field import is_NumberField, NumberField 

  

R = self.base_ring() 

if not R.is_integral_domain(): 

raise ValueError("the base ring must be a domain") 

  

if check_irreducible and not self.is_irreducible(): 

raise ValueError("polynomial must be irreducible") 

  

if self.degree() <= 1: 

return R.fraction_field() 

  

if sage.rings.integer_ring.is_IntegerRing(R): 

return NumberField(self, names) 

  

if sage.rings.rational_field.is_RationalField(R) or is_NumberField(R): 

return NumberField(self, names) 

  

return R.fraction_field()[self._parent.variable_name()].quotient(self, names) 

  

def sylvester_matrix(self, right, variable = None): 

""" 

Returns the Sylvester matrix of self and right. 

  

Note that the Sylvester matrix is not defined if one of the polynomials 

is zero. 

  

INPUT: 

  

- right: a polynomial in the same ring as self. 

- variable: optional, included for compatibility with the multivariate 

case only. The variable of the polynomials. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

sage: f = (6*x + 47)*(7*x^2 - 2*x + 38) 

sage: g = (6*x + 47)*(3*x^3 + 2*x + 1) 

sage: M = f.sylvester_matrix(g) 

sage: M 

[ 42 317 134 1786 0 0 0] 

[ 0 42 317 134 1786 0 0] 

[ 0 0 42 317 134 1786 0] 

[ 0 0 0 42 317 134 1786] 

[ 18 141 12 100 47 0 0] 

[ 0 18 141 12 100 47 0] 

[ 0 0 18 141 12 100 47] 

  

If the polynomials share a non-constant common factor then the 

determinant of the Sylvester matrix will be zero:: 

  

sage: M.determinant() 

0 

  

If self and right are polynomials of positive degree, the determinant 

of the Sylvester matrix is the resultant of the polynomials.:: 

  

sage: h1 = R.random_element() 

sage: h2 = R.random_element() 

sage: M1 = h1.sylvester_matrix(h2) 

sage: M1.determinant() == h1.resultant(h2) 

True 

  

The rank of the Sylvester matrix is related to the degree of the 

gcd of self and right:: 

  

sage: f.gcd(g).degree() == f.degree() + g.degree() - M.rank() 

True 

sage: h1.gcd(h2).degree() == h1.degree() + h2.degree() - M1.rank() 

True 

  

TESTS: 

  

The variable is optional, but must be the same in both rings:: 

  

sage: K.<x> = QQ['x'] 

sage: f = x+1 

sage: g = QQ['y']([1, 0, 1]) 

sage: f.sylvester_matrix(f, x) 

[1 1] 

[1 1] 

sage: f.sylvester_matrix(g, x) 

Traceback (most recent call last): 

... 

TypeError: no common canonical parent for objects with parents: 'Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in y over Rational Field' 

  

Polynomials must be defined over compatible base rings:: 

  

sage: f = QQ['x']([1, 0, 1]) 

sage: g = ZZ['x']([1, 0, 1]) 

sage: h = GF(25, 'a')['x']([1, 0, 1]) 

sage: f.sylvester_matrix(g) 

[1 0 1 0] 

[0 1 0 1] 

[1 0 1 0] 

[0 1 0 1] 

sage: g.sylvester_matrix(h) 

[1 0 1 0] 

[0 1 0 1] 

[1 0 1 0] 

[0 1 0 1] 

sage: f.sylvester_matrix(h) 

Traceback (most recent call last): 

... 

TypeError: no common canonical parent for objects with parents: 'Univariate Polynomial Ring in x over Rational Field' and 'Univariate Polynomial Ring in x over Finite Field in a of size 5^2' 

  

We can compute the sylvester matrix of a univariate and multivariate 

polynomial:: 

  

sage: K.<x,y> = QQ['x,y'] 

sage: g = K.random_element() 

sage: f.sylvester_matrix(g) == K(f).sylvester_matrix(g,x) 

True 

  

Corner cases:: 

  

sage: K.<x>=QQ[] 

sage: f = x^2+1 

sage: g = K(0) 

sage: f.sylvester_matrix(g) 

Traceback (most recent call last): 

... 

ValueError: The Sylvester matrix is not defined for zero polynomials 

sage: g.sylvester_matrix(f) 

Traceback (most recent call last): 

... 

ValueError: The Sylvester matrix is not defined for zero polynomials 

sage: g.sylvester_matrix(g) 

Traceback (most recent call last): 

... 

ValueError: The Sylvester matrix is not defined for zero polynomials 

sage: K(3).sylvester_matrix(x^2) 

[3 0] 

[0 3] 

sage: K(3).sylvester_matrix(K(4)) 

[] 

""" 

  

# This code is almost exactly the same as that of 

# sylvester_matrix() in multi_polynomial.pyx. 

  

if self._parent != right.parent(): 

a, b = coercion_model.canonical_coercion(self,right) 

variable = a.parent()(self.variables()[0]) 

#We add the variable to cover the case that right is a multivariate 

#polynomial 

return a.sylvester_matrix(b, variable) 

  

if variable: 

if variable.parent() != self._parent: 

variable = self._parent(variable) 

  

from sage.matrix.constructor import matrix 

  

# The dimension of the sage matrix is self.degree() + right.degree() 

  

if self.is_zero() or right.is_zero(): 

raise ValueError("The Sylvester matrix is not defined for zero polynomials") 

  

m = self.degree() 

n = right.degree() 

  

M = matrix(self.base_ring(), n + m, n + m) 

  

r = 0 

offset = 0 

for _ in range(n): 

for c in range(m, -1, -1): 

M[r, m - c + offset] = self[c] 

offset += 1 

r += 1 

  

offset = 0 

for _ in range(m): 

for c in range(n, -1, -1): 

M[r, n - c + offset] = right[c] 

offset += 1 

r += 1 

  

return M 

  

cpdef constant_coefficient(self): 

""" 

Return the constant coefficient of this polynomial. 

  

OUTPUT: element of base ring 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = -2*x^3 + 2*x - 1/3 

sage: f.constant_coefficient() 

-1/3 

""" 

return self[0] 

  

cpdef Polynomial _new_constant_poly(self, a, Parent P): 

""" 

Create a new constant polynomial from a in P, which MUST be an 

element of the base ring of P (this is not checked). 

  

EXAMPLES:: 

  

sage: R.<w> = PolynomialRing(GF(9,'a'), sparse=True) 

sage: a = w._new_constant_poly(0, R); a 

0 

sage: a.coefficients() 

[] 

""" 

t = type(self) 

return t(P, [a] if a else [], check=False) 

  

def is_monic(self): 

""" 

Returns True if this polynomial is monic. The zero polynomial is by 

definition not monic. 

  

EXAMPLES:: 

  

sage: x = QQ['x'].0 

sage: f = x + 33 

sage: f.is_monic() 

True 

sage: f = 0*x 

sage: f.is_monic() 

False 

sage: f = 3*x^3 + x^4 + x^2 

sage: f.is_monic() 

True 

sage: f = 2*x^2 + x^3 + 56*x^5 

sage: f.is_monic() 

False 

  

AUTHORS: 

  

- Naqi Jaffery (2006-01-24): examples 

""" 

return not self.is_zero() and self[self.degree()] == 1 

  

def is_unit(self): 

r""" 

Return True if this polynomial is a unit. 

  

EXAMPLES:: 

  

sage: a = Integers(90384098234^3) 

sage: b = a(2*191*236607587) 

sage: b.is_nilpotent() 

True 

sage: R.<x> = a[] 

sage: f = 3 + b*x + b^2*x^2 

sage: f.is_unit() 

True 

sage: f = 3 + b*x + b^2*x^2 + 17*x^3 

sage: f.is_unit() 

False 

  

EXERCISE (Atiyah-McDonald, Ch 1): Let `A[x]` be a 

polynomial ring in one variable. Then 

`f=\sum a_i x^i \in A[x]` is a unit if and only if 

`a_0` is a unit and `a_1,\ldots, a_n` are 

nilpotent. 

  

TESTS: 

  

Check that :trac:`18600` is fixed:: 

  

sage: R.<x> = PolynomialRing(ZZ, sparse=True) 

sage: c = x^2^100 + 1 

sage: c.is_unit() 

False 

""" 

if self.degree() > 0: 

try: 

if self._parent.base_ring().is_integral_domain(): 

return False 

except NotImplementedError: 

pass 

for c in self.coefficients()[1:]: 

if not c.is_nilpotent(): 

return False 

return self[0].is_unit() 

  

def is_nilpotent(self): 

r""" 

Return True if this polynomial is nilpotent. 

  

EXAMPLES:: 

  

sage: R = Integers(12) 

sage: S.<x> = R[] 

sage: f = 5 + 6*x 

sage: f.is_nilpotent() 

False 

sage: f = 6 + 6*x^2 

sage: f.is_nilpotent() 

True 

sage: f^2 

0 

  

EXERCISE (Atiyah-McDonald, Ch 1): Let `A[x]` be a 

polynomial ring in one variable. Then 

`f=\sum a_i x^i \in A[x]` is nilpotent if and only if 

every `a_i` is nilpotent. 

  

TESTS: 

  

Check that :trac:`18600` is fixed:: 

  

sage: R.<x> = PolynomialRing(Zmod(4), sparse=True) 

sage: (2*x^2^100 + 2).is_nilpotent() 

True 

""" 

for c in self.coefficients(): 

if not c.is_nilpotent(): 

return False 

return True 

  

def is_gen(self): 

r""" 

Return True if this polynomial is the distinguished generator of 

the parent polynomial ring. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: R(1).is_gen() 

False 

sage: R(x).is_gen() 

True 

  

Important - this function doesn't return True if self equals the 

generator; it returns True if self *is* the generator. 

  

:: 

  

sage: f = R([0,1]); f 

x 

sage: f.is_gen() 

False 

sage: f is x 

False 

sage: f == x 

True 

""" 

return bool(self._is_gen) 

  

def lc(self): 

""" 

Return the leading coefficient of this polynomial. 

  

OUTPUT: element of the base ring 

This method is same as :meth:`leading_coefficient`. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = (-2/5)*x^3 + 2*x - 1/3 

sage: f.lc() 

-2/5 

""" 

return self[self.degree()] 

  

def leading_coefficient(self): 

""" 

Return the leading coefficient of this polynomial. 

  

OUTPUT: element of the base ring 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = (-2/5)*x^3 + 2*x - 1/3 

sage: f.leading_coefficient() 

-2/5 

""" 

return self[self.degree()] 

  

def lm(self): 

""" 

Return the leading monomial of this polynomial. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = (-2/5)*x^3 + 2*x - 1/3 

sage: f.lm() 

x^3 

sage: R(5).lm() 

1 

sage: R(0).lm() 

0 

sage: R(0).lm().parent() is R 

True 

""" 

if self.degree() < 0: 

return self 

output = [self.base_ring().zero()] * self.degree() + [self.base_ring().one()] 

return self._new_generic(output) 

  

def lt(self): 

""" 

Return the leading term of this polynomial. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = (-2/5)*x^3 + 2*x - 1/3 

sage: f.lt() 

-2/5*x^3 

sage: R(5).lt() 

5 

sage: R(0).lt() 

0 

sage: R(0).lt().parent() is R 

True 

""" 

return self.lc() * self.lm() 

  

def monic(self): 

""" 

Return this polynomial divided by its leading coefficient. Does not 

change this polynomial. 

  

EXAMPLES:: 

  

sage: x = QQ['x'].0 

sage: f = 2*x^2 + x^3 + 56*x^5 

sage: f.monic() 

x^5 + 1/56*x^3 + 1/28*x^2 

sage: f = (1/4)*x^2 + 3*x + 1 

sage: f.monic() 

x^2 + 12*x + 4 

  

The following happens because `f = 0` cannot be made into a 

monic polynomial 

  

:: 

  

sage: f = 0*x 

sage: f.monic() 

Traceback (most recent call last): 

... 

ZeroDivisionError: rational division by zero 

  

Notice that the monic version of a polynomial over the integers is 

defined over the rationals. 

  

:: 

  

sage: x = ZZ['x'].0 

sage: f = 3*x^19 + x^2 - 37 

sage: g = f.monic(); g 

x^19 + 1/3*x^2 - 37/3 

sage: g.parent() 

Univariate Polynomial Ring in x over Rational Field 

  

AUTHORS: 

  

- Naqi Jaffery (2006-01-24): examples 

""" 

if self.is_monic(): 

return self 

a = ~self.leading_coefficient() 

R = self._parent 

if a.parent() != R.base_ring(): 

S = R.base_extend(a.parent()) 

return a*S(self) 

else: 

return a*self 

  

def coefficients(self, sparse=True): 

""" 

Return the coefficients of the monomials appearing in self. 

If ``sparse=True`` (the default), it returns only the non-zero coefficients. 

Otherwise, it returns the same value as ``self.list()``. 

(In this case, it may be slightly faster to invoke ``self.list()`` directly.) 

  

EXAMPLES:: 

  

sage: _.<x> = PolynomialRing(ZZ) 

sage: f = x^4+2*x^2+1 

sage: f.coefficients() 

[1, 2, 1] 

sage: f.coefficients(sparse=False) 

[1, 0, 2, 0, 1] 

""" 

zero = self._parent.base_ring().zero() 

if (sparse): 

return [c for c in self.list() if c != zero] 

else: 

return self.list() 

  

def exponents(self): 

""" 

Return the exponents of the monomials appearing in self. 

  

EXAMPLES:: 

  

sage: _.<x> = PolynomialRing(ZZ) 

sage: f = x^4+2*x^2+1 

sage: f.exponents() 

[0, 2, 4] 

""" 

zero = self._parent.base_ring().zero() 

l = self.list() 

return [i for i in range(len(l)) if l[i] != zero] 

  

cpdef list list(self, bint copy=True): 

""" 

Return a new copy of the list of the underlying elements of ``self``. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = (-2/5)*x^3 + 2*x - 1/3 

sage: v = f.list(); v 

[-1/3, 2, 0, -2/5] 

  

Note that v is a list, it is mutable, and each call to the list 

method returns a new list:: 

  

sage: type(v) 

<... 'list'> 

sage: v[0] = 5 

sage: f.list() 

[-1/3, 2, 0, -2/5] 

  

Here is an example with a generic polynomial ring:: 

  

sage: R.<x> = QQ[] 

sage: S.<y> = R[] 

sage: f = y^3 + x*y -3*x; f 

y^3 + x*y - 3*x 

sage: type(f) 

<type 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'> 

sage: v = f.list(); v 

[-3*x, x, 0, 1] 

sage: v[0] = 10 

sage: f.list() 

[-3*x, x, 0, 1] 

""" 

raise NotImplementedError 

  

def prec(self): 

""" 

Return the precision of this polynomial. This is always infinity, 

since polynomials are of infinite precision by definition (there is 

no big-oh). 

  

EXAMPLES:: 

  

sage: x = polygen(ZZ) 

sage: (x^5 + x + 1).prec() 

+Infinity 

sage: x.prec() 

+Infinity 

""" 

return infinity.infinity 

  

def padded_list(self, n=None): 

""" 

Return list of coefficients of self up to (but not including) 

`q^n`. 

  

Includes 0's in the list on the right so that the list has length 

`n`. 

  

INPUT: 

  

  

- ``n`` - (default: None); if given, an integer that 

is at least 0 

  

  

EXAMPLES:: 

  

sage: x = polygen(QQ) 

sage: f = 1 + x^3 + 23*x^5 

sage: f.padded_list() 

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

sage: f.padded_list(10) 

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

sage: len(f.padded_list(10)) 

10 

sage: f.padded_list(3) 

[1, 0, 0] 

sage: f.padded_list(0) 

[] 

sage: f.padded_list(-1) 

Traceback (most recent call last): 

... 

ValueError: n must be at least 0 

  

TESTS: 

  

Check that :trac:`18600` is fixed:: 

  

sage: R.<x> = PolynomialRing(ZZ, sparse=True) 

sage: (x^2^100 + x^8 - 1).padded_list(10) 

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

""" 

if n is None: 

return self.list() 

if n < 0: 

raise ValueError("n must be at least 0") 

if self.degree() < n: 

v = self.list() 

z = self._parent.base_ring().zero() 

return v + [z]*(n - len(v)) 

else: 

return self[:int(n)].padded_list(n) 

  

def coeffs(self): 

r""" 

Using ``coeffs()`` is now deprecated (:trac:`17518`). 

Returns ``self.list()``. 

  

(It is potentially slightly faster to use 

``self.list()`` directly.) 

  

EXAMPLES:: 

  

sage: x = QQ['x'].0 

sage: f = 10*x^3 + 5*x + 2/17 

sage: f.coeffs() 

doctest:...: DeprecationWarning: The use of coeffs() is now deprecated in favor of coefficients(sparse=False). 

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

[2/17, 5, 0, 10] 

""" 

deprecation(17518, 'The use of coeffs() is now deprecated in favor of coefficients(sparse=False).') 

return self.list() 

  

def monomial_coefficient(self, m): 

""" 

Return the coefficient in the base ring of the monomial ``m`` in 

``self``, where ``m`` must have the same parent as ``self``. 

  

INPUT: 

  

- ``m`` - a monomial 

  

OUTPUT: 

  

Coefficient in base ring. 

  

EXAMPLES:: 

  

sage: P.<x> = QQ[] 

  

The parent of the return is a member of the base ring. 

sage: f = 2 * x 

sage: c = f.monomial_coefficient(x); c 

2 

sage: c.parent() 

Rational Field 

  

sage: f = x^9 - 1/2*x^2 + 7*x + 5/11 

sage: f.monomial_coefficient(x^9) 

1 

sage: f.monomial_coefficient(x^2) 

-1/2 

sage: f.monomial_coefficient(x) 

7 

sage: f.monomial_coefficient(x^0) 

5/11 

sage: f.monomial_coefficient(x^3) 

0 

""" 

if not m.parent() is self._parent: 

raise TypeError("monomial must have same parent as self.") 

  

d = m.degree() 

coeffs = self.list() 

if 0 <= d < len(coeffs): 

return coeffs[d] 

else: 

return self._parent.base_ring().zero() 

  

def monomials(self): 

""" 

Return the list of the monomials in ``self`` in a decreasing order of their degrees. 

  

EXAMPLES:: 

  

sage: P.<x> = QQ[] 

sage: f = x^2 + (2/3)*x + 1 

sage: f.monomials() 

[x^2, x, 1] 

sage: f = P(3/2) 

sage: f.monomials() 

[1] 

sage: f = P(0) 

sage: f.monomials() 

[] 

sage: f = x 

sage: f.monomials() 

[x] 

sage: f = - 1/2*x^2 + x^9 + 7*x + 5/11 

sage: f.monomials() 

[x^9, x^2, x, 1] 

sage: x = var('x') 

sage: K.<rho> = NumberField(x**2 + 1) 

sage: R.<y> = QQ[] 

sage: p = rho*y 

sage: p.monomials() 

[y] 

""" 

if self.is_zero(): 

return [] 

v = self._parent.gen() 

zero = self._parent.base_ring().zero() 

coeffs = self.list() 

return [v**i for i in range(self.degree(), -1, -1) if coeffs[i] != zero] 

  

def newton_raphson(self, n, x0): 

""" 

Return a list of n iterative approximations to a root of this 

polynomial, computed using the Newton-Raphson method. 

  

The Newton-Raphson method is an iterative root-finding algorithm. 

For f(x) a polynomial, as is the case here, this is essentially the 

same as Horner's method. 

  

INPUT: 

  

  

- ``n`` - an integer (=the number of iterations), 

  

- ``x0`` - an initial guess x0. 

  

  

OUTPUT: A list of numbers hopefully approximating a root of 

f(x)=0. 

  

If one of the iterates is a critical point of f then a 

ZeroDivisionError exception is raised. 

  

EXAMPLES:: 

  

sage: x = PolynomialRing(RealField(), 'x').gen() 

sage: f = x^2 - 2 

sage: f.newton_raphson(4, 1) 

[1.50000000000000, 1.41666666666667, 1.41421568627451, 1.41421356237469] 

  

AUTHORS: 

  

- David Joyner and William Stein (2005-11-28) 

""" 

n = sage.rings.integer.Integer(n) 

df = self.derivative() 

K = self._parent.base_ring() 

a = K(x0) 

L = [] 

for i in range(n): 

a -= self(a) / df(a) 

L.append(a) 

return L 

  

def polynomial(self, var): 

r""" 

Let var be one of the variables of the parent of self. This returns 

self viewed as a univariate polynomial in var over the polynomial 

ring generated by all the other variables of the parent. 

  

For univariate polynomials, if var is the generator of the parent 

ring, we return this polynomial, otherwise raise an error. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: (x+1).polynomial(x) 

x + 1 

  

TESTS:: 

  

sage: x.polynomial(1) 

Traceback (most recent call last): 

... 

ValueError: given variable is not the generator of parent. 

""" 

if self._parent.ngens() == 1: 

if self._parent.gen() == var: 

return self 

raise ValueError("given variable is not the generator of parent.") 

raise NotImplementedError 

  

def newton_slopes(self, p, lengths=False): 

""" 

Return the `p`-adic slopes of the Newton polygon of self, 

when this makes sense. 

  

OUTPUT: 

  

If `lengths` is `False`, a list of rational numbers. If `lengths` is 

`True`, a list of couples `(s,l)` where `s` is the slope and `l` the 

length of the corresponding segment in the Newton polygon. 

  

EXAMPLES:: 

  

sage: x = QQ['x'].0 

sage: f = x^3 + 2 

sage: f.newton_slopes(2) 

[1/3, 1/3, 1/3] 

sage: R.<x> = PolynomialRing(ZZ, sparse=True) 

sage: p = x^5 + 6*x^2 + 4 

sage: p.newton_slopes(2) 

[1/2, 1/2, 1/3, 1/3, 1/3] 

sage: p.newton_slopes(2, lengths=True) 

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

sage: (x^2^100 + 27).newton_slopes(3, lengths=True) 

[(3/1267650600228229401496703205376, 1267650600228229401496703205376)] 

  

ALGORITHM: Uses PARI if `lengths` is `False`. 

""" 

if not lengths: 

f = self.__pari__() 

v = list(f.newtonpoly(p)) 

return [sage.rings.rational.Rational(x) for x in v] 

  

e = self.exponents() 

c = self.coefficients() 

if len(e) == 0: return [] 

if len(e) == 1: 

if e[0] == 0: return [] 

else: return [(infinity.infinity, e[0])] 

  

if e[0] == 0: slopes = [] 

else: slopes = [(infinity.infinity, e[0])] 

  

points = [(e[0], c[0].valuation(p)), (e[1], c[1].valuation(p))] 

slopes.append((-(c[1].valuation(p)-c[0].valuation(p))/(e[1] - e[0]), e[1]-e[0])) 

for i in range(2, len(e)): 

v = c[i].valuation(p) 

s = -(v-points[-1][1])/(e[i]-points[-1][0]) 

while len(slopes) > 0 and s >= slopes[-1][0]: 

slopes = slopes[:-1] 

points = points[:-1] 

s = -(v-points[-1][1])/(e[i]-points[-1][0]) 

slopes.append((s,e[i]-points[-1][0])) 

points.append((e[i],v)) 

  

return slopes 

  

def dispersion_set(self, other=None): 

r""" 

Compute the dispersion set of two polynomials. 

  

The dispersion set of `f` and `g` is the set of nonnegative integers 

`n` such that `f(x + n)` and `g(x)` have a nonconstant common factor. 

  

When ``other`` is ``None``, compute the auto-dispersion set of 

``self``, i.e., its dispersion set with itself. 

  

ALGORITHM: 

  

See Section 4 of Man & Wright [ManWright1994]_. 

  

.. [ManWright1994] Yiu-Kwong Man and Francis J. Wright. 

*Fast Polynomial Dispersion Computation and its Application to 

Indefinite Summation*. ISSAC 1994. 

  

.. SEEALSO:: :meth:`dispersion` 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x.dispersion_set(x + 1) 

[1] 

sage: (x + 1).dispersion_set(x) 

[] 

  

sage: pol = x^3 + x - 7 

sage: (pol*pol(x+3)^2).dispersion_set() 

[0, 3] 

""" 

other = self if other is None else self._parent.coerce(other) 

x = self._parent.gen() 

dispersions = set() 

for p, _ in self.factor(): 

# need both due to the semantics of is_primitive() over fields 

assert p.is_monic() or p.is_primitive() 

for q, _ in other.factor(): 

m, n = p.degree(), q.degree() 

assert q.is_monic() or q.is_primitive() 

if m != n or p[n] != q[n]: 

continue 

alpha = (q[n-1] - p[n-1])/(n*p[n]) 

if alpha.is_integer(): # ZZ() might work for non-integers... 

alpha = ZZ(alpha) 

else: 

continue 

if alpha < 0 or alpha in dispersions: 

continue 

if n >= 1 and p(x + alpha) != q: 

continue 

dispersions.add(alpha) 

return list(dispersions) 

  

def dispersion(self, other=None): 

r""" 

Compute the dispersion of a pair of polynomials. 

  

The dispersion of `f` and `g` is the largest nonnegative integer `n` 

such that `f(x + n)` and `g(x)` have a nonconstant common factor. 

  

When ``other`` is ``None``, compute the auto-dispersion of ``self``, 

i.e., its dispersion with itself. 

  

.. SEEALSO:: :meth:`dispersion_set` 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x.dispersion(x + 1) 

1 

sage: (x + 1).dispersion(x) 

-Infinity 

  

sage: Pol.<x> = QQbar[] 

sage: pol = Pol([sqrt(5), 1, 3/2]) 

sage: pol.dispersion() 

0 

sage: (pol*pol(x+3)).dispersion() 

3 

""" 

dispersions = self.dispersion_set(other) 

return max(dispersions) if len(dispersions) > 0 else infinity.minus_infinity 

  

##################################################################### 

# Conversions to other systems 

##################################################################### 

def __pari__(self): 

r""" 

Return polynomial as a PARI object. 

  

Sage does not handle PARI's variable ordering requirements 

gracefully at this time. In practice, this means that the variable 

``x`` needs to be the topmost variable, as in the 

example. 

  

EXAMPLES:: 

  

sage: f = QQ['x']([0,1,2/3,3]) 

sage: pari(f) 

3*x^3 + 2/3*x^2 + x 

  

:: 

  

sage: S.<a> = QQ['a'] 

sage: R.<x> = S['x'] 

sage: f = R([0, a]) + R([0, 0, 2/3]) 

sage: pari(f) 

2/3*x^2 + a*x 

  

Polynomials over a number field work, provided that the variable is 

called 'x':: 

  

sage: x = polygen(QQ) 

sage: K.<b> = NumberField(x^2 + x + 1) 

sage: R.<x> = PolynomialRing(K) 

sage: pol = (b + x)^3; pol 

x^3 + 3*b*x^2 + (-3*b - 3)*x + 1 

sage: pari(pol) 

Mod(1, y^2 + y + 1)*x^3 + Mod(3*y, y^2 + y + 1)*x^2 + Mod(-3*y - 3, y^2 + y + 1)*x + Mod(1, y^2 + y + 1) 

  

TESTS: 

  

Unfortunately, variable names matter:: 

  

sage: R.<x, y> = QQ[] 

sage: S.<a> = R[] 

sage: f = x^2 + a; g = y^3 + a 

sage: pari(f) 

Traceback (most recent call last): 

... 

PariError: incorrect priority in gtopoly: variable x <= a 

  

Stacked polynomial rings, first with a univariate ring on the 

bottom:: 

  

sage: S.<a> = QQ['a'] 

sage: R.<x> = S['x'] 

sage: pari(x^2 + 2*x) 

x^2 + 2*x 

sage: pari(a*x + 2*x^3) 

2*x^3 + a*x 

  

Stacked polynomial rings, second with a multivariate ring on the 

bottom:: 

  

sage: S.<a, b> = ZZ['a', 'b'] 

sage: R.<x> = S['x'] 

sage: pari(x^2 + 2*x) 

x^2 + 2*x 

sage: pari(a*x + 2*b*x^3) 

2*b*x^3 + a*x 

  

Stacked polynomial rings with exotic base rings:: 

  

sage: S.<a, b> = GF(7)['a', 'b'] 

sage: R.<x> = S['x'] 

sage: pari(x^2 + 9*x) 

x^2 + 2*x 

sage: pari(a*x + 9*b*x^3) 

2*b*x^3 + a*x 

  

:: 

  

sage: S.<a> = Integers(8)['a'] 

sage: R.<x> = S['x'] 

sage: pari(x^2 + 2*x) 

Mod(1, 8)*x^2 + Mod(2, 8)*x 

sage: pari(a*x + 10*x^3) 

Mod(2, 8)*x^3 + Mod(1, 8)*a*x 

""" 

return self._pari_with_name(self._parent.variable_name()) 

  

def _pari_or_constant(self, name=None): 

r""" 

Convert ``self`` to PARI. This behaves identical to :meth:`__pari__` 

or :meth:`_pari_with_name` except for constant polynomials: 

then the constant is returned instead of a constant polynomial. 

  

INPUT: 

  

- ``name`` -- (default: None) Variable name. If not given, use 

``self.parent().variable_name()``. This argument is irrelevant 

for constant polynomials. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

sage: pol = 2*x^2 + 7*x - 5 

sage: pol._pari_or_constant() 

2*x^2 + 7*x - 5 

sage: pol._pari_or_constant('a') 

2*a^2 + 7*a - 5 

sage: pol = R(7) 

sage: pol._pari_or_constant() 

7 

sage: pol._pari_or_constant().type() 

't_INT' 

sage: pol.__pari__().type() 

't_POL' 

sage: PolynomialRing(IntegerModRing(101), 't')()._pari_or_constant() 

Mod(0, 101) 

""" 

if self.is_constant(): 

return self[0].__pari__() 

if name is None: 

name = self._parent.variable_name() 

return self._pari_with_name(name) 

  

def _pari_with_name(self, name='x'): 

r""" 

Return polynomial as a PARI object with topmost variable 

``name``. By default, use 'x' for the variable name. 

  

For internal use only. 

  

EXAMPLES: 

  

sage: R.<a> = PolynomialRing(ZZ) 

sage: (2*a^2 + a)._pari_with_name() 

2*x^2 + x 

sage: (2*a^2 + a)._pari_with_name('y') 

2*y^2 + y 

""" 

vals = [x.__pari__() for x in self.list()] 

return pari(vals).Polrev(name) 

  

def _pari_init_(self): 

return repr(self.__pari__()) 

  

def _magma_init_(self, magma): 

""" 

Return a string that evaluates in Magma to this polynomial. 

  

EXAMPLES:: 

  

sage: magma = Magma() # new session 

sage: R.<y> = ZZ[] 

sage: f = y^3 - 17*y + 5 

sage: f._magma_init_(magma) # optional - magma 

'_sage_[...]![5,-17,0,1]' 

sage: g = magma(f); g # optional - magma 

y^3 - 17*y + 5 

  

Note that in Magma there is only one polynomial ring over each 

base, so if we make the polynomial ring over ZZ with variable 

`z`, then this changes the variable name of the polynomial 

we already defined:: 

  

sage: R.<z> = ZZ[] 

sage: magma(R) # optional - magma 

Univariate Polynomial Ring in z over Integer Ring 

sage: g # optional - magma 

z^3 - 17*z + 5 

  

In Sage the variable name does not change:: 

  

sage: f 

y^3 - 17*y + 5 

  

A more complicated nested example:: 

  

sage: k.<a> = GF(9); R.<s,t> = k[]; S.<W> = R[] 

sage: magma(a*W^20 + s*t/a) # optional - magma 

a*W^20 + a^7*s*t 

""" 

# Get a reference to Magma version of parent. 

R = magma(self._parent) 

# Get list of coefficients. 

v = ','.join([a._magma_init_(magma) for a in self.list()]) 

return '%s![%s]'%(R.name(), v) 

  

def _gap_(self, gap): 

""" 

Return this polynomial in GAP. 

  

INPUT: 

  

- ``gap`` -- a GAP or libgap instance 

  

EXAMPLES:: 

  

sage: R.<y> = ZZ[] 

sage: f = y^3 - 17*y + 5 

sage: g = gap(f); g # indirect doctest 

y^3-17*y+5 

sage: f._gap_init_() 

'y^3 - 17*y + 5' 

sage: R.<z> = ZZ[] 

sage: gap(R) 

PolynomialRing( Integers, ["z"] ) 

sage: g 

y^3-17*y+5 

sage: gap(z^2 + z) 

z^2+z 

sage: libgap(z^2 + z) 

z^2+z 

  

Coefficients in a finite field:: 

  

sage: R.<y> = GF(7)[] 

sage: f = y^3 - 17*y + 5 

sage: g = gap(f); g 

y^3+Z(7)^4*y+Z(7)^5 

sage: h = libgap(f); h 

y^3+Z(7)^4*y+Z(7)^5 

sage: g.Factors() 

[ y+Z(7)^0, y+Z(7)^0, y+Z(7)^5 ] 

sage: h.Factors() 

[ y+Z(7)^0, y+Z(7)^0, y+Z(7)^5 ] 

sage: f.factor() 

(y + 5) * (y + 1)^2 

""" 

R = gap(self._parent) 

var = list(R.IndeterminatesOfPolynomialRing())[0] 

return self(var) 

  

def _libgap_(self): 

r""" 

TESTS:: 

  

sage: R.<x> = ZZ[] 

sage: libgap(-x^3 + 3*x) # indirect doctest 

-x^3+3*x 

sage: libgap(R.zero()) # indirect doctest 

0 

""" 

from sage.libs.gap.libgap import libgap 

return self._gap_(libgap) 

  

###################################################################### 

  

@coerce_binop 

def resultant(self, other): 

r""" 

Return the resultant of ``self`` and ``other``. 

  

INPUT: 

  

- ``other`` -- a polynomial 

  

OUTPUT: an element of the base ring of the polynomial ring 

  

ALGORITHM: 

  

Uses PARI's ``polresultant`` function. For base rings that 

are not supported by PARI, the resultant is computed as the 

determinant of the Sylvester matrix. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x^3 + x + 1; g = x^3 - x - 1 

sage: r = f.resultant(g); r 

-8 

sage: r.parent() is QQ 

True 

  

We can compute resultants over univariate and multivariate 

polynomial rings:: 

  

sage: R.<a> = QQ[] 

sage: S.<x> = R[] 

sage: f = x^2 + a; g = x^3 + a 

sage: r = f.resultant(g); r 

a^3 + a^2 

sage: r.parent() is R 

True 

  

:: 

  

sage: R.<a, b> = QQ[] 

sage: S.<x> = R[] 

sage: f = x^2 + a; g = x^3 + b 

sage: r = f.resultant(g); r 

a^3 + b^2 

sage: r.parent() is R 

True 

  

TESTS:: 

  

sage: R.<x, y> = QQ[] 

sage: S.<a> = R[] 

sage: f = x^2 + a; g = y^3 + a 

sage: h = f.resultant(g); h 

y^3 - x^2 

sage: h.parent() is R 

True 

  

Check that :trac:`13672` is fixed:: 

  

sage: R.<t> = GF(2)[] 

sage: S.<x> = R[] 

sage: f = (t^2 + t)*x + t^2 + t 

sage: g = (t + 1)*x + t^2 

sage: f.resultant(g) 

t^4 + t 

  

Check that :trac:`15061` is fixed:: 

  

sage: R.<T> = PowerSeriesRing(QQ) 

sage: F = R([1,1],2) 

sage: RP.<x> = PolynomialRing(R) 

sage: P = x^2 - F 

sage: P.resultant(P.derivative()) 

-4 - 4*T + O(T^2) 

  

Check that :trac:`16360` is fixed:: 

  

sage: K.<x> = FunctionField(QQ) 

sage: R.<y> = K[] 

sage: y.resultant(y+x) 

x 

  

sage: K.<a> = FunctionField(QQ) 

sage: R.<b> = K[] 

sage: L.<b> = K.extension(b^2-a) 

sage: R.<x> = L[] 

sage: f=x^2-a 

sage: g=x-b 

sage: f.resultant(g) 

0 

  

Check that :trac:`17817` is fixed:: 

  

sage: A.<a,b,c> = Frac(PolynomialRing(QQ,'a,b,c')) 

sage: B.<d,e,f> = PolynomialRing(A,'d,e,f') 

sage: R.<x>= PolynomialRing(B,'x') 

sage: S.<y> = PolynomialRing(R,'y') 

sage: p = ((1/b^2*d^2+1/a)*x*y^2+a*b/c*y+e+x^2) 

sage: q = -4*c^2*y^3+1 

sage: p.resultant(q) 

16*c^4*x^6 + 48*c^4*e*x^4 + (1/b^6*d^6 + 3/(a*b^4)*d^4 + ((-12*a^3*b*c + 3)/(a^2*b^2))*d^2 + (-12*a^3*b*c + 1)/a^3)*x^3 + 48*c^4*e^2*x^2 + (((-12*a*c)/b)*d^2*e + (-12*b*c)*e)*x + 16*c^4*e^3 + 4*a^3*b^3/c 

  

""" 

variable = self.variable_name() 

try: 

res = self.__pari__().polresultant(other, variable) 

return self._parent.base_ring()(res) 

except (TypeError, ValueError, PariError, NotImplementedError): 

return self.sylvester_matrix(other).det() 

  

def composed_op(p1, p2, op, algorithm=None, monic=False): 

r""" 

Return the composed sum, difference, product or quotient of this 

polynomial with another one. 

  

In the case of two monic polynomials `p_1` and `p_2` over an integral 

domain, the composed sum, difference, etc. are given by 

  

.. MATH:: 

  

\prod_{p_1(a)=p_2(b)=0}(x - (a \ast b)), \qquad 

\ast ∈ \{ +, -, ×, / \} 

  

where the roots `a` and `b` are to be considered in the algebraic 

closure of the fraction field of the coefficients and counted with 

multiplicities. If the polynomials are not monic this quantity is 

multiplied by `\\alpha_1^{deg(p_2)} \\alpha_2^{deg(p_1)}` where 

`\\alpha_1` and `\\alpha_2` are the leading coefficients of `p_1` and 

`p_2` respectively. 

  

INPUT: 

  

- ``p2`` -- univariate polynomial belonging to the same polynomial ring 

as this polynomial 

  

- ``op`` -- ``operator.OP`` where ``OP=add`` or ``sub`` or ``mul`` or 

``truediv``. 

  

- ``algorithm`` -- can be "resultant" or "BFSS"; 

by default the former is used when the polynomials have few nonzero 

coefficients and small degrees or if the base ring is not `\ZZ` or 

`\QQ`. Otherwise the latter is used. 

  

- ``monic`` -- whether to return a monic polynomial. If ``True`` the 

coefficients of the result belong to the fraction field of the 

coefficients. 

  

ALGORITHM: 

  

The computation is straightforward using resultants. Indeed for the 

composed sum it would be `Res_y(p1(x-y), p2(y))`. However, the method 

from [BFSS]_ using series expansions is asymptotically much faster. 

  

Note that the algorithm ``BFSS`` with polynomials with coefficients in 

`\ZZ` needs to perform operations over `\QQ`. 

  

.. TODO:: 

  

- The [BFSS]_ algorithm has been implemented here only in the case of 

polynomials over rationals. For other rings of zero characteristic 

(or if the characteristic is larger than the product of the degrees), 

one needs to implement a generic method ``_exp_series``. In the 

general case of non-zero characteristic there is an alternative 

algorithm in the same paper. 

  

- The Newton series computation can be done much more efficiently! 

See [BFSS]_. 

  

EXAMPLES:: 

  

sage: x = polygen(ZZ) 

sage: p1 = x^2 - 1 

sage: p2 = x^4 - 1 

sage: p1.composed_op(p2, operator.add) 

x^8 - 4*x^6 + 4*x^4 - 16*x^2 

sage: p1.composed_op(p2, operator.mul) 

x^8 - 2*x^4 + 1 

sage: p1.composed_op(p2, operator.truediv) 

x^8 - 2*x^4 + 1 

  

This function works over any field. However for base rings other than 

`\ZZ` and `\QQ` only the resultant algorithm is available:: 

  

sage: x = polygen(QQbar) 

sage: p1 = x**2 - AA(2).sqrt() 

sage: p2 = x**3 - AA(3).sqrt() 

sage: r1 = p1.roots(multiplicities=False) 

sage: r2 = p2.roots(multiplicities=False) 

sage: p = p1.composed_op(p2, operator.add) 

sage: p 

1.000000000000000?*x^6 - 4.242640687119285?*x^4 - 

3.464101615137755?*x^3 + 6.000000000000000?*x^2 - 

14.69693845669907?*x + 0.1715728752538099? 

sage: all(p(x+y).is_zero() for x in r1 for y in r2) 

True 

  

sage: x = polygen(GF(2)) 

sage: p1 = x**2 + x - 1 

sage: p2 = x**3 + x - 1 

sage: p_add = p1.composed_op(p2, operator.add) 

sage: p_add 

x^6 + x^5 + x^3 + x^2 + 1 

sage: p_mul = p1.composed_op(p2, operator.mul) 

sage: p_mul 

x^6 + x^4 + x^2 + x + 1 

sage: p_div = p1.composed_op(p2, operator.truediv) 

sage: p_div 

x^6 + x^5 + x^4 + x^2 + 1 

  

sage: K = GF(2**6, 'a') 

sage: r1 = p1.roots(K, multiplicities=False) 

sage: r2 = p2.roots(K, multiplicities=False) 

sage: all(p_add(x1+x2).is_zero() for x1 in r1 for x2 in r2) 

True 

sage: all(p_mul(x1*x2).is_zero() for x1 in r1 for x2 in r2) 

True 

sage: all(p_div(x1/x2).is_zero() for x1 in r1 for x2 in r2) 

True 

  

TESTS: 

  

In Python 2, ``operator.div`` still works:: 

  

sage: from six import PY2 

sage: div = getattr(operator, "div" if PY2 else "truediv") 

sage: p1.composed_op(p2, div) 

x^6 + x^5 + x^4 + x^2 + 1 

  

:: 

  

sage: y = polygen(ZZ) 

sage: for p1 in [2*y^3 - y + 3, -y^5 - 2, 4*y - 3]: 

....: for p2 in [5*y^2 - 7, -3*y - 1]: 

....: for monic in [True,False]: 

....: for op in [operator.add, operator.sub, operator.mul, operator.truediv]: 

....: pr = p1.composed_op(p2, op, "resultant", monic=monic) 

....: pb = p1.composed_op(p2, op, "BFSS", monic=monic) 

....: assert ((pr == pb) or ((not monic) and pr == -pb) and (parent(pr) is parent(pb))) 

  

REFERENCES: 

  

.. [BFSS] \A. Bostan, P. Flajolet, B. Salvy and E. Schost, 

*Fast Computation of special resultants*, 

Journal of Symbolic Computation 41 (2006), 1-29 

""" 

cdef long j 

cdef long prec 

  

try: 

if op is operator.div: 

op = operator.truediv 

except AttributeError: 

pass 

  

if op not in (operator.add, operator.sub, operator.mul, operator.truediv): 

raise ValueError("op must be operator.OP where OP=add, sub, mul or truediv") 

  

if not isinstance(p2, Polynomial): 

raise TypeError("p2 must be a polynomial") 

p1, p2 = coercion_model.canonical_coercion(p1, p2) 

K = p1.parent() 

assert is_PolynomialRing(p1.parent()) 

S = K.base_ring() 

Sf = S.fraction_field() 

  

cdef long d1 = p1.degree() 

cdef long d2 = p2.degree() 

if d1 <= 0 or d2 <= 0: 

raise ValueError('the polynomials must have positive degree') 

  

if op is operator.truediv and p2.valuation() > 0: 

raise ZeroDivisionError('p2 must have zero valuation') 

if algorithm is None: 

# choose the algorithm observing that the "resultant" one 

# is fast when there are few terms and the degrees are not high 

N = 7 

if Sf is not QQ or (d1 <= N and d2 <= N): 

algorithm = "resultant" 

else: 

c = d1*sum(bool(p1[i]) for i in range(d1 + 1))*\ 

d2*sum(bool(p2[i]) for i in range(d2 + 1)) 

if c <= N**4: 

algorithm = "resultant" 

else: 

algorithm = "BFSS" 

  

if algorithm == "resultant": 

R = K['x', 'y'] 

x = R.gen(0) 

y = R.gen(1) 

if op is operator.add: 

lp = p1(x - y) 

elif op is operator.sub: 

lp = p1(x + y) 

elif op is operator.mul: 

lp = p1(x).homogenize(y) 

else: 

lp = p1(x * y) 

q = p2(y).resultant(lp, y).univariate_polynomial(K) 

return q.monic() if monic else q 

  

elif algorithm == "BFSS": 

if Sf is not QQ: 

raise ValueError("BFSS algorithm is available only for the base ring ZZ or QQ") 

if op is operator.sub: 

p2 = p2(-K.gen()) 

elif op is operator.truediv: 

p2 = p2.reverse() 

# the computation below needs must be done in the fraction field 

# even though the result would have the same ring 

if Sf is not S: 

K = K.change_ring(Sf) 

p1 = p1.change_ring(Sf) 

p2 = p2.change_ring(Sf) 

prec = d1*d2 + 1 

np1 = p1.reverse().inverse_series_trunc(prec) 

np1 = np1._mul_trunc_(p1.derivative().reverse(), prec) 

np2 = p2.reverse().inverse_series_trunc(prec) 

np2 = np2._mul_trunc_(p2.derivative().reverse(), prec) 

if op in (operator.add, operator.sub): 

# compute np1e and np2e, the Hadamard products of respectively 

# np1 and np2 with the exponential series. That is 

# a0 + a1 x + a2 x^2 + ... 

# -> 

# a0 + a1/1! x + a2/2! x^2 + ... 

fj = Sf.one() 

a1, a2 = [np1[0]], [np2[0]] 

for j in range(1, prec): 

fj = fj*j 

a1.append(np1[j] / fj) 

a2.append(np2[j] / fj) 

np1e = K(a1) 

np2e = K(a2) 

  

# recover the polynomial from its Newton series 

np3e = np1e*np2e 

fj = -Sf.one() 

a3 = [Sf.zero()] 

for j in range(1, prec): 

a3.append(np3e[j] * fj) 

fj = fj*j 

np = K(a3) 

q = np 

else: 

np = K([-np1[j]*np2[j] for j in range(1, prec)]) 

q = np.integral() 

  

q = q._exp_series(prec).reverse() 

q = q.shift(prec - q.degree() - 1) 

if monic: 

return q 

else: 

return (p1.leading_coefficient()**p2.degree() * 

p2.leading_coefficient()**p1.degree() * q).change_ring(S) 

  

else: 

raise ValueError('algorithm must be "resultant" or "BFSS"') 

  

def compose_power(self, k, algorithm=None, monic=False): 

r""" 

Return the `k`-th iterate of the composed product of this 

polynomial with itself. 

  

INPUT: 

  

- `k` -- a non-negative integer 

  

- ``algorithm`` -- ``None`` (default), ``"resultant"`` or ``"BFSS"``. 

See :meth:`.composed_op` 

  

- ``monic`` - ``False`` (default) or ``True``. 

See :meth:`.composed_op` 

  

OUTPUT: 

  

The polynomial of degree `d^k` where `d` is the degree, whose 

roots are all `k`-fold products of roots of this polynomial. 

That is, `f*f*\dots*f` where this is `f` and 

`f*f=` f.composed_op(f,operator.mul). 

  

EXAMPLES:: 

  

sage: R.<a,b,c> = ZZ[] 

sage: x = polygen(R) 

sage: f = (x-a)*(x-b)*(x-c) 

sage: f.compose_power(2).factor() 

(x - c^2) * (x - b^2) * (x - a^2) * (x - b*c)^2 * (x - a*c)^2 * (x - a*b)^2 

  

sage: x = polygen(QQ) 

sage: f = x^2-2*x+2 

sage: f2 = f.compose_power(2); f2 

x^4 - 4*x^3 + 8*x^2 - 16*x + 16 

sage: f2 == f.composed_op(f,operator.mul) 

True 

sage: f3 = f.compose_power(3); f3 

x^8 - 8*x^7 + 32*x^6 - 64*x^5 + 128*x^4 - 512*x^3 + 2048*x^2 - 4096*x + 4096 

sage: f3 == f2.composed_op(f,operator.mul) 

True 

sage: f4 = f.compose_power(4) 

sage: f4 == f3.composed_op(f,operator.mul) 

True 

""" 

try: 

k = ZZ(k) 

except ValueError("Cannot iterate {} times".format(k)): 

return self 

if k < 0: 

raise ValueError("Cannot iterate a negative number {} of times".format(k)) 

if k == 0: 

return self.variables()[0] - 1 

if k == 1: 

return self 

if k == 2: 

return self.composed_op(self, operator.mul, 

algorithm=algorithm, monic=monic) 

k2, k1 = k.quo_rem(2) 

# recurse to get the k/2 -iterate where k=2*k2+k1: 

R = self.compose_power(k2, algorithm=algorithm, monic=monic) 

# square: 

R = R.composed_op(R, operator.mul, algorithm=algorithm, monic=monic) 

# one more factor if k odd: 

if k1: 

R = R.composed_op(self, operator.mul) 

return R 

  

def adams_operator(self, n, monic=False): 

r""" 

Return the polynomial whose roots are the `n`-th power 

of the roots of this. 

  

INPUT: 

  

- `n` -- an integer 

  

- ``monic`` -- boolean (default ``False``) 

if set to ``True``, force the output to be monic 

  

EXAMPLES:: 

  

sage: f = cyclotomic_polynomial(30) 

sage: f.adams_operator(7)==f 

True 

sage: f.adams_operator(6) == cyclotomic_polynomial(5)**2 

True 

sage: f.adams_operator(10) == cyclotomic_polynomial(3)**4 

True 

sage: f.adams_operator(15) == cyclotomic_polynomial(2)**8 

True 

sage: f.adams_operator(30) == cyclotomic_polynomial(1)**8 

True 

  

sage: x = polygen(QQ) 

sage: f = x^2-2*x+2 

sage: f.adams_operator(10) 

x^2 + 1024 

  

When f is monic the output will have leading coefficient 

`\pm1` depending on the degree, but we can force it to be 

monic:: 

  

sage: R.<a,b,c> = ZZ[] 

sage: x = polygen(R) 

sage: f = (x-a)*(x-b)*(x-c) 

sage: f.adams_operator(3).factor() 

(-1) * (x - c^3) * (x - b^3) * (x - a^3) 

sage: f.adams_operator(3,monic=True).factor() 

(x - c^3) * (x - b^3) * (x - a^3) 

  

""" 

u, v = PolynomialRing(self._parent.base_ring(), ['u', 'v']).gens() 

R = (u - v**n).resultant(self(v), v) 

R = R([self.variables()[0], 0]) 

if monic: 

R = R.monic() 

return R 

  

def symmetric_power(self, k, monic=False): 

r""" 

Return the polynomial whose roots are products of `k`-th distinct 

roots of this. 

  

EXAMPLES:: 

  

sage: x = polygen(QQ) 

sage: f = x^4-x+2 

sage: [f.symmetric_power(k) for k in range(5)] 

[x - 1, x^4 - x + 2, x^6 - 2*x^4 - x^3 - 4*x^2 + 8, x^4 - x^3 + 8, x - 2] 

  

sage: f = x^5-2*x+2 

sage: [f.symmetric_power(k) for k in range(6)] 

[x - 1, 

x^5 - 2*x + 2, 

x^10 + 2*x^8 - 4*x^6 - 8*x^5 - 8*x^4 - 8*x^3 + 16, 

x^10 + 4*x^7 - 8*x^6 + 16*x^5 - 16*x^4 + 32*x^2 + 64, 

x^5 + 2*x^4 - 16, 

x + 2] 

  

sage: R.<a,b,c,d> = ZZ[] 

sage: x = polygen(R) 

sage: f = (x-a)*(x-b)*(x-c)*(x-d) 

sage: [f.symmetric_power(k).factor() for k in range(5)] 

[x - 1, 

(-x + d) * (-x + c) * (-x + b) * (-x + a), 

(x - c*d) * (x - b*d) * (x - a*d) * (x - b*c) * (x - a*c) * (x - a*b), 

(x - b*c*d) * (x - a*c*d) * (x - a*b*d) * (x - a*b*c), 

x - a*b*c*d] 

""" 

try: 

k = ZZ(k) 

except (ValueError, TypeError): 

raise ValueError("Cannot compute k'th symmetric power for k={}".format(k)) 

n = self.degree() 

if k < 0 or k > n: 

raise ValueError("Cannot compute k'th symmetric power for k={}".format(k)) 

x = self.variables()[0] 

if k == 0: 

return x - 1 

if k == 1: 

if monic: 

return self.monic() 

return self 

c = (-1)**n * self(0) 

if k == n: 

return x - c 

if k > n - k: # use (n-k)'th symmetric power 

g = self.symmetric_power(n - k, monic=monic) 

from sage.arith.all import binomial 

g = ((-x)**binomial(n,k) * g(c/x) / c**binomial(n-1,k)).numerator() 

if monic: 

g = g.monic() 

return g 

  

def star(g, h): 

return g.composed_op(h, operator.mul, monic=True) 

  

def rpow(g, n): 

return g.adams_operator(n, monic=True) 

if k == 2: 

g = (star(self, self) // rpow(self, 2)).nth_root(2) 

if monic: 

g = g.monic() 

return g 

if k == 3: 

g = star(self.symmetric_power(2, monic=monic), self) * rpow(self, 3) 

h = star(rpow(self, 2), self) 

g = (g // h).nth_root(3) 

if monic: 

g = g.monic() 

return g 

  

fkn = fkd = self._parent.one() 

for j in range(1, k + 1): 

g = star(rpow(self, j), self.symmetric_power(k - j)) 

if j % 2: 

fkn *= g 

else: 

fkd *= g 

  

fk = fkn // fkd 

assert fk * fkd == fkn 

g = fk.nth_root(k) 

if monic: 

g = g.monic() 

return g 

  

def discriminant(self): 

r""" 

Returns the discriminant of self. 

  

The discriminant is 

  

.. MATH:: 

  

R_n := a_n^{2 n-2} \prod_{1<i<j<n} (r_i-r_j)^2, 

  

where `n` is the degree of self, `a_n` is the 

leading coefficient of self and the roots of self are 

`r_1, \ldots, r_n`. 

  

OUTPUT: An element of the base ring of the polynomial ring. 

  

ALGORITHM: 

  

Uses the identity `R_n(f) := (-1)^{n (n-1)/2} R(f, f') 

a_n^{n-k-2}`, where `n` is the degree of self, `a_n` is the 

leading coefficient of self, `f'` is the derivative of `f`, 

and `k` is the degree of `f'`. Calls :meth:`.resultant`. 

  

EXAMPLES: 

  

In the case of elliptic curves in special form, the discriminant is 

easy to calculate:: 

  

sage: R.<x> = QQ[] 

sage: f = x^3 + x + 1 

sage: d = f.discriminant(); d 

-31 

sage: d.parent() is QQ 

True 

sage: EllipticCurve([1, 1]).discriminant()/16 

-31 

  

:: 

  

sage: R.<x> = QQ[] 

sage: f = 2*x^3 + x + 1 

sage: d = f.discriminant(); d 

-116 

  

We can compute discriminants over univariate and multivariate 

polynomial rings:: 

  

sage: R.<a> = QQ[] 

sage: S.<x> = R[] 

sage: f = a*x + x + a + 1 

sage: d = f.discriminant(); d 

1 

sage: d.parent() is R 

True 

  

:: 

  

sage: R.<a, b> = QQ[] 

sage: S.<x> = R[] 

sage: f = x^2 + a + b 

sage: d = f.discriminant(); d 

-4*a - 4*b 

sage: d.parent() is R 

True 

  

TESTS:: 

  

sage: R.<x, y> = QQ[] 

sage: S.<a> = R[] 

sage: f = x^2 + a 

sage: f.discriminant() 

1 

  

Check that :trac:`13672` is fixed:: 

  

sage: R.<t> = GF(5)[] 

sage: S.<x> = R[] 

sage: f = x^10 + 2*x^6 + 2*x^5 + x + 2 

sage: (f-t).discriminant() 

4*t^5 

  

The following examples show that :trac:`11782` has been fixed:: 

  

sage: var('x') 

x 

sage: ZZ.quo(81)['x'](3*x^2 + 3*x + 3).discriminant() 

54 

sage: ZZ.quo(9)['x'](2*x^3 + x^2 + x).discriminant() 

2 

  

This was fixed by :trac:`15422`:: 

  

sage: R.<s> = PolynomialRing(Qp(2)) 

sage: (s^2).discriminant() 

0 

  

This was fixed by :trac:`16014`:: 

  

sage: PR.<b,t1,t2,x1,y1,x2,y2> = QQ[] 

sage: PRmu.<mu> = PR[] 

sage: E1 = diagonal_matrix(PR, [1, b^2, -b^2]) 

sage: M = matrix(PR, [[1,-t1,x1-t1*y1],[t1,1,y1+t1*x1],[0,0,1]]) 

sage: E1 = M.transpose()*E1*M 

sage: E2 = E1.subs(t1=t2, x1=x2, y1=y2) 

sage: det(mu*E1 + E2).discriminant().degrees() 

(24, 12, 12, 8, 8, 8, 8) 

  

This addresses an issue raised by :trac:`15061`:: 

  

sage: R.<T> = PowerSeriesRing(QQ) 

sage: F = R([1,1],2) 

sage: RP.<x> = PolynomialRing(R) 

sage: P = x^2 - F 

sage: P.discriminant() 

4 + 4*T + O(T^2) 

""" 

# Late import to avoid cyclic dependencies: 

from sage.rings.power_series_ring import is_PowerSeriesRing 

if self.is_zero(): 

return self._parent.zero() 

n = self.degree() 

base_ring = self._parent.base_ring() 

if (is_MPolynomialRing(base_ring) or 

is_PowerSeriesRing(base_ring)): 

# It is often cheaper to compute discriminant of simple 

# multivariate polynomial and substitute the real 

# coefficients into that result (see #16014). 

return universal_discriminant(n)(list(self)) 

d = self.derivative() 

k = d.degree() 

  

r = n % 4 

u = -1 # (-1)**(n*(n-1)/2) 

if r == 0 or r == 1: 

u = 1 

try: 

an = self[n]**(n - k - 2) 

except ZeroDivisionError: 

assert(n-k-2 == -1) 

# Rather than dividing the resultant by the leading coefficient, 

# we alter the Sylvester matrix (see #11782). 

mat = self.sylvester_matrix(d) 

mat[0, 0] = self.base_ring()(1) 

mat[n - 1, 0] = self.base_ring()(n) 

return u * mat.determinant() 

else: 

return self.base_ring()(u * self.resultant(d) * an) 

  

def reverse(self, degree=None): 

""" 

Return polynomial but with the coefficients reversed. 

  

If an optional degree argument is given the coefficient list will be 

truncated or zero padded as necessary before reversing it. Assuming 

that the constant coefficient of ``self`` is nonzero, the reverse 

polynomial will have the specified degree. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[]; S.<y> = R[] 

sage: f = y^3 + x*y -3*x; f 

y^3 + x*y - 3*x 

sage: f.reverse() 

-3*x*y^3 + x*y^2 + 1 

sage: f.reverse(degree=2) 

-3*x*y^2 + x*y 

sage: f.reverse(degree=5) 

-3*x*y^5 + x*y^4 + y^2 

  

TESTS:: 

  

sage: f.reverse(degree=1.5r) 

Traceback (most recent call last): 

... 

ValueError: degree argument must be a non-negative integer, got 1.5 

  

sage: f.reverse(0) 

-3*x 

sage: f 

y^3 + x*y - 3*x 

""" 

v = self.list() 

  

cdef unsigned long d 

if degree is not None: 

d = degree 

if d != degree: 

raise ValueError("degree argument must be a non-negative integer, got %s"%(degree)) 

if len(v) < degree+1: 

v.reverse() 

v = [0]*(degree+1-len(v)) + v 

elif len(v) > degree+1: 

v = v[:degree+1] 

v.reverse() 

else: # len(v) == degree + 1 

v.reverse() 

else: 

v.reverse() 

  

return self._new_generic(v) 

  

def roots(self, ring=None, multiplicities=True, algorithm=None, **kwds): 

""" 

Return the roots of this polynomial (by default, in the base ring 

of this polynomial). 

  

INPUT: 

  

  

- ``ring`` - the ring to find roots in 

  

- ``multiplicities`` - bool (default: True) if True 

return list of pairs (r, n), where r is the root and n is the 

multiplicity. If False, just return the unique roots, with no 

information about multiplicities. 

  

- ``algorithm`` - the root-finding algorithm to use. 

We attempt to select a reasonable algorithm by default, but this 

lets the caller override our choice. 

  

  

By default, this finds all the roots that lie in the base ring of 

the polynomial. However, the ring parameter can be used to specify 

a ring to look for roots in. 

  

If the polynomial and the output ring are both exact (integers, 

rationals, finite fields, etc.), then the output should always be 

correct (or raise an exception, if that case is not yet handled). 

  

If the output ring is approximate (floating-point real or complex 

numbers), then the answer will be estimated numerically, using 

floating-point arithmetic of at least the precision of the output 

ring. If the polynomial is ill-conditioned, meaning that a small 

change in the coefficients of the polynomial will lead to a 

relatively large change in the location of the roots, this may give 

poor results. Distinct roots may be returned as multiple roots, 

multiple roots may be returned as distinct roots, real roots may be 

lost entirely (because the numerical estimate thinks they are 

complex roots). Note that polynomials with multiple roots are 

always ill-conditioned; there's a footnote at the end of the 

docstring about this. 

  

If the output ring is a RealIntervalField or ComplexIntervalField 

of a given precision, then the answer will always be correct (or an 

exception will be raised, if a case is not implemented). Each root 

will be contained in one of the returned intervals, and the 

intervals will be disjoint. (The returned intervals may be of 

higher precision than the specified output ring.) 

  

At the end of this docstring (after the examples) is a description 

of all the cases implemented in this function, and the algorithms 

used. That section also describes the possibilities for 

"algorithm=", for the cases where multiple algorithms exist. 

  

EXAMPLES:: 

  

sage: x = QQ['x'].0 

sage: f = x^3 - 1 

sage: f.roots() 

[(1, 1)] 

sage: f.roots(ring=CC) # note -- low order bits slightly different on ppc. 

[(1.00000000000000, 1), (-0.500000000000000 - 0.86602540378443...*I, 1), (-0.500000000000000 + 0.86602540378443...*I, 1)] 

sage: f = (x^3 - 1)^2 

sage: f.roots() 

[(1, 2)] 

  

:: 

  

sage: f = -19*x + 884736 

sage: f.roots() 

[(884736/19, 1)] 

sage: (f^20).roots() 

[(884736/19, 20)] 

  

:: 

  

sage: K.<z> = CyclotomicField(3) 

sage: f = K.defining_polynomial() 

sage: f.roots(ring=GF(7)) 

[(4, 1), (2, 1)] 

sage: g = f.change_ring(GF(7)) 

sage: g.roots() 

[(4, 1), (2, 1)] 

sage: g.roots(multiplicities=False) 

[4, 2] 

  

A new ring. In the example below, we add the special method 

_roots_univariate_polynomial to the base ring, and observe 

that this method is called instead to find roots of 

polynomials over this ring. This facility can be used to 

easily extend root finding to work over new rings you 

introduce:: 

  

sage: R.<x> = QQ[] 

sage: (x^2 + 1).roots() 

[] 

sage: g = lambda f, *args, **kwds: f.change_ring(CDF).roots() 

sage: QQ._roots_univariate_polynomial = g 

sage: (x^2 + 1).roots() # abs tol 1e-14 

[(2.7755575615628914e-17 - 1.0*I, 1), (0.9999999999999997*I, 1)] 

sage: del QQ._roots_univariate_polynomial 

  

An example over RR, which illustrates that only the roots in RR are 

returned:: 

  

sage: x = RR['x'].0 

sage: f = x^3 -2 

sage: f.roots() 

[(1.25992104989487, 1)] 

sage: f.factor() 

(x - 1.25992104989487) * (x^2 + 1.25992104989487*x + 1.58740105196820) 

sage: x = RealField(100)['x'].0 

sage: f = x^3 -2 

sage: f.roots() 

[(1.2599210498948731647672106073, 1)] 

  

:: 

  

sage: x = CC['x'].0 

sage: f = x^3 -2 

sage: f.roots() 

[(1.25992104989487, 1), (-0.62996052494743... - 1.09112363597172*I, 1), (-0.62996052494743... + 1.09112363597172*I, 1)] 

sage: f.roots(algorithm='pari') 

[(1.25992104989487, 1), (-0.629960524947437 - 1.09112363597172*I, 1), (-0.629960524947437 + 1.09112363597172*I, 1)] 

  

Another example showing that only roots in the base ring are 

returned:: 

  

sage: x = polygen(ZZ) 

sage: f = (2*x-3) * (x-1) * (x+1) 

sage: f.roots() 

[(1, 1), (-1, 1)] 

sage: f.roots(ring=QQ) 

[(3/2, 1), (1, 1), (-1, 1)] 

  

An example involving large numbers:: 

  

sage: x = RR['x'].0 

sage: f = x^2 - 1e100 

sage: f.roots() 

[(-1.00000000000000e50, 1), (1.00000000000000e50, 1)] 

sage: f = x^10 - 2*(5*x-1)^2 

sage: f.roots(multiplicities=False) 

[-1.6772670339941..., 0.19995479628..., 0.20004530611..., 1.5763035161844...] 

  

:: 

  

sage: x = CC['x'].0 

sage: i = CC.0 

sage: f = (x - 1)*(x - i) 

sage: f.roots(multiplicities=False) 

[1.00000000000000, 1.00000000000000*I] 

sage: g=(x-1.33+1.33*i)*(x-2.66-2.66*i) 

sage: g.roots(multiplicities=False) 

[1.33000000000000 - 1.33000000000000*I, 2.66000000000000 + 2.66000000000000*I] 

  

Describing roots using radical expressions:: 

  

sage: x = QQ['x'].0 

sage: f = x^2 + 2 

sage: f.roots(SR) 

[(-I*sqrt(2), 1), (I*sqrt(2), 1)] 

sage: f.roots(SR, multiplicities=False) 

[-I*sqrt(2), I*sqrt(2)] 

  

The roots of some polynomials can't be described using radical 

expressions:: 

  

sage: (x^5 - x + 1).roots(SR) 

[] 

  

For some other polynomials, no roots can be found at the moment 

due to the way roots are computed. :trac:`17516` addresses 

these defecits. Until that gets implemented, one such example 

is the following:: 

  

sage: f = x^6-300*x^5+30361*x^4-1061610*x^3+1141893*x^2-915320*x+101724 

sage: f.roots() 

[] 

  

A purely symbolic roots example:: 

  

sage: X = var('X') 

sage: f = expand((X-1)*(X-I)^3*(X^2 - sqrt(2))); f 

X^6 - (3*I + 1)*X^5 - sqrt(2)*X^4 + (3*I - 3)*X^4 + (3*I + 1)*sqrt(2)*X^3 + (I + 3)*X^3 - (3*I - 3)*sqrt(2)*X^2 - I*X^2 - (I + 3)*sqrt(2)*X + I*sqrt(2) 

sage: f.roots() 

[(I, 3), (-2^(1/4), 1), (2^(1/4), 1), (1, 1)] 

  

The same operation, performed over a polynomial ring 

with symbolic coefficients:: 

  

sage: X = SR['X'].0 

sage: f = (X-1)*(X-I)^3*(X^2 - sqrt(2)); f 

X^6 + (-3*I - 1)*X^5 + (-sqrt(2) + 3*I - 3)*X^4 + ((3*I + 1)*sqrt(2) + I + 3)*X^3 + (-(3*I - 3)*sqrt(2) - I)*X^2 + (-(I + 3)*sqrt(2))*X + I*sqrt(2) 

sage: f.roots() 

[(I, 3), (-2^(1/4), 1), (2^(1/4), 1), (1, 1)] 

sage: f.roots(multiplicities=False) 

[I, -2^(1/4), 2^(1/4), 1] 

  

A couple of examples where the base ring doesn't have a 

factorization algorithm (yet). Note that this is currently done via 

naive enumeration, so could be very slow:: 

  

sage: R = Integers(6) 

sage: S.<x> = R['x'] 

sage: p = x^2-1 

sage: p.roots() 

Traceback (most recent call last): 

... 

NotImplementedError: root finding with multiplicities for this polynomial not implemented (try the multiplicities=False option) 

sage: p.roots(multiplicities=False) 

[1, 5] 

sage: R = Integers(9) 

sage: A = PolynomialRing(R, 'y') 

sage: y = A.gen() 

sage: f = 10*y^2 - y^3 - 9 

sage: f.roots(multiplicities=False) 

[0, 1, 3, 6] 

  

An example over the complex double field (where root finding is 

fast, thanks to NumPy):: 

  

sage: R.<x> = CDF[] 

sage: f = R.cyclotomic_polynomial(5); f 

x^4 + x^3 + x^2 + x + 1.0 

sage: f.roots(multiplicities=False) # abs tol 1e-9 

[-0.8090169943749469 - 0.5877852522924724*I, -0.8090169943749473 + 0.5877852522924724*I, 0.30901699437494773 - 0.951056516295154*I, 0.30901699437494756 + 0.9510565162951525*I] 

sage: [z^5 for z in f.roots(multiplicities=False)] # abs tol 2e-14 

[0.9999999999999957 - 1.2864981197413038e-15*I, 0.9999999999999976 + 3.062854959141552e-15*I, 1.0000000000000024 + 1.1331077795295987e-15*I, 0.9999999999999953 - 2.0212861992297117e-15*I] 

sage: f = CDF['x']([1,2,3,4]); f 

4.0*x^3 + 3.0*x^2 + 2.0*x + 1.0 

sage: r = f.roots(multiplicities=False) 

sage: [f(a).abs() for a in r] # abs tol 1e-14 

[2.574630599127759e-15, 1.457101633618084e-15, 1.1443916996305594e-15] 

  

Another example over RDF:: 

  

sage: x = RDF['x'].0 

sage: ((x^3 -1)).roots() # abs tol 4e-16 

[(1.0000000000000002, 1)] 

sage: ((x^3 -1)).roots(multiplicities=False) # abs tol 4e-16 

[1.0000000000000002] 

  

More examples involving the complex double field:: 

  

sage: x = CDF['x'].0 

sage: i = CDF.0 

sage: f = x^3 + 2*i; f 

x^3 + 2.0*I 

sage: f.roots() # abs tol 1e-14 

[(-1.0911236359717227 - 0.6299605249474374*I, 1), (3.885780586188048e-16 + 1.2599210498948734*I, 1), (1.0911236359717211 - 0.6299605249474363*I, 1)] 

sage: f.roots(multiplicities=False) # abs tol 1e-14 

[-1.0911236359717227 - 0.6299605249474374*I, 3.885780586188048e-16 + 1.2599210498948734*I, 1.0911236359717211 - 0.6299605249474363*I] 

sage: [abs(f(z)) for z in f.roots(multiplicities=False)] # abs tol 1e-14 

[8.95090418262362e-16, 8.728374398092689e-16, 1.0235750533041806e-15] 

sage: f = i*x^3 + 2; f 

I*x^3 + 2.0 

sage: f.roots() # abs tol 1e-14 

[(-1.0911236359717227 + 0.6299605249474374*I, 1), (3.885780586188048e-16 - 1.2599210498948734*I, 1), (1.0911236359717211 + 0.6299605249474363*I, 1)] 

sage: abs(f(f.roots()[0][0])) # abs tol 1e-13 

1.1102230246251565e-16 

  

Examples using real root isolation:: 

  

sage: x = polygen(ZZ) 

sage: f = x^2 - x - 1 

sage: f.roots() 

[] 

sage: f.roots(ring=RIF) 

[(-0.6180339887498948482045868343657?, 1), (1.6180339887498948482045868343657?, 1)] 

sage: f.roots(ring=RIF, multiplicities=False) 

[-0.6180339887498948482045868343657?, 1.6180339887498948482045868343657?] 

sage: f.roots(ring=RealIntervalField(150)) 

[(-0.6180339887498948482045868343656381177203091798057628621354486227?, 1), (1.618033988749894848204586834365638117720309179805762862135448623?, 1)] 

sage: f.roots(ring=AA) 

[(-0.618033988749895?, 1), (1.618033988749895?, 1)] 

sage: f = f^2 * (x - 1) 

sage: f.roots(ring=RIF) 

[(-0.6180339887498948482045868343657?, 2), (1.0000000000000000000000000000000?, 1), (1.6180339887498948482045868343657?, 2)] 

sage: f.roots(ring=RIF, multiplicities=False) 

[-0.6180339887498948482045868343657?, 1.0000000000000000000000000000000?, 1.6180339887498948482045868343657?] 

  

Examples using complex root isolation:: 

  

sage: x = polygen(ZZ) 

sage: p = x^5 - x - 1 

sage: p.roots() 

[] 

sage: p.roots(ring=CIF) 

[(1.167303978261419?, 1), (-0.764884433600585? - 0.352471546031727?*I, 1), (-0.764884433600585? + 0.352471546031727?*I, 1), (0.181232444469876? - 1.083954101317711?*I, 1), (0.181232444469876? + 1.083954101317711?*I, 1)] 

sage: p.roots(ring=ComplexIntervalField(200)) 

[(1.167303978261418684256045899854842180720560371525489039140082?, 1), (-0.76488443360058472602982318770854173032899665194736756700778? - 0.35247154603172624931794709140258105439420648082424733283770?*I, 1), (-0.76488443360058472602982318770854173032899665194736756700778? + 0.35247154603172624931794709140258105439420648082424733283770?*I, 1), (0.18123244446987538390180023778112063996871646618462304743774? - 1.08395410131771066843034449298076657427364024315511565430114?*I, 1), (0.18123244446987538390180023778112063996871646618462304743774? + 1.08395410131771066843034449298076657427364024315511565430114?*I, 1)] 

sage: rts = p.roots(ring=QQbar); rts 

[(1.167303978261419?, 1), (-0.7648844336005847? - 0.3524715460317263?*I, 1), (-0.7648844336005847? + 0.3524715460317263?*I, 1), (0.1812324444698754? - 1.083954101317711?*I, 1), (0.1812324444698754? + 1.083954101317711?*I, 1)] 

sage: p.roots(ring=AA) 

[(1.167303978261419?, 1)] 

sage: p = (x - rts[4][0])^2 * (3*x^2 + x + 1) 

sage: p.roots(ring=QQbar) 

[(-0.1666666666666667? - 0.552770798392567?*I, 1), (-0.1666666666666667? + 0.552770798392567?*I, 1), (0.1812324444698754? + 1.083954101317711?*I, 2)] 

sage: p.roots(ring=CIF) 

[(-0.1666666666666667? - 0.552770798392567?*I, 1), (-0.1666666666666667? + 0.552770798392567?*I, 1), (0.1812324444698754? + 1.083954101317711?*I, 2)] 

  

Note that coefficients in a number field with defining polynomial 

`x^2 + 1` are considered to be Gaussian rationals (with the 

generator mapping to +I), if you ask for complex roots. 

  

:: 

  

sage: K.<im> = QuadraticField(-1) 

sage: y = polygen(K) 

sage: p = y^4 - 2 - im 

sage: p.roots(ring=CC) 

[(-1.2146389322441... - 0.14142505258239...*I, 1), (-0.14142505258239... + 1.2146389322441...*I, 1), (0.14142505258239... - 1.2146389322441...*I, 1), (1.2146389322441... + 0.14142505258239...*I, 1)] 

sage: p = p^2 * (y^2 - 2) 

sage: p.roots(ring=CIF) 

[(-1.414213562373095?, 1), (1.414213562373095?, 1), (-1.214638932244183? - 0.141425052582394?*I, 2), (-0.141425052582394? + 1.214638932244183?*I, 2), (0.141425052582394? - 1.214638932244183?*I, 2), (1.214638932244183? + 0.141425052582394?*I, 2)] 

  

Note that one should not use NumPy when wanting high precision 

output as it does not support any of the high precision types:: 

  

sage: R.<x> = RealField(200)[] 

sage: f = x^2 - R(pi) 

sage: f.roots() 

[(-1.7724538509055160272981674833411451827975494561223871282138, 1), (1.7724538509055160272981674833411451827975494561223871282138, 1)] 

sage: f.roots(algorithm='numpy') 

doctest... UserWarning: NumPy does not support arbitrary precision arithmetic. The roots found will likely have less precision than you expect. 

[(-1.77245385090551..., 1), (1.77245385090551..., 1)] 

  

We can also find roots over number fields:: 

  

sage: K.<z> = CyclotomicField(15) 

sage: R.<x> = PolynomialRing(K) 

sage: (x^2 + x + 1).roots() 

[(z^5, 1), (-z^5 - 1, 1)] 

  

There are many combinations of floating-point input and output 

types that work. (Note that some of them are quite pointless like using 

``algorithm='numpy'`` with high-precision types.) 

  

:: 

  

sage: rflds = (RR, RDF, RealField(100)) 

sage: cflds = (CC, CDF, ComplexField(100)) 

sage: def cross(a, b): 

....: return list(cartesian_product_iterator([a, b])) 

sage: flds = cross(rflds, rflds) + cross(rflds, cflds) + cross(cflds, cflds) 

sage: for (fld_in, fld_out) in flds: 

....: x = polygen(fld_in) 

....: f = x^3 - fld_in(2) 

....: x2 = polygen(fld_out) 

....: f2 = x2^3 - fld_out(2) 

....: for algo in (None, 'pari', 'numpy'): 

....: rts = f.roots(ring=fld_out, multiplicities=False) 

....: if fld_in == fld_out and algo is None: 

....: print("{} {}".format(fld_in, rts)) 

....: for rt in rts: 

....: assert(abs(f2(rt)) <= 1e-10) 

....: assert(rt.parent() == fld_out) 

Real Field with 53 bits of precision [1.25992104989487] 

Real Double Field [1.25992104989...] 

Real Field with 100 bits of precision [1.2599210498948731647672106073] 

Complex Field with 53 bits of precision [1.25992104989487, -0.62996052494743... - 1.09112363597172*I, -0.62996052494743... + 1.09112363597172*I] 

Complex Double Field [1.25992104989..., -0.629960524947... - 1.0911236359717...*I, -0.629960524947... + 1.0911236359717...*I] 

Complex Field with 100 bits of precision [1.2599210498948731647672106073, -0.62996052494743658238360530364 - 1.0911236359717214035600726142*I, -0.62996052494743658238360530364 + 1.0911236359717214035600726142*I] 

  

Note that we can find the roots of a polynomial with algebraic 

coefficients:: 

  

sage: rt2 = sqrt(AA(2)) 

sage: rt3 = sqrt(AA(3)) 

sage: x = polygen(AA) 

sage: f = (x - rt2) * (x - rt3); f 

x^2 - 3.146264369941973?*x + 2.449489742783178? 

sage: rts = f.roots(); rts 

[(1.414213562373095?, 1), (1.732050807568878?, 1)] 

sage: rts[0][0] == rt2 

True 

sage: f.roots(ring=RealIntervalField(150)) 

[(1.414213562373095048801688724209698078569671875376948073176679738?, 1), (1.732050807568877293527446341505872366942805253810380628055806980?, 1)] 

  

We can handle polynomials with huge coefficients. 

  

This number doesn't even fit in an IEEE double-precision float, but 

RR and CC allow a much larger range of floating-point numbers:: 

  

sage: bigc = 2^1500 

sage: CDF(bigc) 

+infinity 

sage: CC(bigc) 

3.50746621104340e451 

  

Polynomials using such large coefficients can't be handled by 

numpy, but pari can deal with them:: 

  

sage: x = polygen(QQ) 

sage: p = x + bigc 

sage: p.roots(ring=RR, algorithm='numpy') 

Traceback (most recent call last): 

... 

LinAlgError: Array must not contain infs or NaNs 

sage: p.roots(ring=RR, algorithm='pari') 

[(-3.50746621104340e451, 1)] 

sage: p.roots(ring=AA) 

[(-3.5074662110434039?e451, 1)] 

sage: p.roots(ring=QQbar) 

[(-3.5074662110434039?e451, 1)] 

sage: p = bigc*x + 1 

sage: p.roots(ring=RR) 

[(0.000000000000000, 1)] 

sage: p.roots(ring=AA) 

[(-2.8510609648967059?e-452, 1)] 

sage: p.roots(ring=QQbar) 

[(-2.8510609648967059?e-452, 1)] 

sage: p = x^2 - bigc 

sage: p.roots(ring=RR) 

[(-5.92238652153286e225, 1), (5.92238652153286e225, 1)] 

sage: p.roots(ring=QQbar) 

[(-5.9223865215328558?e225, 1), (5.9223865215328558?e225, 1)] 

  

Algorithms used: 

  

For brevity, we will use RR to mean any RealField of any precision; 

similarly for RIF, CC, and CIF. Since Sage has no specific 

implementation of Gaussian rationals (or of number fields with 

embedding, at all), when we refer to Gaussian rationals below we 

will accept any number field with defining polynomial 

`x^2+1`, mapping the field generator to +I. 

  

We call the base ring of the polynomial K, and the ring given by 

the ring= argument L. (If ring= is not specified, then L is the 

same as K.) 

  

If K and L are floating-point (RDF, CDF, RR, or CC), then a 

floating-point root-finder is used. If L is RDF or CDF then we 

default to using NumPy's roots(); otherwise, we use PARI's 

polroots(). This choice can be overridden with 

algorithm='pari' or algorithm='numpy'. If the algorithm is 

unspecified and NumPy's roots() algorithm fails, then we fall 

back to pari (numpy will fail if some coefficient is infinite, 

for instance). 

  

If L is SR, then the roots will be radical expressions, 

computed as the solutions of a symbolic polynomial expression. 

At the moment this delegates to 

:meth:`sage.symbolic.expression.Expression.solve` 

which in turn uses Maxima to find radical solutions. 

Some solutions may be lost in this approach. 

Once :trac:`17516` gets implemented, all possible radical 

solutions should become available. 

  

If L is AA or RIF, and K is ZZ, QQ, or AA, then the root isolation 

algorithm sage.rings.polynomial.real_roots.real_roots() is used. 

(You can call real_roots() directly to get more control than this 

method gives.) 

  

If L is QQbar or CIF, and K is ZZ, QQ, AA, QQbar, or the Gaussian 

rationals, then the root isolation algorithm 

sage.rings.polynomial.complex_roots.complex_roots() is used. (You 

can call complex_roots() directly to get more control than this 

method gives.) 

  

If L is AA and K is QQbar or the Gaussian rationals, then 

complex_roots() is used (as above) to find roots in QQbar, then 

these roots are filtered to select only the real roots. 

  

If L is floating-point and K is not, then we attempt to change the 

polynomial ring to L (using .change_ring()) (or, if L is complex 

and K is not, to the corresponding real field). Then we use either 

PARI or numpy as specified above. 

  

For all other cases where K is different than L, we just use 

.change_ring(L) and proceed as below. 

  

The next method, which is used if K is an integral domain, is to 

attempt to factor the polynomial. If this succeeds, then for every 

degree-one factor a\*x+b, we add -b/a as a root (as long as this 

quotient is actually in the desired ring). 

  

If factoring over K is not implemented (or K is not an integral 

domain), and K is finite, then we find the roots by enumerating all 

elements of K and checking whether the polynomial evaluates to zero 

at that value. 

  

.. NOTE:: 

  

We mentioned above that polynomials with multiple roots are 

always ill-conditioned; if your input is given to n bits of 

precision, you should not expect more than n/k good bits 

for a k-fold root. (You can get solutions that make the 

polynomial evaluate to a number very close to zero; 

basically the problem is that with a multiple root, there 

are many such numbers, and it's difficult to choose between 

them.) 

  

To see why this is true, consider the naive floating-point 

error analysis model where you just pretend that all 

floating-point numbers are somewhat imprecise - a little 

'fuzzy', if you will. Then the graph of a floating-point 

polynomial will be a fuzzy line. Consider the graph of 

`(x-1)^3`; this will be a fuzzy line with a 

horizontal tangent at `x=1`, `y=0`. If the 

fuzziness extends up and down by about j, then it will 

extend left and right by about cube_root(j). 

  

TESTS:: 

  

sage: K.<zeta> = CyclotomicField(2) 

sage: R.<x> = K[] 

sage: factor(x^3-1) 

(x - 1) * (x^2 + x + 1) 

  

This shows that the issue from :trac:`6237` is fixed:: 

  

sage: R.<u> = QQ[] 

sage: g = -27*u^14 - 32*u^9 

sage: g.roots(CDF, multiplicities=False) # abs tol 2e-15 

[-1.0345637159435719, 0.0, -0.3196977699902601 - 0.9839285635706636*I, -0.3196977699902601 + 0.9839285635706636*I, 0.8369796279620465 - 0.6081012947885318*I, 0.8369796279620465 + 0.6081012947885318*I] 

sage: g.roots(CDF) # abs tol 2e-15 

[(-1.0345637159435719, 1), (0.0, 9), (-0.3196977699902601 - 0.9839285635706636*I, 1), (-0.3196977699902601 + 0.9839285635706636*I, 1), (0.8369796279620465 - 0.6081012947885318*I, 1), (0.8369796279620465 + 0.6081012947885318*I, 1)] 

  

This shows that the issue at :trac:`2418` is fixed:: 

  

sage: x = polygen(QQ) 

sage: p = (x^50/2^100 + x^10 + x + 1).change_ring(ComplexField(106)) 

sage: rts = (p/2^100).roots(multiplicities=False) 

sage: eps = 2^(-50) # we test the roots numerically 

sage: [abs(p(rt)) < eps for rt in rts] == [True]*50 

True 

  

This shows that the issue at :trac:`10901` is fixed:: 

  

sage: a = var('a'); R.<x> = SR[] 

sage: f = x - a 

sage: f.roots(RR) 

Traceback (most recent call last): 

... 

TypeError: Cannot evaluate symbolic expression to a numeric value. 

sage: f.roots(CC) 

Traceback (most recent call last): 

... 

TypeError: Cannot evaluate symbolic expression to a numeric value. 

  

We can find roots of polynomials defined over `\ZZ` or `\QQ` 

over the `p`-adics, see :trac:`15422`:: 

  

sage: R.<x> = ZZ[] 

sage: pol = (x - 1)^2 

sage: pol.roots(Qp(3,5)) 

[(1 + O(3^5), 2)] 

  

This doesn't work if we first change coefficients to `\QQ_p`:: 

  

sage: pol.change_ring(Qp(3,5)).roots() 

Traceback (most recent call last): 

... 

PrecisionError: p-adic factorization not well-defined since the discriminant is zero up to the requestion p-adic precision 

  

sage: (pol - 3^6).roots(Qp(3,5)) 

[(1 + 2*3^3 + 2*3^4 + O(3^5), 1), (1 + 3^3 + O(3^5), 1)] 

sage: r = pol.roots(Zp(3,5), multiplicities=False); r 

[1 + O(3^5)] 

sage: parent(r[0]) 

3-adic Ring with capped relative precision 5 

  

Spurious crash with pari-2.5.5, see :trac:`16165`:: 

  

sage: f=(1+x+x^2)^3 

sage: f.roots(ring=CC) 

[(-0.500000000000000 - 0.866025403784439*I, 3), 

(-0.500000000000000 + 0.866025403784439*I, 3)] 

  

Test a crash reported at :trac:`19649`:: 

  

sage: polRing.<x> = PolynomialRing(ZZ) 

sage: j = (x+1)^2 * (x-1)^7 * (x^2-x+1)^5 

sage: j.roots(CC) 

[(-1.00000000000000, 2), 

(1.00000000000000, 7), 

(0.500000000000000 - 0.866025403784439*I, 5), 

(0.500000000000000 + 0.866025403784439*I, 5)] 

""" 

K = self._parent.base_ring() 

# If the base ring has a method _roots_univariate_polynomial, 

# try to use it. An exception is raised if the method does not 

# handle the current parameters 

if hasattr(K, '_roots_univariate_polynomial'): 

try: 

return K._roots_univariate_polynomial(self, ring=ring, multiplicities=multiplicities, algorithm=algorithm, **kwds) 

except NotImplementedError: 

# This does not handle something, so keep calm and continue on 

pass 

  

if kwds: 

raise TypeError("roots() got unexpected keyword argument(s): {}".format(kwds.keys())) 

  

L = K if ring is None else ring 

  

late_import() 

  

input_fp = (is_RealField(K) 

or is_ComplexField(K) 

or is_RealDoubleField(K) 

or is_ComplexDoubleField(K)) 

output_fp = (is_RealField(L) 

or is_ComplexField(L) 

or is_RealDoubleField(L) 

or is_ComplexDoubleField(L)) 

input_complex = (is_ComplexField(K) 

or is_ComplexDoubleField(K)) 

output_complex = (is_ComplexField(L) 

or is_ComplexDoubleField(L)) 

input_gaussian = (isinstance(K, NumberField_quadratic) 

and list(K.polynomial()) == [1, 0, 1]) 

  

if input_fp and output_fp: 

# allow for possibly using a fast but less reliable 

# floating point algorithm from numpy 

low_prec = is_RealDoubleField(K) or is_ComplexDoubleField(K) 

if algorithm is None: 

if low_prec: 

algorithm = 'either' 

else: 

algorithm = 'pari' 

  

if algorithm != 'numpy' and algorithm != 'either' and algorithm != 'pari': 

raise ValueError("Unknown algorithm '%s'" % algorithm) 

  

# We should support GSL, too. We could also support PARI's 

# old Newton-iteration algorithm. 

  

input_arbprec = (is_RealField(K) or 

is_ComplexField(K)) 

  

if algorithm == 'numpy' or algorithm == 'either': 

if K.prec() > 53 and L.prec() > 53: 

from warnings import warn 

warn('NumPy does not support arbitrary precision arithmetic. ' + 

'The roots found will likely have less precision than ' + 

'you expect.') 

  

import numpy 

from numpy.linalg.linalg import LinAlgError 

numpy_dtype = ('complex' if input_complex else 'double') 

ty = (complex if input_complex else float) 

coeffs = self.list() 

numpy_array = numpy.array([ty(c) for c in reversed(coeffs)], dtype=numpy_dtype) 

try: 

ext_rts1 = numpy.roots(numpy_array) 

rts = [] 

for rt in ext_rts1: 

rts.append(CDF(rt)) 

rts.sort() 

ext_rts = rts 

except (ValueError, LinAlgError): 

if algorithm == 'either': 

algorithm = 'pari' 

else: 

raise 

  

if algorithm == 'pari': 

if not input_arbprec: 

self = self.change_ring(CC if input_complex else RR) 

ext_rts = self.__pari__().polroots(precision=L.prec()) 

  

if output_complex: 

rts = sort_complex_numbers_for_display([L(root) for root in ext_rts]) 

else: 

rts = sorted([L(root.real()) for root in ext_rts if root.imag() == 0]) 

  

rts_mult = [] 

j = 0 

while j < len(rts): 

rt = rts[j] 

mult = rts.count(rt) 

rts_mult.append((rt, mult)) 

j += mult 

  

if multiplicities: 

return rts_mult 

else: 

return [rt for (rt, mult) in rts_mult] 

  

from sage.symbolic.ring import SR 

if L is SR: 

if self.degree() == 2: 

from sage.functions.other import sqrt 

from sage.libs.pynac.pynac import I 

coeffs = self.list() 

D = coeffs[1]*coeffs[1] - 4*coeffs[0]*coeffs[2] 

if D > 0: 

l = [((-coeffs[1]-sqrt(D))/2/coeffs[2], 1),  

((-coeffs[1]+sqrt(D))/2/coeffs[2], 1)]  

elif D < 0: 

l = [((-coeffs[1]-I*sqrt(-D))/2/coeffs[2], 1),  

((-coeffs[1]+I*sqrt(-D))/2/coeffs[2], 1)] 

else: 

l = [(-coeffs[1]/2/coeffs[2]), 2] 

if multiplicities: 

return l 

else: 

return [val for val,m in l] 

vname = 'do_not_use_this_name_in_a_polynomial_coefficient' 

var = SR(vname) 

expr = self(var) 

rts = expr.solve(var, 

explicit_solutions=True, 

multiplicities=multiplicities) 

if multiplicities: 

return [(rt.rhs(), mult) for rt, mult in zip(*rts)] 

else: 

return [rt.rhs() for rt in rts] 

  

if L != K or is_AlgebraicField_common(L): 

# So far, the only "special" implementations are for real 

# and complex root isolation and for p-adic factorization 

if (is_IntegerRing(K) or is_RationalField(K) 

or is_AlgebraicRealField(K)) and \ 

(is_AlgebraicRealField(L) or is_RealIntervalField(L)): 

  

from sage.rings.polynomial.real_roots import real_roots 

  

if is_AlgebraicRealField(L): 

rts = real_roots(self, retval='algebraic_real') 

else: 

diam = ~(ZZ(1) << L.prec()) 

rts1 = real_roots(self, retval='interval', max_diameter=diam) 

  

# We (essentially) promise in the docstring above 

# that returned intervals will be at least the precision 

# of the given ring. But real_roots() does not guarantee 

# this; for instance, if it returns exactly zero, 

# it may return this with a low-precision 

# RealIntervalFieldElement. 

  

rts = [] 

for (rt, mult) in rts1: 

if rt.prec() < L.prec(): 

rt = L(rt) 

rts.append((rt, mult)) 

  

if multiplicities: 

return rts 

else: 

return [rt for (rt, mult) in rts] 

  

if (is_IntegerRing(K) or is_RationalField(K) 

or is_AlgebraicField_common(K) or input_gaussian) and \ 

(is_ComplexIntervalField(L) or is_AlgebraicField_common(L)): 

  

from sage.rings.polynomial.complex_roots import complex_roots 

  

if is_ComplexIntervalField(L): 

rts = complex_roots(self, min_prec=L.prec()) 

elif is_AlgebraicField(L): 

rts = complex_roots(self, retval='algebraic') 

else: 

rts = complex_roots(self, retval='algebraic_real') 

  

if multiplicities: 

return rts 

else: 

return [rt for (rt, mult) in rts] 

  

if output_fp and output_complex and not input_gaussian: 

# If we want the complex roots, and the input is not 

# floating point, we convert to a real polynomial 

# (except when the input coefficients are Gaussian rationals). 

if is_ComplexDoubleField(L): 

real_field = RDF 

else: 

real_field = RealField(L.prec()) 

  

return self.change_ring(real_field).roots(ring=L, multiplicities=multiplicities, algorithm=algorithm) 

elif is_pAdicRing(L) or is_pAdicField(L): 

p = L.prime() 

n = L.precision_cap() 

try: 

F = self.factor_padic(p, n) 

except AttributeError: 

pass 

else: 

return self.change_ring(L)._roots_from_factorization(F, multiplicities) 

  

return self.change_ring(L).roots(multiplicities=multiplicities, algorithm=algorithm) 

  

try: 

if K.is_integral_domain(): 

if not K.is_field(): 

try: 

# get rid of the content of self since we don't need it 

# and we really don't want to factor it if it's a huge 

# integer 

c = self.content() 

self = self//c 

except AttributeError: 

pass 

return self._roots_from_factorization(self.factor(), multiplicities) 

else: 

raise NotImplementedError 

except NotImplementedError: 

if K.is_finite(): 

if multiplicities: 

raise NotImplementedError("root finding with multiplicities for this polynomial not implemented (try the multiplicities=False option)") 

else: 

return [a for a in K if not self(a)] 

  

raise NotImplementedError("root finding for this polynomial not implemented") 

  

def _roots_from_factorization(self, F, multiplicities): 

""" 

Given a factorization ``F`` of the polynomial ``self``, return 

the roots of ``self``. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: pol = 20*x^3 - 50*x^2 + 20*x 

sage: F = pol.factor(); F 

2 * 5 * (x - 2) * x * (2*x - 1) 

sage: pol._roots_from_factorization(F, multiplicities=True) 

[(2, 1), (0, 1)] 

sage: pol.change_ring(QQ)._roots_from_factorization(F, multiplicities=False) 

[2, 0, 1/2] 

""" 

seq = [] 

K = self._parent.base_ring() 

for fac in F: 

g = fac[0] 

if g.degree() == 1: 

rt = -g[0] / g[1] 

# We need to check that this root is actually in K; 

# otherwise we'd return roots in the fraction field of K. 

if rt in K: 

rt = K(rt) 

if multiplicities: 

seq.append((rt,fac[1])) 

else: 

seq.append(rt) 

return seq 

  

def real_roots(self): 

""" 

Return the real roots of this polynomial, without multiplicities. 

  

Calls self.roots(ring=RR), unless this is a polynomial with 

floating-point real coefficients, in which case it calls 

self.roots(). 

  

EXAMPLES:: 

  

sage: x = polygen(ZZ) 

sage: (x^2 - x - 1).real_roots() 

[-0.618033988749895, 1.61803398874989] 

  

TESTS:: 

  

sage: x = polygen(RealField(100)) 

sage: (x^2 - x - 1).real_roots()[0].parent() 

Real Field with 100 bits of precision 

sage: x = polygen(RDF) 

sage: (x^2 - x - 1).real_roots()[0].parent() 

Real Double Field 

  

sage: x=polygen(ZZ,'x'); v=(x^2-x-1).real_roots() 

sage: v[0].parent() is RR 

True 

""" 

K = self.base_ring() 

if is_RealField(K) or is_RealDoubleField(K): 

return self.roots(multiplicities=False) 

  

return self.roots(ring=RR, multiplicities=False) 

  

def complex_roots(self): 

""" 

Return the complex roots of this polynomial, without 

multiplicities. 

  

Calls self.roots(ring=CC), unless this is a polynomial with 

floating-point coefficients, in which case it is uses the 

appropriate precision from the input coefficients. 

  

EXAMPLES:: 

  

sage: x = polygen(ZZ) 

sage: (x^3 - 1).complex_roots() # note: low order bits slightly different on ppc. 

[1.00000000000000, -0.500000000000000 - 0.86602540378443...*I, -0.500000000000000 + 0.86602540378443...*I] 

  

TESTS:: 

  

sage: x = polygen(RR) 

sage: (x^3 - 1).complex_roots()[0].parent() 

Complex Field with 53 bits of precision 

sage: x = polygen(RDF) 

sage: (x^3 - 1).complex_roots()[0].parent() 

Complex Double Field 

sage: x = polygen(RealField(200)) 

sage: (x^3 - 1).complex_roots()[0].parent() 

Complex Field with 200 bits of precision 

sage: x = polygen(CDF) 

sage: (x^3 - 1).complex_roots()[0].parent() 

Complex Double Field 

sage: x = polygen(ComplexField(200)) 

sage: (x^3 - 1).complex_roots()[0].parent() 

Complex Field with 200 bits of precision 

sage: x=polygen(ZZ,'x'); v=(x^2-x-1).complex_roots() 

sage: v[0].parent() is CC 

True 

""" 

K = self.base_ring() 

if is_RealField(K): 

return self.roots(ring=ComplexField(K.prec()), multiplicities=False) 

if is_RealDoubleField(K): 

return self.roots(ring=CDF, multiplicities=False) 

if is_ComplexField(K) or is_ComplexDoubleField(K): 

return self.roots(multiplicities=False) 

  

return self.roots(ring=CC, multiplicities=False) 

  

def number_of_roots_in_interval(self, a=None, b=None): 

r""" 

Return the number of roots of this polynomial in the interval 

[a,b], counted without multiplicity. The endpoints a, b default to 

-Infinity, Infinity (which are also valid input values). 

  

Calls the PARI routine polsturm. Note that as of version 2.8, PARI 

includes the left endpoint of the interval (and no longer uses 

Sturm's algorithm on exact inputs). polsturm requires a polynomial 

with real coefficients; in case PARI returns an error, we try again 

after taking the GCD of `self` with its complex conjugate. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

sage: pol = (x-1)^2 * (x-2)^2 * (x-3) 

sage: pol.number_of_roots_in_interval(1, 2) 

2 

sage: pol.number_of_roots_in_interval(1.01, 2) 

1 

sage: pol.number_of_roots_in_interval(None, 2) 

2 

sage: pol.number_of_roots_in_interval(1, Infinity) 

3 

sage: pol.number_of_roots_in_interval() 

3 

sage: pol = (x-1)*(x-2)*(x-3) 

sage: pol2 = pol.change_ring(CC) 

sage: pol2.number_of_roots_in_interval() 

3 

sage: R.<x> = PolynomialRing(CC) 

sage: pol = (x-1)*(x-CC(I)) 

sage: pol.number_of_roots_in_interval(0,2) 

1 

  

TESTS:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

sage: pol = (x-1)^2 * (x-2)^2 * (x-3) 

sage: pol.number_of_roots_in_interval(1, 2) 

2 

sage: pol = chebyshev_T(5,x) 

sage: pol.number_of_roots_in_interval(-1,2) 

5 

sage: pol.number_of_roots_in_interval(0,2) 

3 

  

""" 

pol = self // self.gcd(self.derivative()) #squarefree part 

if a is None: 

a1 = -infinity.infinity 

else: 

a1 = a 

if b is None: 

b1 = infinity.infinity 

else: 

b1 = b 

try: 

return(pari(pol).polsturm([a1,b1])) 

except PariError: 

# Take GCD with the conjugate, to extract the maximum factor 

# with real coefficients. 

pol2 = pol.gcd(pol.map_coefficients(lambda z: z.conjugate())) 

return(pari(pol2).polsturm([a1,b1])) 

  

def number_of_real_roots(self): 

r""" 

Return the number of real roots of this polynomial, counted 

without multiplicity. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

sage: pol = (x-1)^2 * (x-2)^2 * (x-3) 

sage: pol.number_of_real_roots() 

3 

sage: pol = (x-1)*(x-2)*(x-3) 

sage: pol2 = pol.change_ring(CC) 

sage: pol2.number_of_real_roots() 

3 

sage: R.<x> = PolynomialRing(CC) 

sage: pol = (x-1)*(x-CC(I)) 

sage: pol.number_of_real_roots() 

1 

""" 

return self.number_of_roots_in_interval() 

  

def all_roots_in_interval(self, a=None, b=None): 

r""" 

Return True if the roots of this polynomial are all real and 

contained in the given interval. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

sage: pol = (x-1)^2 * (x-2)^2 * (x-3) 

sage: pol.all_roots_in_interval(1, 3) 

True 

sage: pol.all_roots_in_interval(1.01, 3) 

False 

sage: pol = chebyshev_T(5,x) 

sage: pol.all_roots_in_interval(-1,1) 

True 

sage: pol = chebyshev_T(5,x/2) 

sage: pol.all_roots_in_interval(-1,1) 

False 

sage: pol.all_roots_in_interval() 

True 

""" 

pol = self // self.gcd(self.derivative()) 

return(pol.number_of_roots_in_interval(a,b) == pol.degree()) 

  

def is_real_rooted(self): 

r""" 

Return True if the roots of this polynomial are all real. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(ZZ) 

sage: pol = chebyshev_T(5, x) 

sage: pol.is_real_rooted() 

True 

sage: pol = x^2 + 1 

sage: pol.is_real_rooted() 

False 

""" 

return self.all_roots_in_interval() 

  

def reciprocal_transform(self, R=1, q=1): 

r""" 

Transform a general polynomial into a self-reciprocal polynomial. 

  

The input `Q` and output `P` satisfy the relation 

  

.. MATH:: 

  

P(x) = Q(x + q/x) x^{\deg(Q)} R(x). 

  

In this relation, `Q` has all roots in the real interval  

`[-2\sqrt{q}, 2\sqrt{q}]` if and only if `P` has all roots on the 

circle `|x| = \sqrt{q}` and `R` divides `x^2-q`. 

  

.. SEEALSO:: 

  

The inverse operation is :meth:`trace_polynomial`. 

  

INPUT: 

  

- ``R`` -- polynomial 

- ``q`` -- scalar (default: `1`) 

  

EXAMPLES:: 

  

sage: pol.<x> = PolynomialRing(Rationals()) 

sage: u = x^2+x-1 

sage: u.reciprocal_transform() 

x^4 + x^3 + x^2 + x + 1 

sage: u.reciprocal_transform(R=x-1) 

x^5 - 1 

sage: u.reciprocal_transform(q=3) 

x^4 + x^3 + 5*x^2 + 3*x + 9 

""" 

S = self.parent() 

x = S.gen() 

return S(x**(self.degree()) * self(x + q/x)) * R 

  

def trace_polynomial(self): 

r""" 

Compute the trace polynomial and cofactor. 

  

The input `P` and output `Q` satisfy the relation 

  

.. MATH:: 

  

P(x) = Q(x + q/x) x^{\deg(Q)} R(x). 

  

In this relation, `Q` has all roots in the real interval 

`[-2\sqrt{q}, 2\sqrt{q}]` if and only if `P` has all roots on the 

circle `|x| = \sqrt{q}` and `R` divides `x^2-q`. We thus require 

that the base ring of this polynomial have a coercion to the real 

numbers. 

  

.. SEEALSO:: 

  

The inverse operation is :meth:`reciprocal_transform`. 

  

OUTPUT: 

  

- ``Q`` -- trace polynomial 

- ``R`` -- cofactor 

- ``q`` -- scaling factor 

  

EXAMPLES:: 

  

sage: pol.<x> = PolynomialRing(Rationals()) 

sage: u = x^5 - 1; u.trace_polynomial() 

(x^2 + x - 1, x - 1, 1) 

sage: u = x^4 + x^3 + 5*x^2 + 3*x + 9 

sage: u.trace_polynomial() 

(x^2 + x - 1, 1, 3) 

  

We check that this function works for rings 

that have a coercion to the reals:: 

  

sage: K.<a> = NumberField(x^2-2,embedding=1.4) 

sage: u = x^4 + a*x^3 + 3*x^2 + 2*a*x + 4 

sage: u.trace_polynomial() 

(x^2 + a*x - 1, 1, 2) 

sage: (u*(x^2-2)).trace_polynomial() 

(x^2 + a*x - 1, x^2 - 2, 2) 

sage: (u*(x^2-2)^2).trace_polynomial() 

(x^4 + a*x^3 - 9*x^2 - 8*a*x + 8, 1, 2) 

sage: (u*(x^2-2)^3).trace_polynomial() 

(x^4 + a*x^3 - 9*x^2 - 8*a*x + 8, x^2 - 2, 2) 

sage: u = x^4 + a*x^3 + 3*x^2 + 4*a*x + 16 

sage: u.trace_polynomial() 

(x^2 + a*x - 5, 1, 4) 

sage: (u*(x-2)).trace_polynomial() 

(x^2 + a*x - 5, x - 2, 4) 

sage: (u*(x+2)).trace_polynomial() 

(x^2 + a*x - 5, x + 2, 4) 

""" 

S = self.parent() 

A = S.base_ring() 

x = S.gen() 

if self[0] == 0: 

raise ValueError("Polynomial not self-reciprocal") 

d = self.degree() 

sg = (self[0]/self[d]).sign() 

try: 

q = A(abs(self[0]/self[d])**(2/d)) 

except (TypeError, ValueError): 

raise ValueError("Polynomial not self-reciprocal") 

for i in range(d/2+1): 

if self[d-i] != sg*self[i]/q**(d/2-i): 

raise ValueError("Polynomial not self-reciprocal") 

Q = self 

if sg == -1 and Q.degree() % 2 == 0: 

cofactor = x**2 - q 

elif sg == -1: 

cofactor = x - q.sqrt() 

elif Q.degree() % 2 == 1: 

cofactor = x + q.sqrt() 

else: 

cofactor = S(1) 

Q //= cofactor 

coeffs = [] 

m = Q.degree() // 2 

for i in reversed(range(m+1)): 

coeffs.insert(0, Q.leading_coefficient()) 

Q = (Q % (x**2 + q)**i) // x 

return S(coeffs), cofactor, q 

  

def is_weil_polynomial(self, return_q=False): 

r""" 

Return True if this is a Weil polynomial. 

  

This polynomial must have rational or integer coefficients. 

  

INPUT: 

  

- ``self`` -- polynomial with rational or integer coefficients 

  

- ``return_q`` -- (default ``False``) if ``True``, return a second value `q` 

which is the prime power with respect to which this is `q`-Weil, 

or 0 if there is no such value. 

  

EXAMPLES:: 

  

sage: polRing.<x> = PolynomialRing(Rationals()) 

sage: P0 = x^4 + 5*x^3 + 15*x^2 + 25*x + 25 

sage: P1 = x^4 + 25*x^3 + 15*x^2 + 5*x + 25 

sage: P2 = x^4 + 5*x^3 + 25*x^2 + 25*x + 25 

sage: P0.is_weil_polynomial(return_q=True) 

(True, 5) 

sage: P0.is_weil_polynomial(return_q=False) 

True 

sage: P1.is_weil_polynomial(return_q=True) 

(False, 0) 

sage: P1.is_weil_polynomial(return_q=False) 

False 

sage: P2.is_weil_polynomial() 

False 

  

AUTHORS: 

  

David Zureick-Brown (2017-10-01) 

""" 

from sage.rings.rational_field import QQ 

if not QQ.has_coerce_map_from(self.base_ring()): 

raise NotImplementedError 

polRing = self.parent() 

x = polRing.gen() 

# the following is the polynomial whose roots are the squares 

# of the roots of self. 

Q = polRing(list(self(x)*self(-x))[::2]) 

try: 

Q, _, q = Q.trace_polynomial() 

except ValueError: 

b = False 

else: 

b = Q.all_roots_in_interval(-2*q.sqrt(), 2*q.sqrt()) 

if return_q: 

return (b, ZZ(q.sqrt())) if b else (b, 0) 

else: 

return b 

  

  

def variable_name(self): 

""" 

Return name of variable used in this polynomial as a string. 

  

OUTPUT: string 

  

EXAMPLES:: 

  

sage: R.<t> = QQ[] 

sage: f = t^3 + 3/2*t + 5 

sage: f.variable_name() 

't' 

""" 

return self._parent.variable_name() 

  

@coerce_binop 

def xgcd(self, other): 

r""" 

Return an extended gcd of this polynomial and ``other``. 

  

INPUT: 

  

- ``other`` -- a polynomial in the same ring as this polynomial 

  

OUTPUT: 

  

A tuple ``(r, s, t)`` where ``r`` is a greatest common divisor 

of this polynomial and ``other``, and ``s`` and ``t`` are such 

that ``r = s*self + t*other`` holds. 

  

.. NOTE:: 

  

The actual algorithm for computing the extended gcd depends on the 

base ring underlying the polynomial ring. If the base ring defines 

a method ``_xgcd_univariate_polynomial``, then this method will be 

called (see examples below). 

  

EXAMPLES:: 

  

sage: R.<x> = QQbar[] 

sage: (2*x^2).gcd(2*x) 

x 

sage: R.zero().gcd(0) 

0 

sage: (2*x).gcd(0) 

x 

  

One can easily add xgcd functionality to new rings by providing a 

method ``_xgcd_univariate_polynomial``:: 

  

sage: R.<x> = QQ[] 

sage: S.<y> = R[] 

sage: h1 = y*x 

sage: h2 = y^2*x^2 

sage: h1.xgcd(h2) 

Traceback (most recent call last): 

... 

NotImplementedError: Univariate Polynomial Ring in x over Rational Field does not provide an xgcd implementation for univariate polynomials 

sage: T.<x,y> = QQ[] 

sage: def poor_xgcd(f,g): 

....: ret = S(T(f).gcd(g)) 

....: if ret == f: return ret,S.one(),S.zero() 

....: if ret == g: return ret,S.zero(),S.one() 

....: raise NotImplementedError 

sage: R._xgcd_univariate_polynomial = poor_xgcd 

sage: h1.xgcd(h2) 

(x*y, 1, 0) 

sage: del R._xgcd_univariate_polynomial 

  

""" 

if hasattr(self.base_ring(), '_xgcd_univariate_polynomial'): 

return self.base_ring()._xgcd_univariate_polynomial(self, other) 

else: 

raise NotImplementedError("%s does not provide an xgcd implementation for univariate polynomials"%self.base_ring()) 

  

def rational_reconstruct(self, m, n_deg=None, d_deg=None): 

r""" 

Return a tuple of two polynomials ``(n, d)`` 

where ``self * d`` is congruent to ``n`` modulo ``m`` and 

``n.degree() <= n_deg`` and ``d.degree() <= d_deg``. 

  

INPUT: 

  

- ``m`` -- a univariate polynomial 

  

- ``n_deg`` -- (optional) an integer; the default is `\lfloor (\deg(m) - 1)/2 \rfloor` 

  

- ``d_deg`` -- (optional) an integer; the default is `\lfloor (\deg(m) - 1)/2 \rfloor` 

  

ALGORITHM: 

  

The algorithm is based on the extended Euclidean algorithm for the polynomial greatest common divisor. 

  

EXAMPLES: 

  

Over `\QQ[z]`:: 

  

sage: z = PolynomialRing(QQ, 'z').gen() 

sage: p = -z**16 - z**15 - z**14 + z**13 + z**12 + z**11 - z**5 - z**4 - z**3 + z**2 + z + 1 

sage: m = z**21 

sage: n, d = p.rational_reconstruct(m); 

sage: print((n ,d)) 

(z^4 + 2*z^3 + 3*z^2 + 2*z + 1, z^10 + z^9 + z^8 + z^7 + z^6 + z^5 + z^4 + z^3 + z^2 + z + 1) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

  

Over `\ZZ[z]`:: 

  

sage: z = PolynomialRing(ZZ, 'z').gen(); 

sage: p = -z**16 - z**15 - z**14 + z**13 + z**12 + z**11 - z**5 - z**4 - z**3 + z**2 + z + 1 

sage: m = z**21 

sage: n, d = p.rational_reconstruct(m); 

sage: print((n ,d)) 

(z^4 + 2*z^3 + 3*z^2 + 2*z + 1, z^10 + z^9 + z^8 + z^7 + z^6 + z^5 + z^4 + z^3 + z^2 + z + 1) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

  

Over an integral domain ``d`` might not be monic:: 

  

sage: P = PolynomialRing(ZZ,'x'); 

sage: x = P.gen() 

sage: p = 7*x^5 - 10*x^4 + 16*x^3 - 32*x^2 + 128*x + 256 

sage: m = x^5; 

sage: n, d = p.rational_reconstruct(m, 3, 2) 

sage: print((n ,d)) 

(-32*x^3 + 384*x^2 + 2304*x + 2048, 5*x + 8) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

sage: n, d = p.rational_reconstruct(m, 4, 0) 

sage: print((n ,d)) 

(-10*x^4 + 16*x^3 - 32*x^2 + 128*x + 256, 1) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

  

Over `\QQ(t)[z]`:: 

  

sage: P = PolynomialRing(QQ, 't') 

sage: t = P.gen() 

sage: Pz = PolynomialRing(P.fraction_field(), 'z') 

sage: z = Pz.gen() 

sage: # p = (1 + t^2*z + z^4) / (1 - t*z) 

sage: p = (1 + t^2*z + z^4)*(1 - t*z).inverse_mod(z^9) 

sage: m = z^9; 

sage: n, d = p.rational_reconstruct(m); 

sage: print((n ,d)) 

((1/-t)*z^4 - t*z + 1/-t, z + 1/-t) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

sage: w = PowerSeriesRing(P.fraction_field(), 'w').gen() 

sage: n = -10*t^2*z^4 + (-t^2 + t - 1)*z^3 + (-t - 8)*z^2 + z + 2*t^2 - t 

sage: d = z^4 + (2*t + 4)*z^3 + (-t + 5)*z^2 + (t^2 + 2)*z + t^2 + 2*t + 1 

sage: prec = 9 

sage: nc, dc = Pz((n.subs(z = w)/d.subs(z = w) + O(w^prec)).list()).rational_reconstruct(z^prec) 

sage: print( (nc, dc) == (n, d) ) 

True 

  

Over `\QQ[t][z]`:: 

  

sage: P = PolynomialRing(QQ, 't') 

sage: t = P.gen() 

sage: z = PolynomialRing(P, 'z').gen() 

sage: # p = (1 + t^2*z + z^4) / (1 - t*z) mod z^9 

sage: p = (1 + t^2*z + z^4) * sum((t*z)**i for i in range(9)) 

sage: m = z^9; 

sage: n, d = p.rational_reconstruct(m,); 

sage: print((n ,d)) 

(-z^4 - t^2*z - 1, t*z - 1) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

  

Over `\QQ_5`:: 

  

sage: x = PolynomialRing(Qp(5),'x').gen() 

sage: p = 4*x^5 + 3*x^4 + 2*x^3 + 2*x^2 + 4*x + 2 

sage: m = x^6 

sage: n, d = p.rational_reconstruct(m, 3, 2); 

sage: print(((p*d - n) % m ).is_zero()) 

True 

  

Can also be used to obtain known Padé approximations:: 

  

sage: z = PowerSeriesRing(QQ, 'z').gen() 

sage: P = PolynomialRing(QQ,'x'); 

sage: x = P.gen() 

sage: p = P(exp(z).list()) 

sage: m = x^5; 

sage: n, d = p.rational_reconstruct(m, 4, 0) 

sage: print((n ,d)) 

(1/24*x^4 + 1/6*x^3 + 1/2*x^2 + x + 1, 1) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

sage: m = x^3 

sage: n, d = p.rational_reconstruct(m, 1, 1) 

sage: print((n ,d)) 

(-x - 2, x - 2) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

sage: p = P(log(1-z).list()) 

sage: m = x^9; 

sage: n, d = p.rational_reconstruct(m, 4, 4) 

sage: print((n ,d)) 

(25/6*x^4 - 130/3*x^3 + 105*x^2 - 70*x, x^4 - 20*x^3 + 90*x^2 - 140*x + 70) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

sage: p = P(sqrt(1+z).list()) 

sage: m = x^6; 

sage: n, d = p.rational_reconstruct(m, 3, 2) 

sage: print((n ,d)) 

(1/6*x^3 + 3*x^2 + 8*x + 16/3, x^2 + 16/3*x + 16/3) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

sage: p = P(exp(2*z).list()) 

sage: m = x^7; 

sage: n, d = p.rational_reconstruct(m, 3, 3) 

sage: print((n ,d)) 

(-x^3 - 6*x^2 - 15*x - 15, x^3 - 6*x^2 + 15*x - 15) 

sage: print(((p*d - n) % m ).is_zero()) 

True 

  

Over `\RR[z]`:: 

  

sage: z = PowerSeriesRing(RR, 'z').gen() 

sage: P = PolynomialRing(RR,'x'); 

sage: x = P.gen() 

sage: p = P(exp(2*z).list()) 

sage: m = x^7 

sage: n, d = p.rational_reconstruct( m, 3, 3) 

sage: print((n ,d)) # absolute tolerance 1e-10 

(-x^3 - 6.0*x^2 - 15.0*x - 15.0, x^3 - 6.0*x^2 + 15.0*x - 15.0) 

  

.. SEEALSO:: 

  

* :mod:`sage.matrix.berlekamp_massey`, 

* :meth:`sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint.rational_reconstruct` 

""" 

P = self.parent() 

if not P.base_ring().is_field(): 

if not P.base_ring().is_integral_domain(): 

raise NotImplementedError("rational_reconstruct() " 

"is only implemented when the base ring is a field " 

"or a integral domain, " 

"a workaround is to do a multimodular approach") 

Pf = P.base_extend(P.base_ring().fraction_field()); 

sF = Pf(self); 

mF = Pf(m); 

n, d = sF.rational_reconstruct( mF, n_deg, d_deg) 

l = lcm([n.denominator(), d.denominator()]) 

n *= l 

d *= l 

return P(n), P(d) 

  

# n and d are unique if m.degree() > (n.degree() + d.degree()) 

if n_deg is None: 

n_deg = (m.degree() - 1) // 2 

if d_deg is None: 

d_deg = (m.degree() - 1) // 2 

  

if n_deg < 0 or d_deg < 0: 

raise ValueError("the degree bounds " 

"n_deg and d_deg should be positive") 

  

#XGCD until degree the degree of t1 surpasses the degree of n 

s0 = P(0); 

t0 = P(1); 

s1 = P(m); 

t1 = self.mod(s1); 

  

while n_deg < t1.degree() and t1 != 0: 

q, r1 = s1.quo_rem(t1); 

r0 = s0 - q*t0; 

s0 = t0 

s1 = t1 

t0 = r0 

t1 = r1 

  

assert t0 != 0 

if d_deg < t0.degree(): 

raise ValueError("could not complete rational reconstruction") 

  

# make the denominator monic 

c = t0.leading_coefficient() 

t0 = t0.monic() 

t1 = t1 / c 

return t1, t0 

  

  

def variables(self): 

""" 

Returns the tuple of variables occurring in this polynomial. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: x.variables() 

(x,) 

  

A constant polynomial has no variables. 

  

:: 

  

sage: R(2).variables() 

() 

""" 

if self.is_constant(): 

return () 

else: 

return self._parent.gens() 

  

def args(self): 

""" 

Returns the generator of this polynomial ring, which is the (only) 

argument used when calling self. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: x.args() 

(x,) 

  

A constant polynomial has no variables, but still takes a single 

argument. 

  

:: 

  

sage: R(2).args() 

(x,) 

""" 

return self._parent.gens() 

  

def valuation(self, p=None): 

r""" 

If `f = a_r x^r + a_{r+1}x^{r+1} + \cdots`, with 

`a_r` nonzero, then the valuation of `f` is 

`r`. The valuation of the zero polynomial is 

`\infty`. 

  

If a prime (or non-prime) `p` is given, then the valuation 

is the largest power of `p` which divides self. 

  

The valuation at `\infty` is -self.degree(). 

  

EXAMPLES:: 

  

sage: P.<x> = ZZ[] 

sage: (x^2+x).valuation() 

1 

sage: (x^2+x).valuation(x+1) 

1 

sage: (x^2+1).valuation() 

0 

sage: (x^3+1).valuation(infinity) 

-3 

sage: P(0).valuation() 

+Infinity 

""" 

cdef int k 

  

if not self: 

return infinity.infinity 

  

if p is infinity.infinity: 

return -self.degree() 

  

if p is None: 

for k from 0 <= k <= self.degree(): 

if self[k]: 

return ZZ(k) 

if isinstance(p, Polynomial): 

p = self._parent.coerce(p) 

elif is_Ideal(p) and p.ring() is self._parent: # eventually need to handle fractional ideals in the fraction field 

if self._parent.base_ring().is_field(): # common case 

p = p.gen() 

else: 

raise NotImplementedError 

else: 

from sage.rings.fraction_field import is_FractionField 

if is_FractionField(p.parent()) and self._parent.has_coerce_map_from(p.parent().ring()): 

p = self._parent.coerce(p.parent().ring()(p)) # here we require that p be integral. 

else: 

raise TypeError("The polynomial, p, must have the same parent as self.") 

  

if p.degree() == 0: 

raise ArithmeticError("The polynomial, p, must have positive degree.") 

k = 0 

while self % p == 0: 

k = k + 1 

self //= p 

return sage.rings.integer.Integer(k) 

  

def ord(self, p=None): 

r""" 

This is the same as the valuation of self at p. See the 

documentation for ``self.valuation``. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: (x^2+x).ord(x+1) 

1 

""" 

return self.valuation(p) 

  

def add_bigoh(self, prec): 

r""" 

Returns the power series of precision at most prec got by adding 

`O(q^\text{prec})` to self, where q is its variable. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = 1 + 4*x + x^3 

sage: f.add_bigoh(7) 

1 + 4*x + x^3 + O(x^7) 

sage: f.add_bigoh(2) 

1 + 4*x + O(x^2) 

sage: f.add_bigoh(2).parent() 

Power Series Ring in x over Integer Ring 

""" 

return self._parent.completion(self._parent.gen())(self).add_bigoh(prec) 

  

@cached_method 

def is_irreducible(self): 

r""" 

Return whether this polynomial is irreducible. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: (x^3 + 1).is_irreducible() 

False 

sage: (x^2 - 1).is_irreducible() 

False 

sage: (x^3 + 2).is_irreducible() 

True 

sage: R(0).is_irreducible() 

False 

  

The base ring does matter: for example, `2x` is irreducible as a 

polynomial in `\QQ[x]`, but not in `\ZZ[x]`:: 

  

sage: R.<x> = ZZ[] 

sage: R(2*x).is_irreducible() 

False 

sage: R.<x> = QQ[] 

sage: R(2*x).is_irreducible() 

True 

  

TESTS:: 

  

sage: F.<t> = NumberField(x^2-5) 

sage: Fx.<xF> = PolynomialRing(F) 

sage: f = Fx([2*t - 5, 5*t - 10, 3*t - 6, -t, -t + 2, 1]) 

sage: f.is_irreducible() 

False 

sage: f = Fx([2*t - 3, 5*t - 10, 3*t - 6, -t, -t + 2, 1]) 

sage: f.is_irreducible() 

True 

  

If the base ring implements `_is_irreducible_univariate_polynomial`, 

then this method gets used instead of the generic algorithm which just 

factors the input:: 

  

sage: R.<x> = QQbar[] 

sage: hasattr(QQbar, "_is_irreducible_univariate_polynomial") 

True 

sage: (x^2 + 1).is_irreducible() 

False 

  

Constants can be irreducible if they are not units:: 

  

sage: R.<x> = ZZ[] 

sage: R(1).is_irreducible() 

False 

sage: R(4).is_irreducible() 

False 

sage: R(5).is_irreducible() 

True 

  

Check that caching works:: 

  

sage: R.<x> = ZZ[] 

sage: x.is_irreducible() 

True 

sage: x.is_irreducible.cache 

True 

  

  

""" 

if self.is_zero(): 

return False 

if self.is_unit(): 

return False 

if self.degree() == 0: 

return self.base_ring()(self).is_irreducible() 

  

B = self.parent().base_ring() 

if hasattr(B, '_is_irreducible_univariate_polynomial'): 

return B._is_irreducible_univariate_polynomial(self) 

  

F = self.factor() 

if len(F) > 1 or F[0][1] > 1: 

return False 

return True 

  

def shift(self, n): 

r""" 

Returns this polynomial multiplied by the power `x^n`. If 

`n` is negative, terms below `x^n` will be 

discarded. Does not change this polynomial (since polynomials are 

immutable). 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: p = x^2 + 2*x + 4 

sage: p.shift(0) 

x^2 + 2*x + 4 

sage: p.shift(-1) 

x + 2 

sage: p.shift(-5) 

0 

sage: p.shift(2) 

x^4 + 2*x^3 + 4*x^2 

  

One can also use the infix shift operator:: 

  

sage: f = x^3 + x 

sage: f >> 2 

x 

sage: f << 2 

x^5 + x^3 

  

TESTS:: 

  

sage: p = R(0) 

sage: p.shift(3).is_zero() 

True 

sage: p.shift(-3).is_zero() 

True 

  

AUTHORS: 

  

- David Harvey (2006-08-06) 

  

- Robert Bradshaw (2007-04-18): Added support for infix 

operator. 

""" 

if n == 0 or self.degree() < 0: 

return self # safe because immutable. 

if n > 0: 

output = [self.base_ring().zero()] * n 

output.extend(self.coefficients(sparse=False)) 

return self._new_generic(output) 

if n < 0: 

if n > self.degree(): 

return self._new_generic([]) 

else: 

return self._new_generic(self.coefficients(sparse=False)[-int(n):]) 

  

def __lshift__(self, k): 

""" 

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = x + 2 

sage: f << 3 

x^4 + 2*x^3 

""" 

return self.shift(k) 

  

def __rshift__(self, k): 

""" 

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^4 + 2*x^3 

sage: f >> 3 

x + 2 

""" 

return self.shift(-k) 

  

cpdef Polynomial truncate(self, long n): 

r""" 

Returns the polynomial of degree ` < n` which is equivalent 

to self modulo `x^n`. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[]; S.<y> = PolynomialRing(R, sparse=True) 

sage: f = y^3 + x*y -3*x; f 

y^3 + x*y - 3*x 

sage: f.truncate(2) 

x*y - 3*x 

sage: f.truncate(1) 

-3*x 

sage: f.truncate(0) 

0 

""" 

# __getitem__ already returns a polynomial!! 

# We must not have check=False, since 0 must not have __coeffs = [0]. 

return <Polynomial>self._parent(self[:n])#, check=False) 

  

cdef _inplace_truncate(self, long prec): 

return self.truncate(prec) 

  

@cached_method 

def is_squarefree(self): 

""" 

Return False if this polynomial is not square-free, i.e., if there is a 

non-unit `g` in the polynomial ring such that `g^2` divides ``self``. 

  

.. WARNING:: 

  

This method is not consistent with 

:meth:`.squarefree_decomposition` since the latter does not factor 

the content of a polynomial. See the examples below. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = (x-1)*(x-2)*(x^2-5)*(x^17-3); f 

x^21 - 3*x^20 - 3*x^19 + 15*x^18 - 10*x^17 - 3*x^4 + 9*x^3 + 9*x^2 - 45*x + 30 

sage: f.is_squarefree() 

True 

sage: (f*(x^2-5)).is_squarefree() 

False 

  

A generic implementation is available, which relies on gcd 

computations:: 

  

sage: R.<x> = ZZ[] 

sage: (2*x).is_squarefree() 

True 

sage: (4*x).is_squarefree() 

False 

sage: (2*x^2).is_squarefree() 

False 

sage: R(0).is_squarefree() 

False 

sage: S.<y> = QQ[] 

sage: R.<x> = S[] 

sage: (2*x*y).is_squarefree() 

True 

sage: (2*x*y^2).is_squarefree() 

False 

  

In positive characteristic, we compute the square-free 

decomposition or a full factorization, depending on which is 

available:: 

  

sage: K.<t> = FunctionField(GF(3)) 

sage: R.<x> = K[] 

sage: (x^3-x).is_squarefree() 

True 

sage: (x^3-1).is_squarefree() 

False 

sage: (x^3+t).is_squarefree() 

True 

sage: (x^3+t^3).is_squarefree() 

False 

  

In the following example, `t^2` is a unit in the base field:: 

  

sage: R(t^2).is_squarefree() 

True 

  

This method is not consistent with :meth:`.squarefree_decomposition`:: 

  

sage: R.<x> = ZZ[] 

sage: f = 4 * x 

sage: f.is_squarefree() 

False 

sage: f.squarefree_decomposition() 

(4) * x 

  

If you want this method equally not to consider the content, you can 

remove it as in the following example:: 

  

sage: c = f.content() 

sage: (f/c).is_squarefree() 

True 

  

If the base ring is not an integral domain, the question is not 

mathematically well-defined:: 

  

sage: R.<x> = IntegerModRing(9)[] 

sage: pol = (x + 3)*(x + 6); pol 

x^2 

sage: pol.is_squarefree() 

Traceback (most recent call last): 

... 

TypeError: is_squarefree() is not defined for polynomials over Ring of integers modulo 9 

  

TESTS: 

  

Check that the results are cached:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^2 

sage: f.is_squarefree() 

False 

sage: f.is_squarefree.cache 

False 

  

If the base ring implements `_is_squarefree_univariate_polynomial`, 

then this method gets used instead of the generic algorithm in 

:meth:`_is_squarefree_generic`:: 

  

sage: R.<x> = QQbar[] 

sage: (x^2).is_squarefree() 

False 

sage: hasattr(QQbar, '_is_squarefree_univariate_polynomial') 

False 

sage: QQbar._is_squarefree_univariate_polynomial = lambda self: True 

sage: (x^2).is_squarefree() 

True 

sage: del(QQbar._is_squarefree_univariate_polynomial) 

  

""" 

B = self._parent.base_ring() 

if B not in sage.categories.integral_domains.IntegralDomains(): 

raise TypeError("is_squarefree() is not defined for polynomials over {}".format(B)) 

  

B = self.parent().base_ring() 

if hasattr(B, '_is_squarefree_univariate_polynomial'): 

return B._is_squarefree_univariate_polynomial(self) 

  

return self._is_squarefree_generic() 

  

def _is_squarefree_generic(self): 

r""" 

Return False if this polynomial is not square-free, i.e., if there is a 

non-unit `g` in the polynomial ring such that `g^2` divides ``self``. 

  

EXAMPLES:: 

  

sage: R.<x> = QQbar[] 

sage: (x^2*(x + 1)).is_squarefree() # indirect doctest 

False 

sage: (x*(x+1)).is_squarefree() # indirect doctest 

True 

  

""" 

B = self.parent().base_ring() 

  

# a square-free polynomial has a square-free content 

if not B.is_field(): 

content = self.content_ideal().gen() 

if not content.is_squarefree(): 

return False 

  

# separable polynomials are square-free 

if self.derivative().gcd(self).is_constant(): 

return True 

  

# for characteristic zero rings, square-free polynomials have to be separable 

if B.characteristic().is_zero(): 

return False 

  

# over rings of positive characteristic, we rely on the square-free decomposition if available 

try: 

F = self.squarefree_decomposition() 

# We catch: 

# - NotImplementedError in case squarefree decomposition is not implemented 

# - AttributeError in case p-th roots are not (or do not exist) 

except (NotImplementedError, AttributeError): 

F = self.factor() 

return all([e<=1 for (f,e) in F]) 

  

def radical(self): 

""" 

Returns the radical of self; over a field, this is the product of 

the distinct irreducible factors of self. (This is also sometimes 

called the "square-free part" of self, but that term is ambiguous; 

it is sometimes used to mean the quotient of self by its maximal 

square factor.) 

  

EXAMPLES:: 

  

sage: P.<x> = ZZ[] 

sage: t = (x^2-x+1)^3 * (3*x-1)^2 

sage: t.radical() 

3*x^3 - 4*x^2 + 4*x - 1 

sage: radical(12 * x^5) 

6*x 

  

If self has a factor of multiplicity divisible by the characteristic (see :trac:`8736`):: 

  

sage: P.<x> = GF(2)[] 

sage: (x^3 + x^2).radical() 

x^2 + x 

""" 

P = self._parent 

R = P.base_ring() 

p = R.characteristic() 

if p == 0 or p > self.degree(): 

if R.is_field(): 

return self // self.gcd(self.derivative()) 

else: 

# Be careful with the content: return the 

# radical of the content times the radical of 

# (self/content) 

content = self.content() 

self_1 = (self//content) 

return (self_1 // self_1.gcd(self_1.derivative())) * content.radical() 

else: # The above method is not always correct (see Trac 8736) 

return self.factor().radical_value() 

  

def content_ideal(self): 

""" 

Return the content ideal of this polynomial, defined as the ideal 

generated by its coefficients. 

  

EXAMPLES:: 

  

sage: R.<x> = IntegerModRing(4)[] 

sage: f = x^4 + 3*x^2 + 2 

sage: f.content_ideal() 

Ideal (2, 3, 1) of Ring of integers modulo 4 

  

When the base ring is a gcd ring, the content as a ring element is 

the generator of the content ideal:: 

  

sage: R.<x> = ZZ[] 

sage: f = 2*x^3 - 4*x^2 + 6*x - 10 

sage: f.content_ideal().gen() 

2 

""" 

return self.base_ring().ideal(self.coefficients()) 

  

content = deprecated_function_alias(16613, content_ideal) 

  

def norm(self, p): 

r""" 

Return the `p`-norm of this polynomial. 

  

DEFINITION: For integer `p`, the `p`-norm of a 

polynomial is the `p`\th root of the sum of the 

`p`\th powers of the absolute values of the coefficients of 

the polynomial. 

  

INPUT: 

  

  

- ``p`` - (positive integer or +infinity) the degree 

of the norm 

  

  

EXAMPLES:: 

  

sage: R.<x> = RR[] 

sage: f = x^6 + x^2 + -x^4 - 2*x^3 

sage: f.norm(2) 

2.64575131106459 

sage: (sqrt(1^2 + 1^2 + (-1)^2 + (-2)^2)).n() 

2.64575131106459 

  

:: 

  

sage: f.norm(1) 

5.00000000000000 

sage: f.norm(infinity) 

2.00000000000000 

  

:: 

  

sage: f.norm(-1) 

Traceback (most recent call last): 

... 

ValueError: The degree of the norm must be positive 

  

TESTS:: 

  

sage: R.<x> = RR[] 

sage: f = x^6 + x^2 + -x^4 -x^3 

sage: f.norm(int(2)) 

2.00000000000000 

  

Check that :trac:`18600` is fixed:: 

  

sage: R.<x> = PolynomialRing(ZZ, sparse=True) 

sage: (x^2^100 + 1).norm(1) 

2.00000000000000 

  

AUTHORS: 

  

- Didier Deshommes 

- William Stein: fix bugs, add definition, etc. 

""" 

if p <= 0 : 

raise ValueError("The degree of the norm must be positive") 

  

coeffs = self.coefficients() 

if p == infinity.infinity: 

return RR(max([abs(i) for i in coeffs])) 

  

p = sage.rings.integer.Integer(p) # because we'll do 1/p below. 

  

if p == 1: 

return RR(sum([abs(i) for i in coeffs])) 

  

return RR(sum([abs(i)**p for i in coeffs]))**(1/p) 

  

cpdef long number_of_terms(self): 

""" 

Returns the number of non-zero coefficients of self. Also called weight, 

hamming weight or sparsity. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = x^3 - x 

sage: f.number_of_terms() 

2 

sage: R(0).number_of_terms() 

0 

sage: f = (x+1)^100 

sage: f.number_of_terms() 

101 

sage: S = GF(5)['y'] 

sage: S(f).number_of_terms() 

5 

sage: cyclotomic_polynomial(105).number_of_terms() 

33 

  

The method :meth:`hamming_weight` is an alias:: 

  

sage: f.hamming_weight() 

101 

""" 

cdef long w = 0 

for a in self.coefficients(sparse=False): 

if a: 

w += 1 

return w 

  

# alias hamming_weight for number_of_terms: 

hamming_weight = number_of_terms 

  

def map_coefficients(self, f, new_base_ring=None): 

""" 

Returns the polynomial obtained by applying ``f`` to the non-zero 

coefficients of ``self``. 

  

If ``f`` is a :class:`sage.categories.map.Map`, then the resulting 

polynomial will be defined over the codomain of ``f``. Otherwise, the 

resulting polynomial will be over the same ring as self. Set 

``new_base_ring`` to override this behaviour. 

  

INPUT: 

  

- ``f`` -- a callable that will be applied to the coefficients of self. 

  

- ``new_base_ring`` (optional) -- if given, the resulting polynomial 

will be defined over this ring. 

  

EXAMPLES:: 

  

sage: R.<x> = SR[] 

sage: f = (1+I)*x^2 + 3*x - I 

sage: f.map_coefficients(lambda z: z.conjugate()) 

(-I + 1)*x^2 + 3*x + I 

sage: R.<x> = ZZ[] 

sage: f = x^2 + 2 

sage: f.map_coefficients(lambda a: a + 42) 

43*x^2 + 44 

sage: R.<x> = PolynomialRing(SR, sparse=True) 

sage: f = (1+I)*x^(2^32) - I 

sage: f.map_coefficients(lambda z: z.conjugate()) 

(-I + 1)*x^4294967296 + I 

sage: R.<x> = PolynomialRing(ZZ, sparse=True) 

sage: f = x^(2^32) + 2 

sage: f.map_coefficients(lambda a: a + 42) 

43*x^4294967296 + 44 

  

Examples with different base ring:: 

  

sage: R.<x> = ZZ[] 

sage: k = GF(2) 

sage: residue = lambda x: k(x) 

sage: f = 4*x^2+x+3 

sage: g = f.map_coefficients(residue); g 

x + 1 

sage: g.parent() 

Univariate Polynomial Ring in x over Integer Ring 

sage: g = f.map_coefficients(residue, new_base_ring = k); g 

x + 1 

sage: g.parent() 

Univariate Polynomial Ring in x over Finite Field of size 2 (using GF2X) 

sage: residue = k.coerce_map_from(ZZ) 

sage: g = f.map_coefficients(residue); g 

x + 1 

sage: g.parent() 

Univariate Polynomial Ring in x over Finite Field of size 2 (using GF2X) 

""" 

R = self._parent 

if new_base_ring is not None: 

R = R.change_ring(new_base_ring) 

elif isinstance(f, Map): 

R = R.change_ring(f.codomain()) 

return R({k: f(v) for (k,v) in self.dict().items()}) 

  

def is_cyclotomic(self, certificate=False, algorithm="pari"): 

r""" 

Test if this polynomial is a cyclotomic polynomial. 

  

A *cyclotomic polynomial* is a monic, irreducible polynomial such that 

all roots are roots of unity. 

  

By default the answer is a boolean. But if ``certificate`` is ``True``, 

the result is a non-negative integer: it is ``0`` if ``self`` is not 

cyclotomic, and a positive integer ``n`` if ``self`` is the `n`-th 

cyclotomic polynomial. 

  

.. SEEALSO:: 

  

:meth:`is_cyclotomic_product` 

:meth:`cyclotomic_part` 

:meth:`has_cyclotomic_factor` 

  

INPUT: 

  

- ``certificate`` -- boolean, default to ``False``. Only works with 

``algorithm`` set to "pari". 

  

- ``algorithm`` -- either "pari" or "sage" (default is "pari") 

  

ALGORITHM: 

  

The native algorithm implemented in Sage uses the first 

algorithm of [BD89]_. The algorithm in pari (using 

:pari:`poliscyclo`) is more subtle since it does compute the 

inverse of the Euler `\phi` function to determine the `n` such 

that the polynomial is the `n`-th cyclotomic polynomial. 

  

EXAMPLES: 

  

Quick tests:: 

  

sage: P.<x> = ZZ['x'] 

sage: (x - 1).is_cyclotomic() 

True 

sage: (x + 1).is_cyclotomic() 

True 

sage: (x^2 - 1).is_cyclotomic() 

False 

sage: (x^2 + x + 1).is_cyclotomic(certificate=True) 

3 

sage: (x^2 + 2*x + 1).is_cyclotomic(certificate=True) 

0 

  

Test first 100 cyclotomic polynomials:: 

  

sage: all(cyclotomic_polynomial(i).is_cyclotomic() for i in range(1,101)) 

True 

  

Some more tests:: 

  

sage: (x^16 + x^14 - x^10 + x^8 - x^6 + x^2 + 1).is_cyclotomic(algorithm="pari") 

False 

sage: (x^16 + x^14 - x^10 + x^8 - x^6 + x^2 + 1).is_cyclotomic(algorithm="sage") 

False 

  

sage: (x^16 + x^14 - x^10 - x^8 - x^6 + x^2 + 1).is_cyclotomic(algorithm="pari") 

True 

sage: (x^16 + x^14 - x^10 - x^8 - x^6 + x^2 + 1).is_cyclotomic(algorithm="sage") 

True 

  

sage: y = polygen(QQ) 

sage: (y/2 - 1/2).is_cyclotomic() 

False 

sage: (2*(y/2 - 1/2)).is_cyclotomic() 

True 

  

Invalid arguments:: 

  

sage: (x - 3).is_cyclotomic(algorithm="sage", certificate=True) 

Traceback (most recent call last): 

... 

ValueError: no implementation of the certificate within Sage 

  

Test using other rings:: 

  

sage: z = polygen(GF(5)) 

sage: (z - 1).is_cyclotomic() 

Traceback (most recent call last): 

... 

NotImplementedError: not implemented in non-zero characteristic 

  

TESTS:: 

  

sage: R = ZZ['x'] 

sage: for _ in range(20): 

....: p = R.random_element(degree=randint(10,20)) 

....: ans_pari = p.is_cyclotomic(algorithm="pari") 

....: ans_sage = p.is_cyclotomic(algorithm="sage") 

....: assert ans_pari == ans_sage, "problem with p={}".format(p) 

sage: for d in range(2,20): 

....: p = cyclotomic_polynomial(d) 

....: assert p.is_cyclotomic(algorithm="pari"), "pari problem with p={}".format(p) 

....: assert p.is_cyclotomic(algorithm="sage"), "sage problem with p={}".format(p) 

  

Test the output type when ``certificate=True``:: 

  

sage: type((x^2 - 2).is_cyclotomic(certificate=True)) 

<type 'sage.rings.integer.Integer'> 

sage: type((x -1).is_cyclotomic(certificate=True)) 

<type 'sage.rings.integer.Integer'> 

  

Check that the arguments are forwarded when the input is not a 

polynomial with coefficients in `\ZZ`:: 

  

sage: x = polygen(QQ) 

sage: (x-1).is_cyclotomic(certificate=True) 

1 

  

REFERENCES: 

  

.. [BD89] \R. J. Bradford and J. H. Davenport, Effective tests 

for cyclotomic polynomials, Symbolic and Algebraic Computation (1989) 

pp. 244 -- 251, :doi:`10.1007/3-540-51084-2_22` 

""" 

S = self.base_ring() 

if S.characteristic() != 0: 

raise NotImplementedError("not implemented in non-zero characteristic") 

if S != ZZ: 

try: 

f = self.change_ring(ZZ) 

except TypeError: 

return False 

return f.is_cyclotomic(certificate=certificate, algorithm=algorithm) 

  

if algorithm == "pari": 

ans = self.__pari__().poliscyclo() 

return Integer(ans) if certificate else bool(ans) 

  

elif algorithm != "sage": 

raise ValueError("algorithm must be either 'pari' or 'sage'") 

  

elif certificate: 

raise ValueError("no implementation of the certificate within Sage") 

  

if not self.is_monic(): 

return False 

  

P = self._parent 

gen = P.gen() 

  

if self == gen - 1: # the first cyc. pol. is treated apart 

return True 

  

if self.constant_coefficient() != 1: 

return False 

  

if not self.is_irreducible(): 

return False 

  

coefs = self.coefficients(sparse=False) 

  

# compute the graeffe transform of self 

po_odd = P(coefs[1::2]) 

po_even = P(coefs[0::2]) 

f1 = po_even*po_even - gen*(po_odd*po_odd) 

  

# first case 

if f1 == self: 

return True 

  

# second case 

selfminus = self(-gen) 

if f1 == selfminus: 

if selfminus.leading_coefficient() < 0 and (-selfminus).is_cyclotomic(algorithm="sage"): 

return True 

elif selfminus.is_cyclotomic(algorithm="sage"): 

return True 

  

# third case, we need to take a square root 

ans, ff1 = f1.is_square(True) 

return ans and ff1.is_cyclotomic(algorithm="sage") 

  

def is_cyclotomic_product(self): 

r""" 

Test whether this polynomial is a product of cyclotomic polynomials. 

  

This method simply calls the function :pari:`poliscycloprod` 

from the Pari library. 

  

.. SEEALSO:: 

  

:meth:`is_cyclotomic` 

:meth:`cyclotomic_part` 

:meth:`has_cyclotomic_factor` 

  

EXAMPLES:: 

  

sage: x = polygen(ZZ) 

sage: (x^5 - 1).is_cyclotomic_product() 

True 

sage: (x^5 + x^4 - x^2 + 1).is_cyclotomic_product() 

False 

  

sage: p = prod(cyclotomic_polynomial(i) for i in [2,5,7,12]) 

sage: p.is_cyclotomic_product() 

True 

  

sage: (x^5 - 1/3).is_cyclotomic_product() 

False 

  

sage: x = polygen(Zmod(5)) 

sage: (x-1).is_cyclotomic_product() 

Traceback (most recent call last): 

... 

NotImplementedError: not implemented in non-zero characteristic 

""" 

if self.base_ring().characteristic() != 0: 

raise NotImplementedError("not implemented in non-zero characteristic") 

if self.base_ring() != ZZ: 

try: 

f = self.change_ring(ZZ) 

except TypeError: 

return False 

return f.is_cyclotomic_product() 

  

return bool(self.__pari__().poliscycloprod()) 

  

def cyclotomic_part(self): 

r""" 

Return the product of the irreducible factors of this polynomial 

which are cyclotomic polynomials. 

  

The algorithm assumes that the polynomial has rational coefficients. 

  

.. SEEALSO:: 

  

:meth:`is_cyclotomic` 

:meth:`is_cyclotomic_product` 

:meth:`has_cyclotomic_factor` 

  

EXAMPLES:: 

  

sage: P.<x> = PolynomialRing(Integers()) 

sage: pol = 2*(x^4 + 1) 

sage: pol.cyclotomic_part() 

x^4 + 1 

sage: pol = x^4 + 2 

sage: pol.cyclotomic_part() 

1 

sage: pol = (x^4 + 1)^2 * (x^4 + 2) 

sage: pol.cyclotomic_part() 

x^8 + 2*x^4 + 1 

  

sage: P.<x> = PolynomialRing(QQ) 

sage: pol = (x^4 + 1)^2 * (x^4 + 2) 

sage: pol.cyclotomic_part() 

x^8 + 2*x^4 + 1 

  

sage: P.<x> = PolynomialRing(RR) 

sage: pol = (x^4 + 1)^2 * (x^4 + 2) 

sage: pol.cyclotomic_part() 

Traceback (most recent call last): 

... 

NotImplementedError: not implemented for inexact base rings 

  

sage: x = polygen(Zmod(5)) 

sage: (x-1).cyclotomic_part() 

Traceback (most recent call last): 

... 

NotImplementedError: not implemented in non-zero characteristic 

""" 

S = self.base_ring() 

if S.characteristic() != 0: 

raise NotImplementedError("not implemented in non-zero characteristic") 

if not S.is_exact(): 

raise NotImplementedError("not implemented for inexact base rings") 

R = self._parent 

x = R.gen() 

# Extract Phi_n when n is odd. 

t1 = self 

while True: 

t2 = t1.gcd(t1(x**2)) 

if t1.degree() == t2.degree(): break 

t1 = t2 

ans = t1 

# Extract Phi_n when v_2(n) = 1, 2, ... 

t0 = self // t1 

i = 0 

while t0.degree() > 0: 

t1 = t0 

while True: 

t2 = t1.gcd(t1(-x**2)) 

if t1.degree() == t2.degree(): break 

t1 = t2 

ans *= t1(x**(2**i)) 

t0 = t0 // t1 

t1 = t0.gcd(t0(-x)) 

t0 = R(list(t1)[::2]) 

i += 1 

return(ans // ans.leading_coefficient()) 

  

def has_cyclotomic_factor(self): 

r""" 

Return True if the given polynomial has a nontrivial cyclotomic factor. 

  

The algorithm assumes that the polynomial has rational coefficients. 

  

If the polynomial is known to be irreducible, it may be slightly more 

efficient to call `is_cyclotomic` instead. 

  

.. SEEALSO:: 

  

:meth:`is_cyclotomic` 

:meth:`is_cyclotomic_product` 

:meth:`cyclotomic_part` 

  

EXAMPLES:: 

  

sage: pol.<x> = PolynomialRing(Rationals()) 

sage: u = x^5-1; u.has_cyclotomic_factor() 

True 

sage: u = x^5-2; u.has_cyclotomic_factor() 

False 

sage: u = pol(cyclotomic_polynomial(7)) * pol.random_element() #random 

sage: u.has_cyclotomic_factor() 

True 

""" 

if not QQ.has_coerce_map_from(self.base_ring()): 

raise NotImplementedError("coefficients not rational") 

polRing = self.parent() 

x = polRing.gen() 

  

pol1 = self 

# First, while pol1 has a nontrivial even factor, replace 

# that factor with the polynomials whose roots are the squares of 

# the roots of that factor. This replaces any roots of unity of order 

# divisible by 4 with roots of unity of order not divisible by 4. 

  

pol2 = pol1.gcd(pol1(-x)) 

while not pol2.is_constant(): 

pol1 = (pol1 // pol2) * polRing(pol2.list()[::2]) 

pol2 = pol1.gcd(pol1(-x)) 

  

# Next, replace pol1 with the polynomial whose roots are the 

# squares of pol1. This replaces any roots of unity of even order 

# with roots of unity of odd order. 

pol1 = polRing((pol1*pol1(-x)).list()[::2]) 

  

# Finally, find the largest factor of pol1 whose roots are 

# stable under squaring. This factor is constant if and only if 

# the original polynomial has no cyclotomic factor. 

while True: 

if pol1.is_constant(): return(False) 

pol2 = pol1.gcd(polRing((pol1*pol1(-x)).list()[::2])) 

if pol1.degree() == pol2.degree(): return(True) 

pol1 = pol2 

  

def homogenize(self, var='h'): 

r""" 

Return the homogenization of this polynomial. 

  

The polynomial itself is returned if it is homogeneous already. Otherwise, 

its monomials are multiplied with the smallest powers of ``var`` such 

that they all have the same total degree. 

  

INPUT: 

  

- ``var`` -- a variable in the polynomial ring (as a string, an element 

of the ring, or ``0``) or a name for a new variable (default: 

``'h'``) 

  

OUTPUT: 

  

If ``var`` specifies the variable in the polynomial ring, then a 

homogeneous element in that ring is returned. Otherwise, a homogeneous 

element is returned in a polynomial ring with an extra last variable 

``var``. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: f = x^2 + 1 

sage: f.homogenize() 

x^2 + h^2 

  

The parameter ``var`` can be used to specify the name of the variable:: 

  

sage: g = f.homogenize('z'); g 

x^2 + z^2 

sage: g.parent() 

Multivariate Polynomial Ring in x, z over Rational Field 

  

However, if the polynomial is homogeneous already, then that parameter 

is ignored and no extra variable is added to the polynomial ring:: 

  

sage: f = x^2 

sage: g = f.homogenize('z'); g 

x^2 

sage: g.parent() 

Univariate Polynomial Ring in x over Rational Field 

  

For compatibility with the multivariate case, if ``var`` specifies the 

variable of the polynomial ring, then the monomials are multiplied with 

the smallest powers of ``var`` such that the result is homogeneous; in 

other words, we end up with a monomial whose leading coefficient is the 

sum of the coefficients of the polynomial:: 

  

sage: f = x^2 + x + 1 

sage: f.homogenize('x') 

3*x^2 

  

In positive characteristic, the degree can drop in this case:: 

  

sage: R.<x> = GF(2)[] 

sage: f = x + 1 

sage: f.homogenize(x) 

0 

  

For compatibility with the multivariate case, the parameter ``var`` can 

also be 0 to specify the variable in the polynomial ring:: 

  

sage: R.<x> = QQ[] 

sage: f = x^2 + x + 1 

sage: f.homogenize(0) 

3*x^2 

  

""" 

if self.is_homogeneous(): 

return self 

  

x, = self.variables() 

  

if isinstance(var, int) or isinstance(var, Integer): 

if var: 

raise TypeError("Variable index %d must be < 1." % var) 

else: 

return sum(self.coefficients())*x**self.degree() 

  

x_name = self.variable_name() 

var = str(var) 

  

if var == x_name: 

return sum(self.coefficients())*x**self.degree() 

  

P = PolynomialRing(self.base_ring(), [x_name, var]) 

return P(self)._homogenize(1) 

  

def is_homogeneous(self): 

r""" 

Return ``True`` if this polynomial is homogeneous. 

  

EXAMPLES:: 

  

sage: P.<x> = PolynomialRing(QQ) 

sage: x.is_homogeneous() 

True 

sage: P(0).is_homogeneous() 

True 

sage: (x+1).is_homogeneous() 

False 

""" 

return len(self.exponents()) < 2 

  

def nth_root(self, n): 

r""" 

Return a `n`-th root of this polynomial. 

  

This is computed using Newton method in the ring of power series. This 

method works only when the base ring is an integral domain. Morever, for 

polynomial whose coefficient of lower degree is different from 1, the 

elements of the base ring should have a method ``nth_root`` implemented. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: a = 27 * (x+3)**6 * (x+5)**3 

sage: a.nth_root(3) 

3*x^3 + 33*x^2 + 117*x + 135 

  

sage: b = 25 * (x^2 + x + 1) 

sage: b.nth_root(2) 

Traceback (most recent call last): 

... 

ValueError: not a 2nd power 

sage: R(0).nth_root(3) 

0 

sage: R.<x> = QQ[] 

sage: a = 1/4 * (x/7 + 3/2)^2 * (x/2 + 5/3)^4 

sage: a.nth_root(2) 

1/56*x^3 + 103/336*x^2 + 365/252*x + 25/12 

  

sage: K.<sqrt2> = QuadraticField(2) 

sage: R.<x> = K[] 

sage: a = (x + sqrt2)^3 * ((1+sqrt2)*x - 1/sqrt2)^6 

sage: b = a.nth_root(3); b 

(2*sqrt2 + 3)*x^3 + (2*sqrt2 + 2)*x^2 + (-2*sqrt2 - 3/2)*x + 1/2*sqrt2 

sage: b^3 == a 

True 

  

sage: R.<x> = QQbar[] 

sage: p = x**3 + QQbar(2).sqrt() * x - QQbar(3).sqrt() 

sage: r = (p**5).nth_root(5) 

sage: r * p[0] == p * r[0] 

True 

sage: p = (x+1)^20 + x^20 

sage: p.nth_root(20) 

Traceback (most recent call last): 

... 

ValueError: not a 20th power 

  

sage: z = GF(4).gen() 

sage: R.<x> = GF(4)[] 

sage: p = z*x**4 + 2*x - 1 

sage: r = (p**15).nth_root(15) 

sage: r * p[0] == p * r[0] 

True 

sage: ((x+1)**2).nth_root(2) 

x + 1 

sage: ((x+1)**4).nth_root(4) 

x + 1 

sage: ((x+1)**12).nth_root(12) 

x + 1 

sage: (x^4 + x^3 + 1).nth_root(2) 

Traceback (most recent call last): 

... 

ValueError: not a 2nd power 

sage: p = (x+1)^17 + x^17 

sage: r = p.nth_root(17) 

Traceback (most recent call last): 

... 

ValueError: not a 17th power 

  

sage: R1.<x> = QQ[] 

sage: R2.<y> = R1[] 

sage: R3.<z> = R2[] 

sage: (((y**2+x)*z^2 + x*y*z + 2*x)**3).nth_root(3) 

(y^2 + x)*z^2 + x*y*z + 2*x 

sage: ((x+y+z)**5).nth_root(5) 

z + y + x 

  

Here we consider a base ring without ``nth_root`` method. The third 

example with a non-trivial coefficient of lowest degree raises an error:: 

  

sage: R.<x> = QQ[] 

sage: R2 = R.quotient(x**2 + 1) 

sage: x = R2.gen() 

sage: R3.<y> = R2[] 

sage: (y**2 - 2*y + 1).nth_root(2) 

-y + 1 

sage: (y**3).nth_root(3) 

y 

sage: (y**2 + x).nth_root(2) 

Traceback (most recent call last): 

... 

AttributeError: ... has no attribute 'nth_root' 

  

TESTS:: 

  

sage: R.<x> = ZZ[] 

sage: (x^12).nth_root(6) 

x^2 

sage: ((3*x)^15).nth_root(5) 

27*x^3 

sage: parent(R.one().nth_root(3)) 

Univariate Polynomial Ring in x over Integer Ring 

sage: p = (x+1)**20 + x^20 

sage: p.nth_root(20) 

Traceback (most recent call last): 

... 

ValueError: not a 20th power 

sage: (x^3 - 1).nth_root(2) 

Traceback (most recent call last): 

... 

ValueError: not a 2nd power 

sage: (x^3 - 1).nth_root(2) 

Traceback (most recent call last): 

... 

ValueError: not a 2nd power 

  

sage: Zmod(4)['x'].one().nth_root(4) 

Traceback (most recent call last): 

... 

ValueError: n-th root of polynomials over rings with zero divisors 

not implemented 

  

Some random tests:: 

  

sage: for R in [QQ['x'], GF(4)['x']]: 

....: for _ in range(30): 

....: p = R.random_element(degree=randint(10,20)) 

....: n = ZZ.random_element(2,20) 

....: r = (p**n).nth_root(n) 

....: assert r.parent() is R, "R={}\nn={}\np={}".format(R,n,p) 

....: pl = p.leading_coefficient() 

....: rl = r.leading_coefficient() 

....: assert p == r * pl/rl, "R={}\np={}\nr={}".format(R,p,r) 

""" 

R = self.base_ring() 

S = self.parent() 

if R not in sage.categories.integral_domains.IntegralDomains(): 

raise ValueError("n-th root of polynomials over rings with zero divisors not implemented") 

  

if n <= 0: 

raise ValueError("n (={}) must be positive".format(n)) 

elif n == 1 or self.is_zero() or self.is_one(): 

return self 

elif self.degree() % n: 

raise ValueError("not a %s power"%Integer(n).ordinal_str()) 

elif self[0].is_zero(): 

# p = x^k q 

# p^(1/n) = x^(k/n) q^(1/n) 

i = self.valuation() 

if i%n: 

raise ValueError("not a %s power"%Integer(n).ordinal_str()) 

return (self >> i).nth_root(n) << (i // n) 

  

if self[0].is_one(): 

start = S.one() 

else: 

start = S(self[0].nth_root(n)) 

  

cdef Polynomial p, q 

p = self.change_ring(R.fraction_field()) 

q = p._nth_root_series(n, self.degree() // n + 1, start) 

  

# (possible) TODO: below we check that the result is the 

# n-th root. But in ZZ[x] that can be anticipated: we can 

# detect that a given polynomial is not a n-th root inside 

# the iteration of Newton method by looking at denominators. 

if q**n == p: 

return S(q) 

else: 

raise ValueError("not a %s power"%Integer(n).ordinal_str()) 

  

def _nth_root_series(self, long n, long prec, start=None): 

r""" 

Return the first ``prec`` coefficients of the ``n``-th root series of this polynomial. 

  

The method might fail if the exponent ``n`` or the coefficient of 

lowest degree is not invertible in the base ring. In both cases an 

``ArithmeticError`` is raised. 

  

INPUT: 

  

- ``n`` -- positive integer; the exponent of the root 

  

- ``prec`` -- positive integer; the precision of the result 

  

- ``start`` -- optional; the first term of the result. This 

is only considered when the valuation is zero, i.e. when the 

polynomial has a nonzero constant term. 

  

.. ALGORITHM:: 

  

Let us denote by `a` the polynomial from which we wish to extract 

a `n`-th root. The algorithm uses the Newton method for the fixed 

point of `F(x) = x^{-n} - a^{-1}`. The advantage of this approach 

compared to the more naive `x^n - a` is that it does require only 

one polynomial inversion instead of one per iteration of the Newton 

method. 

  

EXAMPLES:: 

  

sage: R.<x> = QQ[] 

sage: (1 + x)._nth_root_series(2, 5) 

-5/128*x^4 + 1/16*x^3 - 1/8*x^2 + 1/2*x + 1 

sage: R.zero()._nth_root_series(3, 5) 

0 

sage: R.one()._nth_root_series(3, 5) 

1 

  

sage: R.<x> = QQbar[] 

sage: p = 2 + 3*x^2 

sage: q = p._nth_root_series(3, 20) 

sage: (q**3).truncate(20) 

3*x^2 + 2 

  

The exponent must be invertible in the base ring:: 

  

sage: R.<x> = ZZ[x] 

sage: (1 + x)._nth_root_series(2, 5) 

Traceback (most recent call last): 

... 

ArithmeticError: exponent not invertible in base ring 

  

Though, the base ring needs not be a field:: 

  

sage: Ru.<u> = QQ[] 

sage: Rux.<x> = Ru[] 

sage: (4 + u*x)._nth_root_series(2,5) 

-5/16384*u^4*x^4 + 1/512*u^3*x^3 - 1/64*u^2*x^2 + 1/4*u*x + 2 

sage: ((4 + u*x)._nth_root_series(2,5)**2).truncate(5) 

u*x + 4 

  

Finite characteristic:: 

  

sage: R.<x> = GF(2)[] 

sage: (1 + x)._nth_root_series(3, 10) 

x^9 + x^8 + x^3 + x^2 + x + 1 

sage: (1 + x^2)._nth_root_series(2, 10) 

x + 1 

sage: (1 + x)._nth_root_series(2, 10) 

Traceback (most recent call last): 

... 

ValueError: not a 2nd power 

  

TESTS:: 

  

sage: QQ['x'].zero()._nth_root_series(3, 5).parent() 

Univariate Polynomial Ring in x over Rational Field 

sage: QQ['x'].one()._nth_root_series(3, 5).parent() 

Univariate Polynomial Ring in x over Rational Field 

""" 

cdef Integer c, cc, e, m, mp1 

cdef Polynomial p, q 

  

R = self.base_ring() 

S = self.parent() 

  

m = ZZ.coerce(n) 

if m <= 0: 

raise ValueError("n (={}) must be positive".format(m)) 

elif m.is_one() or self.is_zero() or self.is_one(): 

return self 

elif self[0].is_zero(): 

# p = x^i q 

# p^(1/m) = x^(i/m) q^(1/m) 

i = self.valuation() 

if i % m: 

raise ValueError("not a %s power"%m.ordinal_str()) 

return (self >> i)._nth_root_series(m, prec - i // m) << (i // m) 

else: 

c = R.characteristic() 

if c and not n % c: 

# characteristic divides n 

e = m.valuation(c) 

cc = c**e 

ans = {} 

for i in range(self.degree()+1): 

if self[i]: 

if i%cc: 

raise ValueError("not a %s power"%m.ordinal_str()) 

ans[i//cc] = self[i].nth_root(cc) 

p = self._parent(ans) 

m = m // cc 

if m.is_one(): 

return p 

else: 

p = self 

  

# beginning of Newton method 

# (we can safely assume that the valuation is 0) 

S = p.parent() 

  

if start is not None: 

a = R(start) 

elif p[0].is_one(): 

a = R.one() 

else: 

a = p[0].nth_root(m) 

  

try: 

q = S(a.inverse_of_unit()) 

except ArithmeticError: 

raise ArithmeticError("constant coefficient not invertible in base ring") 

  

try: 

mi = R(m).inverse_of_unit() 

except ArithmeticError: 

raise ArithmeticError("exponent not invertible in base ring") 

  

from sage.misc.misc import newton_method_sizes 

mp1 = m + 1 

for i in newton_method_sizes(prec): 

q = mi * (mp1 * q - p._mul_trunc_(q._power_trunc(mp1, i), i)) 

return q.inverse_series_trunc(prec) 

  

def specialization(self, D=None, phi=None): 

r""" 

Specialization of this polynomial. 

  

Given a family of polynomials defined over a polynomial ring. A specialization 

is a particular member of that family. The specialization can be specified either 

by a dictionary or a :class:`SpecializationMorphism`. 

  

INPUT: 

  

- ``D`` -- dictionary (optional) 

  

- ``phi`` -- SpecializationMorphism (optional) 

  

OUTPUT: a new polynomial 

  

EXAMPLES:: 

  

sage: R.<c> = PolynomialRing(ZZ) 

sage: S.<z> = PolynomialRing(R) 

sage: F = c*z^2 + c^2 

sage: F.specialization(dict({c:2})) 

2*z^2 + 4 

""" 

if D is None: 

if phi is None: 

raise ValueError("either the dictionary or the specialization must be provided") 

else: 

from sage.rings.polynomial.flatten import SpecializationMorphism 

phi = SpecializationMorphism(self._parent,D) 

return phi(self) 

  

def _log_series(self, long n): 

r""" 

Return the power series expansion of logarithm of this polynomial, 

truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = CBF[] 

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

-0.5000000000000000*x^2 + x 

""" 

raise NotImplementedError 

  

def _exp_series(self, long n): 

r""" 

Return the power series expansion of exponential of this polynomial, 

truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = CBF[] 

sage: x._exp_series(3) 

0.5000000000000000*x^2 + x + 1.000000000000000 

""" 

raise NotImplementedError 

  

def _atan_series(self, long n): 

r""" 

Return the power series expansion of arctangent of this polynomial, 

truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._atan_series(4) 

-1/3*x^3 + x 

""" 

raise NotImplementedError 

  

def _atanh_series(self, long n): 

r""" 

Return the power series expansion of hyperbolic arctangent of this 

polynomial, truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._atanh_series(4) 

1/3*x^3 + x 

""" 

raise NotImplementedError 

  

def _asin_series(self, long n): 

r""" 

Return the power series expansion of arcsine of this polynomial, 

truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._asin_series(4) 

1/6*x^3 + x 

""" 

raise NotImplementedError 

  

def _asinh_series(self, long n): 

r""" 

Return the power series expansion of hyperbolic arcsine of this 

polynomial, truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._asinh_series(4) 

-1/6*x^3 + x 

""" 

raise NotImplementedError 

  

def _tan_series(self, long n): 

r""" 

Return the power series expansion of tangent of this polynomial, 

truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._tan_series(4) 

1/3*x^3 + x 

""" 

raise NotImplementedError 

  

def _sin_series(self, long n): 

r""" 

Return the power series expansion of sine of this polynomial, truncated 

to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._sin_series(4) 

-1/6*x^3 + x 

""" 

raise NotImplementedError 

  

def _cos_series(self, long n): 

r""" 

Return the power series expansion of cosine of this polynomial, 

truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._cos_series(4) 

-1/2*x^2 + 1 

""" 

raise NotImplementedError 

  

def _sinh_series(self, long n): 

r""" 

Return the power series expansion of hyperbolic sine of this 

polynomial, truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._sinh_series(4) 

1/6*x^3 + x 

""" 

raise NotImplementedError 

  

def _cosh_series(self, long n): 

r""" 

Return the power series expansion of hyperbolic cosine of this 

polynomial, truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._cosh_series(4) 

1/2*x^2 + 1 

""" 

raise NotImplementedError 

  

def _tanh_series(self, long n): 

r""" 

Return the power series expansion of hyperbolic tangent of this 

polynomial, truncated to `O(x^n)`. 

  

EXAMPLES:: 

  

sage: Pol.<x> = QQ[] 

sage: x._tanh_series(4) 

-1/3*x^3 + x 

""" 

raise NotImplementedError 

  

  

# ----------------- inner functions ------------- 

# Cython can't handle function definitions inside other function 

  

@cython.boundscheck(False) 

@cython.wraparound(False) 

@cython.overflowcheck(False) 

cdef list do_schoolbook_product(list x, list y, Py_ssize_t deg): 

""" 

Compute the truncated multiplication of two polynomials represented by 

lists, using the schoolbook algorithm. 

  

This is the core of _mul_generic and the code that is used by 

_mul_karatsuba bellow a threshold. 

  

INPUT: 

  

- ``x``, ``y``: lists of coefficients 

- ``deg``: degree at which the output should be truncated, 

negative values mean not to truncate at all 

  

TESTS: 

  

Doctested indirectly in _mul_generic and _mul_karatsuba. For the doctest we 

use a ring such that default multiplication calls external libraries:: 

  

sage: K = ZZ['x'] 

sage: f = K.random_element(8) 

sage: g = K.random_element(8) 

sage: f*g - f._mul_generic(g) 

0 

""" 

cdef Py_ssize_t i, k, start, end 

cdef Py_ssize_t d1 = len(x)-1, d2 = len(y)-1 

if deg < 0 or deg > d1 + d2 + 1: 

deg = d1 + d2 + 1 

if d1 == -1: 

return x 

elif d2 == -1: 

return y 

elif d1 == 0: 

c = x[0] 

return [c*a for a in y[:deg]] # beware of noncommutative rings 

elif d2 == 0: 

c = y[0] 

return [a*c for a in x[:deg]] # beware of noncommutative rings 

coeffs = [None]*deg 

for k in range(deg): 

start = 0 if k <= d2 else k-d2 # max(0, k-d2) 

end = k if k <= d1 else d1 # min(k, d1) 

sum = x[start] * y[k-start] 

for i from start < i <= end: 

sum = sum + x[i] * y[k-i] 

coeffs[k] = sum 

return coeffs 

  

@cython.boundscheck(False) 

@cython.wraparound(False) 

@cython.overflowcheck(False) 

cdef list do_karatsuba_different_size(list left, list right, Py_ssize_t K_threshold): 

""" 

Multiply two polynomials of different degrees by splitting the one of 

largest degree in chunks that are multiplied with the other using the 

Karatsuba algorithm, as explained in _mul_karatsuba. 

  

INPUT: 

  

- `left`: a list representing a polynomial 

- `right`: a list representing a polynomial 

- `K_threshold`: an Integer, a threshold to pass to the classical 

quadratic algorithm. During Karatsuba recursion, if one of the lists 

has length <= K_threshold the classical product is used instead. 

  

TESTS: 

  

This method is indirectly doctested in _mul_karatsuba. 

  

Here, we use Fibonacci numbers that need deepest recursion in this method. 

  

sage: K = ZZ['x'] 

sage: f = K.random_element(21) 

sage: g = K.random_element(34) 

sage: f*g - f._mul_karatsuba(g,0) 

0 

""" 

cdef Py_ssize_t n = len(left), m = len(right) 

cdef Py_ssize_t r, q, i, j, mi 

if n == 0 or m == 0: 

return [] 

if n == 1: 

c = left[0] 

return [c*a for a in right] 

if m == 1: 

c = right[0] 

return [a*c for a in left] # beware of noncommutative rings 

if n <= K_threshold or m <= K_threshold: 

return do_schoolbook_product(left, right, -1) 

if n == m: 

return do_karatsuba(left, right, K_threshold, 0, 0, n) 

if n > m: 

# left is the bigger list 

# n is the bigger number 

q = n // m 

r = n % m 

output = do_karatsuba(left, right, K_threshold, 0, 0, m) 

for i from 1 <= i < q: 

mi = m*i 

carry = do_karatsuba(left, right, K_threshold, mi, 0, m) 

for j from 0 <= j < m-1: 

output[mi+j] = output[mi+j] + carry[j] 

output.extend(carry[m-1:]) 

if r: 

mi = m*q 

carry = do_karatsuba_different_size(left[mi:], right, K_threshold) 

for j from 0 <= j < m-1: 

output[mi+j] = output[mi+j] + carry[j] 

output.extend(carry[m-1:]) 

return output 

else: 

# n < m, I need to repeat the code due to the case 

# of noncommutative rings. 

q = m // n 

r = m % n 

output = do_karatsuba(left, right, K_threshold, 0, 0, n) 

for i from 1 <= i < q: 

mi = n*i 

carry = do_karatsuba(left, right, K_threshold, 0, mi, n) 

for j from 0 <= j < n-1: 

output[mi+j] = output[mi+j] + carry[j] 

output.extend(carry[n-1:]) 

if r: 

mi = n*q 

carry = do_karatsuba_different_size(left, right[mi:], K_threshold) 

for j from 0 <= j < n-1: 

output[mi+j] = output[mi+j] + carry[j] 

output.extend(carry[n-1:]) 

return output 

  

@cython.boundscheck(False) 

@cython.wraparound(False) 

@cython.overflowcheck(False) 

cdef list do_karatsuba(list left, list right, Py_ssize_t K_threshold,Py_ssize_t start_l, Py_ssize_t start_r,Py_ssize_t num_elts): 

""" 

Core routine for Karatsuba multiplication. This function works for two 

polynomials of the same degree. 

  

Input: 

  

- left: a list containing a slice representing a polynomial 

- right: a list containing the slice representing a polynomial with the 

same length as left 

- K_threshold: an integer. For lists of length <= K_threshold, the 

quadratic polynomial multiplication is used. 

- start_l: the index of left where the actual polynomial starts 

- start_r: the index of right where the actual polynomial starts 

- num_elts: the length of the polynomials. 

  

Thus, the actual polynomials we want to multiply are represented by the 

slices: left[ start_l: start_l+num_elts ], right[ right_l: right_l+num_elts ]. 

We use this representation in order to avoid creating slices of lists and 

create smaller lists. 

  

Output: 

  

- a list representing the product of the polynomials 

  

Doctested indirectly in _mul_karatsuba 

  

TESTS:: 

  

sage: K.<x> = ZZ[] 

sage: f = K.random_element(50) + x^51 

sage: g = K.random_element(50) + x^51 

sage: f*g - f._mul_karatsuba(g,0) 

0 

  

Notes on the local variables: 

  

- ac will always be a list of length lenac 

- bd will always be a list of length lenbd 

- a_m_b and c_m_d are lists of length ne, we only make necessary additions 

- tt1 has length lenac 

""" 

cdef Py_ssize_t e, ne, lenac, lenbd, start_le, start_re, i 

if num_elts == 0: 

return [] 

if num_elts == 1: 

return [left[start_l]*right[start_r]] 

if num_elts <= K_threshold: 

# Special case of degree 2, no loop, no function call 

if num_elts == 2: 

b = left[start_l] 

a = left[start_l+1] 

d = right[start_r] 

c = right[start_r+1] 

return [b*d, a*d+b*c, a*c] 

return do_schoolbook_product(left[start_l:start_l+num_elts], 

right[start_r:start_r+num_elts], -1) 

if num_elts == 2: 

# beware of noncommutative rings 

b = left[start_l] 

a = left[start_l+1] 

d = right[start_r] 

c = right[start_r+1] 

ac = a*c 

bd = b*d 

return [bd, (a+b)*(c+d)-ac-bd, ac] 

e = num_elts//2 

ne = num_elts-e 

lenac = 2*ne-1 

lenbd = 2*e-1 

start_le = start_l+e 

start_re = start_r+e 

ac = do_karatsuba(left, right, K_threshold, start_le, start_re, ne) 

bd = do_karatsuba(left, right, K_threshold, start_l, start_r, e) 

a_m_b = left[start_le:start_le+ne] 

c_m_d = right[start_re:start_re+ne] 

for i from 0 <= i < e: 

a_m_b[i] = a_m_b[i] + left[start_l+i] 

c_m_d[i] = c_m_d[i] + right[start_r+i] 

tt1 = do_karatsuba(a_m_b, c_m_d, K_threshold, 0, 0, ne) 

# bd might be shorter than ac, we divide the operations in two loops 

for i from 0 <= i < lenbd: 

tt1[i] = tt1[i] - (ac[i]+bd[i]) 

for i from lenbd <= i < lenac: 

tt1[i] = tt1[i] - ac[i] 

# Reconstruct the product from the lists bd, tt1, ac. 

for i from 0 <= i < e-1: 

bd[e+i] = bd[e+i] + tt1[i] 

bd.append(tt1[e-1]) 

for i from 0 <= i < lenac -e: 

ac[i] = ac[i] + tt1[e+i] 

return bd + ac 

  

  

cdef class Polynomial_generic_dense(Polynomial): 

""" 

A generic dense polynomial. 

  

EXAMPLES:: 

  

sage: f = QQ['x']['y'].random_element() 

sage: loads(f.dumps()) == f 

True 

  

TESTS:: 

  

sage: from sage.rings.polynomial.polynomial_element_generic import Polynomial_generic_dense 

sage: isinstance(f, Polynomial_generic_dense) 

True 

sage: f = CC['x'].random_element() 

sage: isinstance(f, Polynomial_generic_dense) 

True 

  

""" 

def __init__(self, parent, x=None, int check=1, is_gen=False, int construct=0, **kwds): 

Polynomial.__init__(self, parent, is_gen=is_gen) 

if x is None: 

self.__coeffs = [] 

return 

  

R = parent.base_ring() 

if isinstance(x, list): 

if check: 

self.__coeffs = [R(t) for t in x] 

self.__normalize() 

else: 

self.__coeffs = x 

return 

  

if sage.rings.fraction_field_element.is_FractionFieldElement(x): 

if x.denominator() != 1: 

raise TypeError("denominator must be 1") 

else: 

x = x.numerator() 

  

if isinstance(x, Polynomial): 

if (<Element>x)._parent is self._parent: 

x = x.list(copy=True) 

elif R.has_coerce_map_from((<Element>x)._parent):# is R or (<Element>x)._parent == R: 

try: 

if x.is_zero(): 

self.__coeffs = [] 

return 

except (AttributeError, TypeError): 

pass 

x = [x] 

else: 

self.__coeffs = [R(a, **kwds) for a in x.list(copy=False)] 

if check: 

self.__normalize() 

return 

  

elif isinstance(x, int) and x == 0: 

self.__coeffs = [] 

return 

  

elif isinstance(x, dict): 

x = _dict_to_list(x, R.zero()) 

  

elif isinstance(x, pari_gen): 

x = [R(w, **kwds) for w in x.list()] 

check = 0 

elif not isinstance(x, list): 

# We trust that the element constructors do not send x=0 

# if x: 

x = [x] # constant polynomials 

# else: 

# x = [] # zero polynomial 

if check: 

self.__coeffs = [R(z, **kwds) for z in x] 

self.__normalize() 

else: 

self.__coeffs = x 

  

cdef Polynomial_generic_dense _new_c(self, list coeffs, Parent P): 

cdef type t = type(self) 

cdef Polynomial_generic_dense f = <Polynomial_generic_dense>t.__new__(t) 

f._parent = P 

f.__coeffs = coeffs 

return f 

  

cpdef Polynomial _new_constant_poly(self, a, Parent P): 

""" 

Create a new constant polynomial in P with value a. 

  

ASSUMPTION: 

  

The given value **must** be an element of the base ring. That 

assumption is not verified. 

  

EXAMPLES:: 

  

sage: S.<y> = QQ[] 

sage: R.<x> = S[] 

sage: x._new_constant_poly(y+1, R) 

y + 1 

sage: parent(x._new_constant_poly(y+1, R)) 

Univariate Polynomial Ring in x over Univariate Polynomial Ring in y over Rational Field 

""" 

if a: 

return self._new_c([a],P) 

else: 

return self._new_c([],P) 

  

def __reduce__(self): 

""" 

For pickling. 

  

TESTS:: 

  

sage: R.<x> = QQ['a,b']['x'] 

sage: f = x^3-x 

sage: loads(dumps(f)) == f 

True 

  

Make sure we're testing the right method:: 

  

sage: type(f) 

<type 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'> 

""" 

return make_generic_polynomial, (self._parent, self.__coeffs) 

  

def __nonzero__(self): 

return bool(self.__coeffs) 

  

cdef int __normalize(self) except -1: 

""" 

TESTS: 

  

Check that exceptions are propagated correctly (:trac:`18274`):: 

  

sage: class BrokenRational(Rational): 

....: def __bool__(self): 

....: raise NotImplementedError("cannot check whether number is non-zero") 

....: __nonzero__ = __bool__ 

sage: z = BrokenRational() 

sage: R.<x> = QQ[] 

sage: from sage.rings.polynomial.polynomial_element import Polynomial_generic_dense 

sage: Polynomial_generic_dense(R, [z]) 

Traceback (most recent call last): 

... 

NotImplementedError: cannot check whether number is non-zero 

""" 

cdef list x = self.__coeffs 

cdef Py_ssize_t n = len(x) - 1 

while n >= 0 and not x[n]: 

del x[n] 

n -= 1 

  

def __hash__(self): 

return self._hash_c() 

  

@cython.boundscheck(False) 

@cython.wraparound(False) 

cdef get_unsafe(self, Py_ssize_t n): 

""" 

Return the `n`-th coefficient of ``self``. 

  

EXAMPLES:: 

  

sage: R.<x> = RDF[] 

sage: f = (1+2*x)^5; f 

32.0*x^5 + 80.0*x^4 + 80.0*x^3 + 40.0*x^2 + 10.0*x + 1.0 

sage: f[-1] 

0.0 

sage: f[2] 

40.0 

sage: f[6] 

0.0 

sage: f[:3] 

40.0*x^2 + 10.0*x + 1.0 

""" 

return self.__coeffs[n] 

  

def _unsafe_mutate(self, n, value): 

""" 

Never use this unless you really know what you are doing. 

  

.. warning:: 

  

This could easily introduce subtle bugs, since Sage assumes 

everywhere that polynomials are immutable. It's OK to use 

this if you really know what you're doing. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: f = (1+2*x)^2; f 

4*x^2 + 4*x + 1 

sage: f._unsafe_mutate(1, -5) 

sage: f 

4*x^2 - 5*x + 1 

""" 

n = int(n) 

value = self.base_ring()(value) 

if n >= 0 and n < len(self.__coeffs): 

self.__coeffs[n] = value 

if n == len(self.__coeffs) and value == 0: 

self.__normalize() 

elif n < 0: 

raise IndexError("polynomial coefficient index must be nonnegative") 

elif value != 0: 

zero = self.base_ring().zero() 

for _ in xrange(len(self.__coeffs), n): 

self.__coeffs.append(zero) 

self.__coeffs.append(value) 

  

def __floordiv__(self, right): 

""" 

Return the quotient upon division (no remainder). 

  

EXAMPLES:: 

  

sage: R.<x> = QQbar[] 

sage: f = (1+2*x)^3 + 3*x; f 

8*x^3 + 12*x^2 + 9*x + 1 

sage: g = f // (1+2*x); g 

4*x^2 + 4*x + 5/2 

sage: f - g * (1+2*x) 

-3/2 

sage: f.quo_rem(1+2*x) 

(4*x^2 + 4*x + 5/2, -3/2) 

  

TESTS: 

  

Check that :trac:`13048` and :trac:`2034` are fixed:: 

  

sage: R.<x> = QQbar[] 

sage: x // x 

1 

sage: x // 1 

x 

sage: x // int(1) 

x 

sage: x //= int(1); x 

x 

sage: int(1) // x # check that this doesn't segfault 

Traceback (most recent call last): 

... 

AttributeError: type object 'int' has no attribute 'base_ring' 

""" 

if have_same_parent(self, right): 

return (<Polynomial_generic_dense>self)._floordiv_(<Polynomial_generic_dense>right) 

P = parent(self) 

d = P.base_ring()(right) 

cdef Polynomial_generic_dense res = (<Polynomial_generic_dense>self)._new_c([c // d for c in (<Polynomial_generic_dense>self).__coeffs], P) 

res.__normalize() 

return res 

  

cpdef _add_(self, right): 

r""" 

Add two polynomials. 

  

EXAMPLES:: 

  

sage: R.<y> = QQ[] 

sage: S.<x> = R[] 

sage: S([0,1,y,2*y]) + S([1,-2*y,3]) # indirect doctest 

2*y*x^3 + (y + 3)*x^2 + (-2*y + 1)*x + 1 

""" 

cdef Polynomial_generic_dense res 

cdef Py_ssize_t check=0, i, min 

x = (<Polynomial_generic_dense>self).__coeffs 

y = (<Polynomial_generic_dense>right).__coeffs 

if len(x) > len(y): 

min = len(y) 

high = x[min:] 

elif len(x) < len(y): 

min = len(x) 

high = y[min:] 

else: 

min = len(x) 

cdef list low = [x[i] + y[i] for i from 0 <= i < min] 

if len(x) == len(y): 

res = self._new_c(low, self._parent) 

res.__normalize() 

return res 

else: 

return self._new_c(low + high, self._parent) 

  

cpdef _sub_(self, right): 

cdef Polynomial_generic_dense res 

cdef Py_ssize_t check=0, i, min 

x = (<Polynomial_generic_dense>self).__coeffs 

y = (<Polynomial_generic_dense>right).__coeffs 

if len(x) > len(y): 

min = len(y) 

high = x[min:] 

elif len(x) < len(y): 

min = len(x) 

high = [-y[i] for i from min <= i < len(y)] 

else: 

min = len(x) 

low = [x[i] - y[i] for i from 0 <= i < min] 

if len(x) == len(y): 

res = self._new_c(low, self._parent) 

res.__normalize() 

return res 

else: 

return self._new_c(low + high, self._parent) 

  

cpdef _rmul_(self, Element c): 

if not self.__coeffs: 

return self 

if c._parent is not (<Element>self.__coeffs[0])._parent: 

c = (<Element>self.__coeffs[0])._parent._coerce_c(c) 

v = [c * a for a in self.__coeffs] 

cdef Polynomial_generic_dense res = self._new_c(v, self._parent) 

#if not v[len(v)-1]: 

# "normalize" checks this anyway... 

res.__normalize() 

return res 

  

cpdef _lmul_(self, Element c): 

if not self.__coeffs: 

return self 

if c._parent is not (<Element>self.__coeffs[0])._parent: 

c = (<Element>self.__coeffs[0])._parent._coerce_c(c) 

v = [a * c for a in self.__coeffs] 

cdef Polynomial_generic_dense res = self._new_c(v, self._parent) 

#if not v[len(v)-1]: 

# "normalize" checks this anyway... 

res.__normalize() 

return res 

  

cpdef constant_coefficient(self): 

""" 

Return the constant coefficient of this polynomial. 

  

OUTPUT: 

element of base ring 

  

EXAMPLES: 

sage: R.<t> = QQ[] 

sage: S.<x> = R[] 

sage: f = x*t + x + t 

sage: f.constant_coefficient() 

t 

""" 

if not self.__coeffs: 

return self.base_ring().zero() 

else: 

return self.__coeffs[0] 

  

cpdef list list(self, bint copy=True): 

""" 

Return a new copy of the list of the underlying elements of ``self``. 

  

EXAMPLES:: 

  

sage: R.<x> = GF(17)[] 

sage: f = (1+2*x)^3 + 3*x; f 

8*x^3 + 12*x^2 + 9*x + 1 

sage: f.list() 

[1, 9, 12, 8] 

""" 

if copy: 

return list(self.__coeffs) 

else: 

return self.__coeffs 

  

def degree(self, gen=None): 

""" 

EXAMPLES:: 

  

sage: R.<x> = RDF[] 

sage: f = (1+2*x^7)^5 

sage: f.degree() 

35 

  

TESTS: 

  

Check that :trac:`12552` is fixed:: 

  

sage: type(f.degree()) 

<type 'sage.rings.integer.Integer'> 

  

""" 

return smallInteger(len(self.__coeffs) - 1) 

  

def shift(self, Py_ssize_t n): 

r""" 

Returns this polynomial multiplied by the power `x^n`. If 

`n` is negative, terms below `x^n` will be 

discarded. Does not change this polynomial. 

  

EXAMPLES:: 

  

sage: R.<x> = PolynomialRing(PolynomialRing(QQ,'y'), 'x') 

sage: p = x^2 + 2*x + 4 

sage: type(p) 

<type 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'> 

sage: p.shift(0) 

x^2 + 2*x + 4 

sage: p.shift(-1) 

x + 2 

sage: p.shift(2) 

x^4 + 2*x^3 + 4*x^2 

  

TESTS:: 

  

sage: p = R(0) 

sage: p.shift(3).is_zero() 

True 

sage: p.shift(-3).is_zero() 

True 

  

AUTHORS: 

  

- David Harvey (2006-08-06) 

""" 

if n == 0 or self.degree() < 0: 

return self 

if n > 0: 

output = [self.base_ring().zero()] * n 

output.extend(self.__coeffs) 

return self._new_c(output, self._parent) 

if n < 0: 

if n > len(self.__coeffs) - 1: 

return self._parent([]) 

else: 

return self._new_c(self.__coeffs[-int(n):], self._parent) 

  

@coerce_binop 

def quo_rem(self, other): 

""" 

Returns the quotient and remainder of the Euclidean division of 

``self`` and ``other``. 

  

Raises ZerodivisionError if ``other`` is zero. Raises ArithmeticError if the division is not exact. 

  

AUTHORS: 

  

- Kwankyu Lee (2013-06-02) 

  

- Bruno Grenet (2014-07-13) 

  

EXAMPLES:: 

  

sage: P.<x> = QQ[] 

sage: R.<y> = P[] 

sage: f = R.random_element(10) 

sage: g = y^5+R.random_element(4) 

sage: q,r = f.quo_rem(g) 

sage: f == q*g + r 

True 

sage: g = x*y^5 

sage: f.quo_rem(g) 

Traceback (most recent call last): 

... 

ArithmeticError: Division non exact (consider coercing to polynomials over the fraction field) 

sage: g = 0 

sage: f.quo_rem(g) 

Traceback (most recent call last): 

... 

ZeroDivisionError: Division by zero polynomial 

  

TESTS: 

  

The following shows that :trac:`16649` is indeed fixed. :: 

  

sage: P.<x> = QQ[] 

sage: R.<y> = P[] 

sage: f = (2*x^3+1)*y^2 + (x^2-x+3)*y + (3*x+2) 

sage: g = (-1/13*x^2 - x)*y^2 + (-x^2 + 3*x - 155/4)*y - x - 1 

sage: h = f * g 

sage: h.quo_rem(f) 

((-1/13*x^2 - x)*y^2 + (-x^2 + 3*x - 155/4)*y - x - 1, 0) 

sage: h += (2/3*x^2-3*x+1)*y + 7/17*x+6/5 

sage: q,r = h.quo_rem(f) 

sage: h == q*f + r and r.degree() < f.degree() 

True 

""" 

if other.is_zero(): 

raise ZeroDivisionError("Division by zero polynomial") 

if self.is_zero(): 

return self, self 

  

R = self._parent.base_ring() 

x = (<Polynomial_generic_dense>self).__coeffs[:] # make a copy 

y = (<Polynomial_generic_dense>other).__coeffs 

m = len(x) # deg(self)=m-1 

n = len(y) # deg(other)=n-1 

if m < n: 

return self._parent.zero(), self 

  

quo = list() 

for k from m-n >= k >= 0: 

try: 

q = R(x[n+k-1]/y[n-1]) 

except TypeError: 

raise ArithmeticError("Division non exact (consider coercing to polynomials over the fraction field)") 

x[n+k-1] = R.zero() 

for j from n+k-2 >= j >= k: 

x[j] -= q * y[j-k] 

quo.insert(0,q) 

  

return self._new_c(quo,self._parent), self._new_c(x,self._parent)._inplace_truncate(n-1) 

  

cpdef Polynomial truncate(self, long n): 

r""" 

Returns the polynomial of degree ` < n` which is equivalent 

to self modulo `x^n`. 

  

EXAMPLES:: 

  

sage: S.<q> = QQ['t']['q'] 

sage: f = (1+q^10+q^11+q^12).truncate(11); f 

q^10 + 1 

sage: f = (1+q^10+q^100).truncate(50); f 

q^10 + 1 

sage: f.degree() 

10 

sage: f = (1+q^10+q^100).truncate(500); f 

q^100 + q^10 + 1 

  

TESTS: 

  

Make sure we're not actually testing a specialized 

implementation. 

  

:: 

  

sage: type(f) 

<type 'sage.rings.polynomial.polynomial_element.Polynomial_generic_dense'> 

""" 

l = len(self.__coeffs) 

if n > l: 

n = l 

while n > 0 and not self.__coeffs[n-1]: 

n -= 1 

return self._new_c(self.__coeffs[:n], self._parent) 

  

cdef _inplace_truncate(self, long n): 

if n < len(self.__coeffs): 

while n > 0 and not self.__coeffs[n-1]: 

n -= 1 

self.__coeffs = self.__coeffs[:n] 

return self 

  

def make_generic_polynomial(parent, coeffs): 

return parent(coeffs) 

  

  

@cached_function 

def universal_discriminant(n): 

r""" 

Return the discriminant of the 'universal' univariate polynomial 

`a_n x^n + \cdots + a_1 x + a_0` in `\ZZ[a_0, \ldots, a_n][x]`. 

  

INPUT: 

  

- ``n`` - degree of the polynomial 

  

OUTPUT: 

  

The discriminant as a polynomial in `n + 1` variables over `\ZZ`. 

The result will be cached, so subsequent computations of 

discriminants of the same degree will be faster. 

  

EXAMPLES:: 

  

sage: from sage.rings.polynomial.polynomial_element import universal_discriminant 

sage: universal_discriminant(1) 

1 

sage: universal_discriminant(2) 

a1^2 - 4*a0*a2 

sage: universal_discriminant(3) 

a1^2*a2^2 - 4*a0*a2^3 - 4*a1^3*a3 + 18*a0*a1*a2*a3 - 27*a0^2*a3^2 

sage: universal_discriminant(4).degrees() 

(3, 4, 4, 4, 3) 

  

.. SEEALSO:: 

:meth:`Polynomial.discriminant` 

""" 

pr1 = PolynomialRing(ZZ, n + 1, 'a') 

pr2 = PolynomialRing(pr1, 'x') 

p = pr2(list(pr1.gens())) 

return (1 - (n&2))*p.resultant(p.derivative())//pr1.gen(n) 

  

cpdef Polynomial generic_power_trunc(Polynomial p, Integer n, long prec): 

r""" 

Generic truncated power algorithm 

  

INPUT: 

  

- ``p`` - a polynomial 

  

- ``n`` - an integer (of type :class:`sage.rings.integer.Integer`) 

  

- ``prec`` - a precision (should fit into a C long) 

  

TESTS: 

  

Comparison with flint for polynomials over integers and finite field:: 

  

sage: from sage.rings.polynomial.polynomial_element import generic_power_trunc 

  

sage: for S in [ZZ, GF(3)]: 

....: R = PolynomialRing(S, 'x') 

....: for _ in range(100): 

....: p = R.random_element() 

....: n = ZZ.random_element(0, 100) 

....: prec = ZZ.random_element(0, 100) 

....: assert p.power_trunc(n, prec) == generic_power_trunc(p, n, prec), "p = {} n = {} prec = {}".format(p, n, prec) 

""" 

if mpz_sgn(n.value) < 0: 

raise ValueError("n must be a non-negative integer") 

elif prec <= 0: 

return p._parent.zero() 

  

if mpz_cmp_ui(n.value, 4) < 0: 

# These cases will probably be called often 

# and don't benefit from the code below 

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

return p.parent().one() 

elif mpz_cmp_ui(n.value, 1) == 0: 

return p.truncate(prec) 

elif mpz_cmp_ui(n.value, 2) == 0: 

return p._mul_trunc_(p, prec) 

elif mpz_cmp_ui(n.value, 3) == 0: 

return p._mul_trunc_(p, prec)._mul_trunc_(p, prec) 

  

# check for idempotence, and store the result otherwise 

cdef Polynomial a = p.truncate(prec) 

cdef Polynomial aa = a._mul_trunc_(a, prec) 

if aa == a: 

return a 

  

# since we've computed a^2, let's start squaring there 

# so, let's keep the least-significant bit around, just 

# in case. 

cdef int mul_to_do = mpz_tstbit(n.value, 0) 

cdef mp_bitcnt_t i = 1 

cdef mp_bitcnt_t size = mpz_sizeinbase(n.value, 2) 

  

# One multiplication can be saved by starting with 

# the second-smallest power needed rather than with 1 

# we've already squared a, so let's start there. 

cdef Polynomial apow = aa 

while not mpz_tstbit(n.value, i): 

apow = apow._mul_trunc_(apow, prec) 

i += 1 

cdef Polynomial power = apow 

i += 1 

  

# now multiply that least-significant bit in... 

if mul_to_do: 

power = power._mul_trunc_(a, prec) 

  

# and this is straight from the book. 

while i < size: 

apow = apow._mul_trunc_(apow, prec) 

if mpz_tstbit(n.value, i): 

power = power._mul_trunc_(apow, prec) 

i += 1 

  

return power 

  

cpdef list _dict_to_list(dict x, zero): 

""" 

Convert a dict to a list. 

  

EXAMPLES:: 

  

sage: from sage.rings.polynomial.polynomial_element import _dict_to_list 

sage: _dict_to_list({3:-1, 0:5}, 0) 

[5, 0, 0, -1] 

""" 

if not x: 

return [] 

n = max(x.keys()) 

cdef list v 

if isinstance(n, tuple): # a mpoly dict 

n = n[0] 

v = [zero] * (n+1) 

for i, z in x.iteritems(): 

v[i[0]] = z 

else: 

v = [zero] * (n+1) 

for i, z in x.iteritems(): 

v[i] = z 

return v 

  

cdef class Polynomial_generic_dense_inexact(Polynomial_generic_dense): 

""" 

A dense polynomial over an inexact ring. 

  

AUTHOR: 

  

- Xavier Caruso (2013-03) 

""" 

cdef int __normalize(self) except -1: 

r""" 

TESTS:: 

  

Coefficients indistinguishable from 0 are not removed. 

  

sage: R = Zp(5) 

sage: S.<x> = R[] 

sage: S([1,R(0,20)]) 

(O(5^20))*x + (1 + O(5^20)) 

""" 

cdef list x = self.__coeffs 

cdef Py_ssize_t n = len(x) - 1 

cdef RingElement c 

while n >= 0: 

c = x[n] 

if c.is_zero() and c.precision_absolute() is infinity.Infinity: 

del x[n] 

n -= 1 

else: 

break 

  

def degree(self, secure=False): 

r""" 

INPUT: 

  

- secure -- a boolean (default: False) 

  

OUTPUT: 

  

The degree of self. 

  

If ``secure`` is True and the degree of this polynomial 

is not determined (because the leading coefficient is 

indistinguishable from 0), an error is raised 

  

If ``secure`` is False, the returned value is the largest 

`n` so that the coefficient of `x^n` does not compare equal 

to `0`. 

  

EXAMPLES:: 

  

sage: K = Qp(3,10) 

sage: R.<T> = K[] 

sage: f = T + 2; f 

(1 + O(3^10))*T + (2 + O(3^10)) 

sage: f.degree() 

1 

sage: (f-T).degree() 

0 

sage: (f-T).degree(secure=True) 

Traceback (most recent call last): 

... 

PrecisionError: the leading coefficient is indistinguishable from 0 

  

sage: x = O(3^5) 

sage: li = [3^i * x for i in range(0,5)]; li 

[O(3^5), O(3^6), O(3^7), O(3^8), O(3^9)] 

sage: f = R(li); f 

(O(3^9))*T^4 + (O(3^8))*T^3 + (O(3^7))*T^2 + (O(3^6))*T + (O(3^5)) 

sage: f.degree() 

-1 

sage: f.degree(secure=True) 

Traceback (most recent call last): 

... 

PrecisionError: the leading coefficient is indistinguishable from 0 

  

AUTHOR: 

  

- Xavier Caruso (2013-03) 

""" 

coeffs = self.__coeffs 

d = len(coeffs) - 1 

while d >= 0: 

c = coeffs[d] 

if c.is_zero(): 

if secure: 

from sage.rings.padics.precision_error import PrecisionError 

raise PrecisionError("the leading coefficient is indistinguishable from 0") 

else: 

d -= 1 

else: 

break 

return d 

  

def prec_degree(self): 

r""" 

Returns the largest `n` so that precision information is 

stored about the coefficient of `x^n`. 

  

Always greater than or equal to degree. 

  

EXAMPLES:: 

  

sage: K = Qp(3,10) 

sage: R.<T> = K[] 

sage: f = T + 2; f 

(1 + O(3^10))*T + (2 + O(3^10)) 

sage: f.degree() 

1 

sage: f.prec_degree() 

1 

  

sage: g = f - T; g 

(O(3^10))*T + (2 + O(3^10)) 

sage: g.degree() 

0 

sage: g.prec_degree() 

1 

  

AUTHOR: 

  

- Xavier Caruso (2013-03) 

""" 

return len(self.__coeffs) - 1 

  

  

cdef class ConstantPolynomialSection(Map): 

""" 

This class is used for conversion from a polynomial ring to its base ring. 

  

Since :trac:`9944`, it calls the constant_coefficient method, 

which can be optimized for a particular polynomial type. 

  

EXAMPLES:: 

  

sage: P0.<y_1> = GF(3)[] 

sage: P1.<y_2,y_1,y_0> = GF(3)[] 

sage: P0(-y_1) # indirect doctest 

2*y_1 

  

sage: phi = GF(3).convert_map_from(P0); phi 

Generic map: 

From: Univariate Polynomial Ring in y_1 over Finite Field of size 3 

To: Finite Field of size 3 

sage: type(phi) 

<type 'sage.rings.polynomial.polynomial_element.ConstantPolynomialSection'> 

sage: phi(P0.one()) 

1 

sage: phi(y_1) 

Traceback (most recent call last): 

... 

TypeError: not a constant polynomial 

""" 

cpdef Element _call_(self, x): 

""" 

TESTS:: 

  

sage: from sage.rings.polynomial.polynomial_element import ConstantPolynomialSection 

sage: R.<x> = QQ[] 

sage: m = ConstantPolynomialSection(R, QQ); m 

Generic map: 

From: Univariate Polynomial Ring in x over Rational Field 

To: Rational Field 

sage: m(x-x+1/2) # implicit 

1/2 

sage: m(x-x) 

0 

sage: m(x) 

Traceback (most recent call last): 

... 

TypeError: not a constant polynomial 

""" 

if x.degree() <= 0: 

try: 

return <Element>(x.constant_coefficient()) 

except AttributeError: 

return <Element>((<Polynomial>x).constant_coefficient()) 

else: 

raise TypeError("not a constant polynomial") 

  

cdef class PolynomialBaseringInjection(Morphism): 

""" 

This class is used for conversion from a ring to a polynomial 

over that ring. 

  

It calls the _new_constant_poly method on the generator, 

which should be optimized for a particular polynomial type. 

  

Technically, it should be a method of the polynomial ring, but 

few polynomial rings are cython classes, and so, as a method 

of a cython polynomial class, it is faster. 

  

EXAMPLES: 

  

We demonstrate that most polynomial ring classes use 

polynomial base injection maps for coercion. They are 

supposed to be the fastest maps for that purpose. See 

:trac:`9944`. :: 

  

sage: R.<x> = Qp(3)[] 

sage: R.coerce_map_from(R.base_ring()) 

Polynomial base injection morphism: 

From: 3-adic Field with capped relative precision 20 

To: Univariate Polynomial Ring in x over 3-adic Field with capped relative precision 20 

sage: R.<x,y> = Qp(3)[] 

sage: R.coerce_map_from(R.base_ring()) 

Polynomial base injection morphism: 

From: 3-adic Field with capped relative precision 20 

To: Multivariate Polynomial Ring in x, y over 3-adic Field with capped relative precision 20 

sage: R.<x,y> = QQ[] 

sage: R.coerce_map_from(R.base_ring()) 

Polynomial base injection morphism: 

From: Rational Field 

To: Multivariate Polynomial Ring in x, y over Rational Field 

sage: R.<x> = QQ[] 

sage: R.coerce_map_from(R.base_ring()) 

Polynomial base injection morphism: 

From: Rational Field 

To: Univariate Polynomial Ring in x over Rational Field 

  

By :trac:`9944`, there are now only very few exceptions:: 

  

sage: PolynomialRing(QQ,names=[]).coerce_map_from(QQ) 

Generic morphism: 

From: Rational Field 

To: Multivariate Polynomial Ring in no variables over Rational Field 

""" 

  

cdef RingElement _an_element 

cdef object _new_constant_poly_ 

  

def __init__(self, domain, codomain): 

""" 

TESTS:: 

  

sage: from sage.rings.polynomial.polynomial_element import PolynomialBaseringInjection 

sage: PolynomialBaseringInjection(QQ, QQ['x']) 

Polynomial base injection morphism: 

From: Rational Field 

To: Univariate Polynomial Ring in x over Rational Field 

sage: PolynomialBaseringInjection(ZZ, QQ['x']) 

Traceback (most recent call last): 

... 

AssertionError: domain must be basering 

  

:: 

  

sage: R.<t> = Qp(2)[] 

sage: f = R.convert_map_from(R.base_ring()) # indirect doctest 

sage: f(Qp(2).one()*3) 

(1 + 2 + O(2^20)) 

sage: (Qp(2).one()*3)*t 

(1 + 2 + O(2^20))*t 

""" 

assert codomain.base_ring() is domain, "domain must be basering" 

Morphism.__init__(self, domain, codomain) 

self._an_element = codomain.gen() 

self._repr_type_str = "Polynomial base injection" 

self._new_constant_poly_ = self._an_element._new_constant_poly 

  

cdef dict _extra_slots(self): 

""" 

EXAMPLES:: 

  

sage: phi = QQ['x'].coerce_map_from(QQ) # indirect doctest 

sage: phi 

Polynomial base injection morphism: 

From: Rational Field 

To: Univariate Polynomial Ring in x over Rational Field 

sage: phi(3/1) 

3 

""" 

slots = Morphism._extra_slots(self) 

slots.update( 

_an_element=self._an_element, 

_new_constant_poly_=self._new_constant_poly_) 

return slots 

  

cdef _update_slots(self, dict _slots): 

""" 

EXAMPLES:: 

  

sage: phi = QQ['x'].coerce_map_from(QQ) # indirect doctest 

sage: phi 

Polynomial base injection morphism: 

From: Rational Field 

To: Univariate Polynomial Ring in x over Rational Field 

sage: phi(3/1) 

3 

""" 

Morphism._update_slots(self, _slots) 

self._an_element = _slots['_an_element'] 

self._new_constant_poly_ = _slots['_new_constant_poly_'] 

  

cpdef Element _call_(self, x): 

""" 

TESTS:: 

  

sage: from sage.rings.polynomial.polynomial_element import PolynomialBaseringInjection 

sage: m = PolynomialBaseringInjection(ZZ, ZZ['x']); m 

Polynomial base injection morphism: 

From: Integer Ring 

To: Univariate Polynomial Ring in x over Integer Ring 

sage: m(2) # indirect doctest 

2 

sage: parent(m(2)) 

Univariate Polynomial Ring in x over Integer Ring 

""" 

return self._new_constant_poly_(x, self._codomain) 

  

cpdef Element _call_with_args(self, x, args=(), kwds={}): 

""" 

TESTS:: 

  

sage: from sage.rings.polynomial.polynomial_element import PolynomialBaseringInjection 

sage: m = PolynomialBaseringInjection(Qp(5), Qp(5)['x']) 

sage: m(1 + O(5^11), absprec = 5) # indirect doctest 

(1 + O(5^11)) 

""" 

try: 

return self._codomain._element_constructor_(x, *args, **kwds) 

except AttributeError: 

# if there is no element constructor, 

# there is a custom call method. 

return self._codomain(x, *args, **kwds) 

  

def section(self): 

""" 

TESTS:: 

  

sage: from sage.rings.polynomial.polynomial_element import PolynomialBaseringInjection 

sage: m = PolynomialBaseringInjection(RDF, RDF['x']) 

sage: m.section() 

Generic map: 

From: Univariate Polynomial Ring in x over Real Double Field 

To: Real Double Field 

sage: type(m.section()) 

<type 'sage.rings.polynomial.polynomial_element.ConstantPolynomialSection'> 

""" 

return ConstantPolynomialSection(self._codomain, self.domain()) 

  

def is_injective(self): 

r""" 

Return whether this morphism is injective. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: S.<y> = R[] 

sage: S.coerce_map_from(R).is_injective() 

True 

  

Check that :trac:`23203` has been resolved:: 

  

sage: R.is_subring(S) # indirect doctest 

True 

  

""" 

return True 

  

def is_surjective(self): 

r""" 

Return whether this morphism is surjective. 

  

EXAMPLES:: 

  

sage: R.<x> = ZZ[] 

sage: R.coerce_map_from(ZZ).is_surjective() 

False 

  

""" 

return False