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

""" 

Univariate Polynomial Rings 

 

Sage implements sparse and dense polynomials over commutative and 

non-commutative rings. In the non-commutative case, the polynomial 

variable commutes with the elements of the base ring. 

 

AUTHOR: 

 

- William Stein 

 

- Kiran Kedlaya (2006-02-13): added macaulay2 option 

 

- Martin Albrecht (2006-08-25): removed it again as it isn't needed anymore 

 

- Simon King (2011-05): Dense and sparse polynomial rings must not be equal. 

 

- Simon King (2011-10): Choice of categories for polynomial rings. 

 

EXAMPLES:: 

 

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

sage: (z^3 + z - 1)^3 

z^9 + 3*z^7 - 3*z^6 + 3*z^5 - 6*z^4 + 4*z^3 - 3*z^2 + 3*z - 1 

 

Saving and loading of polynomial rings works:: 

 

sage: loads(dumps(QQ['x'])) == QQ['x'] 

True 

sage: k = PolynomialRing(QQ['x'],'y'); loads(dumps(k))==k 

True 

sage: k = PolynomialRing(ZZ,'y'); loads(dumps(k)) == k 

True 

sage: k = PolynomialRing(ZZ,'y', sparse=True); loads(dumps(k)) 

Sparse Univariate Polynomial Ring in y over Integer Ring 

 

Rings with different variable names are not equal; in fact, 

by :trac:`9944`, polynomial rings are equal if and only 

if they are identical (which should be the case for all parent 

structures in Sage):: 

 

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

True 

sage: QQ['y'] != QQ['z'] 

True 

 

We create a polynomial ring over a quaternion algebra:: 

 

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

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

sage: f = w^3 + (i+j)*w + 1 

sage: f 

w^3 + (i + j)*w + 1 

sage: f^2 

w^6 + (2*i + 2*j)*w^4 + 2*w^3 - 2*w^2 + (2*i + 2*j)*w + 1 

sage: f = w + i ; g = w + j 

sage: f * g 

w^2 + (i + j)*w + k 

sage: g * f 

w^2 + (i + j)*w - k 

 

:trac:`9944` introduced some changes related with 

coercion. Previously, a dense and a sparse polynomial ring with the 

same variable name over the same base ring evaluated equal, but of 

course they were not identical.Coercion maps are cached - but if a 

coercion to a dense ring is requested and a coercion to a sparse ring 

is returned instead (since the cache keys are equal!), all hell breaks 

loose. 

 

Therefore, the coercion between rings of sparse and dense polynomials 

works as follows:: 

 

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

sage: S.<x> = QQ[] 

sage: S == R 

False 

sage: S.has_coerce_map_from(R) 

True 

sage: R.has_coerce_map_from(S) 

False 

sage: (R.0+S.0).parent() 

Univariate Polynomial Ring in x over Rational Field 

sage: (S.0+R.0).parent() 

Univariate Polynomial Ring in x over Rational Field 

 

It may be that one has rings of dense or sparse polynomials over 

different base rings. In that situation, coercion works by means of 

the :func:`~sage.categories.pushout.pushout` formalism:: 

 

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

sage: S.<x> = PolynomialRing(ZZ) 

sage: R.has_coerce_map_from(S) 

False 

sage: S.has_coerce_map_from(R) 

False 

sage: S.0 + R.0 

2*x 

sage: (S.0 + R.0).parent() 

Univariate Polynomial Ring in x over Finite Field of size 5 

sage: (S.0 + R.0).parent().is_sparse() 

False 

 

Similarly, there is a coercion from the (non-default) NTL 

implementation for univariate polynomials over the integers 

to the default FLINT implementation, but not vice versa:: 

 

sage: R.<x> = PolynomialRing(ZZ, implementation = 'NTL') 

sage: S.<x> = PolynomialRing(ZZ, implementation = 'FLINT') 

sage: (S.0+R.0).parent() is S 

True 

sage: (R.0+S.0).parent() is S 

True 

 

TESTS:: 

 

sage: K.<x>=FractionField(QQ['x']) 

sage: V.<z> = K[] 

sage: x+z 

z + x 

 

Check that :trac:`5562` has been fixed:: 

 

sage: R.<u> = PolynomialRing(RDF, 1) 

sage: v1 = vector([u]) 

sage: v2 = vector([CDF(2)]) 

sage: v1 * v2 

2.0*u 

 

""" 

 

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

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

# 

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

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

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

# (at your option) any later version. 

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

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

 

from __future__ import absolute_import, print_function 

 

import sys 

from six.moves import range 

 

from sage.structure.element import Element 

 

import sage.categories as categories 

 

import sage.algebras.algebra 

import sage.rings.commutative_algebra as commutative_algebra 

import sage.rings.ring as ring 

from sage.structure.element import is_RingElement 

import sage.rings.polynomial.polynomial_element_generic as polynomial_element_generic 

import sage.rings.rational_field as rational_field 

from sage.rings.integer_ring import ZZ 

from sage.rings.integer import Integer 

from sage.rings.number_field.number_field_base import is_NumberField 

from sage.libs.pari.all import pari_gen 

from sage.rings.polynomial.polynomial_ring_constructor import polynomial_default_category 

 

import sage.misc.latex as latex 

from sage.misc.prandom import randint 

from sage.misc.cachefunc import cached_method 

from sage.misc.lazy_attribute import lazy_attribute 

 

from sage.rings.real_mpfr import is_RealField 

from sage.rings.polynomial.polynomial_singular_interface import PolynomialRing_singular_repr 

from sage.rings.fraction_field_element import FractionFieldElement 

from sage.rings.finite_rings.element_base import FiniteRingElement 

 

from .polynomial_element import PolynomialBaseringInjection 

from .polynomial_real_mpfr_dense import PolynomialRealDense 

from .polynomial_integer_dense_flint import Polynomial_integer_dense_flint 

 

_CommutativeRings = categories.commutative_rings.CommutativeRings() 

 

from . import cyclotomic 

 

from sage.interfaces.singular import SingularElement 

 

 

def is_PolynomialRing(x): 

""" 

Return True if x is a *univariate* polynomial ring (and not a 

sparse multivariate polynomial ring in one variable). 

 

EXAMPLES:: 

 

sage: from sage.rings.polynomial.polynomial_ring import is_PolynomialRing 

sage: from sage.rings.polynomial.multi_polynomial_ring import is_MPolynomialRing 

sage: is_PolynomialRing(2) 

False 

 

This polynomial ring is not univariate. 

 

:: 

 

sage: is_PolynomialRing(ZZ['x,y,z']) 

False 

sage: is_MPolynomialRing(ZZ['x,y,z']) 

True 

 

:: 

 

sage: is_PolynomialRing(ZZ['w']) 

True 

 

Univariate means not only in one variable, but is a specific data 

type. There is a multivariate (sparse) polynomial ring data type, 

which supports a single variable as a special case. 

 

:: 

 

sage: R.<w> = PolynomialRing(ZZ, implementation="singular"); R 

Multivariate Polynomial Ring in w over Integer Ring 

sage: is_PolynomialRing(R) 

False 

sage: type(R) 

<type 'sage.rings.polynomial.multi_polynomial_libsingular.MPolynomialRing_libsingular'> 

""" 

return isinstance(x, PolynomialRing_general) 

 

 

######################################################################################### 

 

class PolynomialRing_general(sage.algebras.algebra.Algebra): 

""" 

Univariate polynomial ring over a ring. 

""" 

_no_generic_basering_coercion = True 

def __init__(self, base_ring, name=None, sparse=False, element_class=None, category=None): 

""" 

EXAMPLES:: 

 

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

sage: R(-1) + R(1) 

0 

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

x^3 - 26/3*x^2 + 64/3*x - 32/3 

 

sage: category(ZZ['x']) 

Join of Category of unique factorization domains 

and Category of commutative algebras over 

(euclidean domains and infinite enumerated sets and metric spaces) 

and Category of infinite sets 

sage: category(GF(7)['x']) 

Join of Category of euclidean domains 

and Category of commutative algebras over 

(finite enumerated fields and subquotients of monoids and quotients of semigroups) and Category of infinite sets 

 

TESTS: 

 

Verify that :trac:`15232` has been resolved:: 

 

sage: K.<x> = FunctionField(QQ) 

sage: R.<y> = K[] 

sage: TestSuite(R).run() 

 

Check that category for zero ring:: 

 

sage: PolynomialRing(Zmod(1), 'x').category() 

Category of finite rings 

""" 

# We trust that, if category is given, it is useful and does not need to be joined 

# with the default category 

if category is None: 

if base_ring.is_zero(): 

category = categories.rings.Rings().Finite() 

else: 

category = polynomial_default_category(base_ring.category(), 1) 

self.__is_sparse = sparse 

if element_class: 

self._polynomial_class = element_class 

else: 

if sparse: 

self._polynomial_class = polynomial_element_generic.Polynomial_generic_sparse 

else: 

from sage.rings.polynomial import polynomial_element 

self._polynomial_class = polynomial_element.Polynomial_generic_dense 

self.Element = self._polynomial_class 

self.__cyclopoly_cache = {} 

self._has_singular = False 

# Algebra.__init__ also calls __init_extra__ of Algebras(...).parent_class, which 

# tries to provide a conversion from the base ring, if it does not exist. 

# This is for algebras that only do the generic stuff in their initialisation. 

# But the attribute _no_generic_basering_coercion prevents that from happening, 

# since we want to use PolynomialBaseringInjection. 

sage.algebras.algebra.Algebra.__init__(self, base_ring, names=name, normalize=True, category=category) 

self.__generator = self.element_class(self, [0,1], is_gen=True) 

self._populate_coercion_lists_( 

#coerce_list = [base_inject], 

#convert_list = [list, base_inject], 

convert_method_name = '_polynomial_') 

 

def __reduce__(self): 

from sage.rings.polynomial.polynomial_ring_constructor import unpickle_PolynomialRing 

args = (self.base_ring(), self.variable_names(), None, self.is_sparse()) 

return unpickle_PolynomialRing, args 

 

def _element_constructor_(self, x=None, check=True, is_gen=False, 

construct=False, **kwds): 

r""" 

Convert ``x`` into this univariate polynomial ring, 

possibly non-canonically. 

 

Conversion from power series:: 

 

sage: R.<x> = QQ[] 

sage: R(1 + x + x^2 + O(x^3)) 

x^2 + x + 1 

 

Stacked polynomial rings coerce into constants if possible. First, 

the univariate case:: 

 

sage: R.<x> = QQ[] 

sage: S.<u> = R[] 

sage: S(u + 2) 

u + 2 

sage: S(x + 3) 

x + 3 

sage: S(x + 3).degree() 

0 

 

Second, the multivariate case:: 

 

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

sage: S.<u> = R[] 

sage: S(x + 2*y) 

x + 2*y 

sage: S(x + 2*y).degree() 

0 

sage: S(u + 2*x) 

u + 2*x 

sage: S(u + 2*x).degree() 

1 

 

Foreign polynomial rings coerce into the highest ring; the point 

here is that an element of T could coerce to an element of R or an 

element of S; it is anticipated that an element of T is more likely 

to be "the right thing" and is historically consistent. 

 

:: 

 

sage: R.<x> = QQ[] 

sage: S.<u> = R[] 

sage: T.<a> = QQ[] 

sage: S(a) 

u 

 

Coercing in pari elements:: 

 

sage: QQ['x'](pari('[1,2,3/5]')) 

3/5*x^2 + 2*x + 1 

sage: QQ['x'](pari('(-1/3)*x^10 + (2/3)*x - 1/5')) 

-1/3*x^10 + 2/3*x - 1/5 

 

Coercing strings:: 

 

sage: QQ['y']('-y') 

-y 

 

TESTS: 

 

Python 3 range is allowed:: 

 

sage: from six.moves import range 

sage: R = PolynomialRing(ZZ,'x') 

sage: R(range(4)) 

3*x^3 + 2*x^2 + x 

 

This shows that the issue at :trac:`4106` is fixed:: 

 

sage: x = var('x') 

sage: R = IntegerModRing(4) 

sage: S = R['x'] 

sage: S(x) 

x 

 

Throw a TypeError if any of the coefficients cannot be coerced 

into the base ring (:trac:`6777`):: 

 

sage: RealField(300)['x']( [ 1, ComplexField(300).gen(), 0 ]) 

Traceback (most recent call last): 

... 

TypeError: unable to convert '1.00...00*I' to a real number 

 

Check that the bug in :trac:`11239` is fixed:: 

 

sage: K.<a> = GF(5^2, prefix='z') 

sage: L.<b> = GF(5^4, prefix='z') 

sage: f = K['x'].gen() + a 

sage: L['x'](f) 

x + b^3 + b^2 + b + 3 

 

A test from :trac:`14485` :: 

 

sage: x = SR.var('x') 

sage: QQbar[x](x^6+x^5+x^4-x^3+x^2-x+2/5) 

x^6 + x^5 + x^4 - x^3 + x^2 - x + 2/5 

""" 

C = self.element_class 

if isinstance(x, (list, tuple)): 

return C(self, x, check=check, is_gen=False, construct=construct) 

if isinstance(x, range): 

return C(self, list(x), check=check, is_gen=False, 

construct=construct) 

if isinstance(x, Element): 

P = x.parent() 

if P is self: 

return x 

elif P is self.base_ring(): 

# It *is* the base ring, hence, we should not need to check. 

# Moreover, if x is equal to zero then we usually need to 

# provide [] to the polynomial class, not [x], if we don't want 

# to check (normally, polynomials like to strip trailing zeroes). 

# However, in the padic case, we WANT that trailing 

# zeroes are not stripped, because O(5)==0, but still it must 

# not be forgotten. It should be the job of the __init__ method 

# to decide whether to strip or not to strip. 

return C(self, [x], check=False, is_gen=False, 

construct=construct) 

elif P == self.base_ring(): 

return C(self, [x], check=True, is_gen=False, 

construct=construct) 

if isinstance(x, SingularElement) and self._has_singular: 

self._singular_().set_ring() 

try: 

return x.sage_poly(self) 

except Exception: 

raise TypeError("Unable to coerce singular object") 

elif isinstance(x , str): 

try: 

from sage.misc.parser import Parser, LookupNameMaker 

R = self.base_ring() 

p = Parser(Integer, R, LookupNameMaker({self.variable_name(): self.gen()}, R)) 

return self(p.parse(x)) 

except NameError: 

raise TypeError("Unable to coerce string") 

elif isinstance(x, FractionFieldElement): 

if x.denominator().is_unit(): 

x = x.numerator() * x.denominator().inverse_of_unit() 

else: 

raise TypeError("denominator must be a unit") 

elif isinstance(x, pari_gen): 

if x.type() == 't_RFRAC': 

raise TypeError("denominator must be a unit") 

if x.type() != 't_POL': 

x = x.Polrev() 

elif isinstance(x, FiniteRingElement): 

try: 

return self(x.polynomial()) 

except AttributeError: 

pass 

elif isinstance(x, sage.rings.power_series_ring_element.PowerSeries): 

x = x.truncate() 

return C(self, x, check, is_gen, construct=construct, **kwds) 

 

@classmethod 

def _implementation_names(cls, implementation, base_ring, sparse=False): 

""" 

Check whether this class can handle the implementation 

``implementation`` over the given base ring and sparseness. 

 

This is a simple wrapper around :meth:`_implementation_names_impl` 

which does the real work. 

 

.. NOTE:: 

 

It is assumed that the ``base_ring`` argument is a base ring 

which the class can handle. 

 

INPUT: 

 

- ``implementation`` -- either a string denoting a specific 

implementation or ``None`` for the default. 

 

- ``base_ring`` -- the base ring for the polynomial ring. 

 

- ``sparse`` -- (boolean) whether the implementation is sparse. 

 

OUTPUT: 

 

- if the implementation is supported, the output is a list of 

all names (possibly including ``None``) which refer to the 

given implementation. The first element of the list is the 

canonical name. If the ``__init__`` method does not take an 

``implementation`` keyword, then the first element must be 

``None``. 

 

- if the implementation is not supported, raise a 

``ValueError``. 

 

EXAMPLES:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_general 

sage: PolynomialRing_general._implementation_names(None, ZZ, True) 

[None, 'generic'] 

sage: PolynomialRing_general._implementation_names("generic", ZZ, True) 

[None, 'generic'] 

sage: PolynomialRing_general._implementation_names("xyzzy", ZZ, True) 

Traceback (most recent call last): 

... 

ValueError: unknown implementation 'xyzzy' for sparse polynomial rings over Integer Ring 

""" 

names = cls._implementation_names_impl(implementation, base_ring, sparse) 

if names is NotImplemented: 

raise ValueError("unknown implementation %r for %s polynomial rings over %r" % 

(implementation, "sparse" if sparse else "dense", base_ring)) 

assert isinstance(names, list) 

assert implementation in names 

return names 

 

@staticmethod 

def _implementation_names_impl(implementation, base_ring, sparse): 

""" 

The underlying implementation of :meth:`_implementation_names`. 

 

The behaviour is exactly the same, except that an unknown 

implementation returns ``NotImplemented`` instead of raising 

``ValueError``. 

 

EXAMPLES:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_general 

sage: PolynomialRing_general._implementation_names_impl("xyzzy", ZZ, True) 

NotImplemented 

""" 

if implementation is None or implementation == "generic": 

return [None, "generic"] 

return NotImplemented 

 

def is_integral_domain(self, proof = True): 

""" 

EXAMPLES:: 

 

sage: ZZ['x'].is_integral_domain() 

True 

sage: Integers(8)['x'].is_integral_domain() 

False 

""" 

return self.base_ring().is_integral_domain(proof) 

 

def is_unique_factorization_domain(self, proof = True): 

""" 

EXAMPLES:: 

 

sage: ZZ['x'].is_unique_factorization_domain() 

True 

sage: Integers(8)['x'].is_unique_factorization_domain() 

False 

""" 

return self.base_ring().is_unique_factorization_domain(proof) 

 

def is_noetherian(self): 

return self.base_ring().is_noetherian() 

 

def some_elements(self): 

r""" 

Return a list of polynomials. 

 

This is typically used for running generic tests. 

 

EXAMPLES:: 

 

sage: R.<x> = QQ[] 

sage: R.some_elements() 

[x, 0, 1, 1/2, x^2 + 2*x + 1, x^3, x^2 - 1, x^2 + 1, 2*x^2 + 2] 

""" 

# the comments in the following lines describe the motivation for 

# adding these elements, they are not accurate over all rings and in 

# all contexts 

R = self.base_ring() 

# Doing things this way is a little robust against rings where 

# 2 might not convert in 

one = R.one() 

return [self.gen(), 

self.zero(), self(one), self(R.an_element()), # elements of the base ring 

self([one,2*one,one]), # a square 

self([0,0,0,one]), # a power but not a square 

self([-one,0,one]), # a reducible element 

self([one,0,one]), # an irreducible element 

self([2*one,0,2*one]), # an element with non-trivial content 

] 

 

def construction(self): 

return categories.pushout.PolynomialFunctor(self.variable_name(), sparse=self.__is_sparse), self.base_ring() 

 

def completion(self, p, prec=20, extras=None): 

""" 

Return the completion of self with respect to the irreducible 

polynomial p. Currently only implemented for p=self.gen(), i.e. you 

can only complete R[x] with respect to x, the result being a ring 

of power series in x. The prec variable controls the precision used 

in the power series ring. 

 

EXAMPLES:: 

 

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

sage: P 

Univariate Polynomial Ring in x over Rational Field 

sage: PP=P.completion(x) 

sage: PP 

Power Series Ring in x over Rational Field 

sage: f=1-x 

sage: PP(f) 

1 - x 

sage: 1/f 

1/(-x + 1) 

sage: 1/PP(f) 

1 + x + x^2 + x^3 + x^4 + x^5 + x^6 + x^7 + x^8 + x^9 + x^10 + x^11 + x^12 + x^13 + x^14 + x^15 + x^16 + x^17 + x^18 + x^19 + O(x^20) 

""" 

if str(p) == self._names[0]: 

from sage.rings.power_series_ring import PowerSeriesRing 

return PowerSeriesRing(self.base_ring(), name=self._names[0], default_prec=prec) 

else: 

raise TypeError("Cannot complete %s with respect to %s" % (self, p)) 

 

def _coerce_map_from_(self, P): 

""" 

The rings that canonically coerce to this polynomial ring are: 

 

- this ring itself 

 

- any ring that canonically coerces to the base ring of this ring. 

 

- polynomial rings in the same variable over any base ring that 

canonically coerces to the base ring of this ring. 

 

- a multivariate polynomial ring P such that self's variable name 

is among the variable names of P, and the ring obtained by 

removing that variable is different from the base ring of self, 

but coerces into it. (see :trac:`813` for a discussion of this) 

 

Caveat: There is no coercion from a dense into a sparse 

polynomial ring. So, when adding a dense and a sparse 

polynomial, the result will be dense. See :trac:`9944`. 

 

EXAMPLES:: 

 

sage: R = QQ['x'] 

sage: R.has_coerce_map_from(QQ) 

True 

sage: R.has_coerce_map_from(ZZ) 

True 

sage: R.has_coerce_map_from(GF(7)) 

False 

sage: R.has_coerce_map_from(ZZ['x']) 

True 

sage: R.has_coerce_map_from(ZZ['y']) 

False 

 

sage: R.coerce_map_from(ZZ) 

Composite map: 

From: Integer Ring 

To: Univariate Polynomial Ring in x over Rational Field 

Defn: Natural morphism: 

From: Integer Ring 

To: Rational Field 

then 

Polynomial base injection morphism: 

From: Rational Field 

To: Univariate Polynomial Ring in x over Rational Field 

 

Here we test against the change in the coercions introduced 

in :trac:`9944`:: 

 

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

sage: S.<x> = QQ[] 

sage: (R.0+S.0).parent() 

Univariate Polynomial Ring in x over Rational Field 

sage: (S.0+R.0).parent() 

Univariate Polynomial Ring in x over Rational Field 

 

Here we test a feature that was implemented in :trac:`813`:: 

 

sage: P = QQ['x','y'] 

sage: Q = Frac(QQ['x'])['y'] 

sage: Q.has_coerce_map_from(P) 

True 

sage: P.0+Q.0 

y + x 

 

In order to avoid bidirectional coercions (which are generally 

problematic), we only have a coercion from P to Q if the base 

ring of Q is more complicated than "P minus one variable":: 

 

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

sage: P.has_coerce_map_from(Q) 

True 

sage: Q.has_coerce_map_from(P) 

False 

sage: Q.base_ring() is P.remove_var(Q.variable_name()) 

True 

 

Over the integers, there is a coercion from the NTL and generic 

implementation to the default FLINT implementation:: 

 

sage: R = PolynomialRing(ZZ, 't', implementation="NTL") 

sage: S = PolynomialRing(ZZ, 't', implementation="FLINT") 

sage: T = PolynomialRing(ZZ, 't', implementation="generic") 

sage: R.has_coerce_map_from(S) 

False 

sage: R.has_coerce_map_from(T) 

False 

sage: S.has_coerce_map_from(T) 

True 

sage: S.has_coerce_map_from(R) 

True 

sage: T.has_coerce_map_from(R) 

False 

sage: T.has_coerce_map_from(S) 

False 

""" 

# In the first place, handle the base ring 

base_ring = self.base_ring() 

if P is base_ring: 

return PolynomialBaseringInjection(base_ring, self) 

# handle constants that canonically coerce into self.base_ring() 

# first, if possible 

try: 

connecting = base_ring.coerce_map_from(P) 

if connecting is not None: 

return self.coerce_map_from(base_ring) * connecting 

except TypeError: 

pass 

 

# polynomial rings in the same variable over a base that canonically 

# coerces into self.base_ring() 

if is_PolynomialRing(P): 

if self.construction()[0] != P.construction()[0]: 

# Construction (including variable names) must be the 

# same to allow coercion 

return False 

self_sparse = self.is_sparse() 

P_sparse = P.is_sparse() 

if self_sparse and not P_sparse: 

# Coerce only sparse -> dense 

return False 

 

if P.base_ring() is base_ring: 

# Same base ring but different implementations. 

# Ideally, we should avoid cyclic coercions (a coercion 

# from A to B and also from B to A), but this is 

# currently hard to do: 

# see https://trac.sagemath.org/ticket/24319 

if not self_sparse and P_sparse: 

# Always allow coercion sparse -> dense 

pass 

elif base_ring is ZZ: 

# Over ZZ, only allow coercion from any ZZ['x'] 

# implementation to the default FLINT implementation 

if self.element_class is not Polynomial_integer_dense_flint: 

return None 

# Other rings: always allow coercion 

# To be fixed in Trac #24319 

f = base_ring.coerce_map_from(P.base_ring()) 

if f is None: 

return None 

from sage.rings.homset import RingHomset 

from sage.rings.polynomial.polynomial_ring_homomorphism import PolynomialRingHomomorphism_from_base 

return PolynomialRingHomomorphism_from_base(RingHomset(P, self), f) 

 

# Last, we consider multivariate polynomial rings: 

from sage.rings.polynomial.multi_polynomial_ring import is_MPolynomialRing 

if is_MPolynomialRing(P) and self.variable_name() in P.variable_names(): 

P_ = P.remove_var(self.variable_name()) 

return self.base_ring()!=P_ and self.base_ring().has_coerce_map_from(P_) 

 

def _magma_init_(self, magma): 

""" 

Used in converting this ring to the corresponding ring in MAGMA. 

 

EXAMPLES:: 

 

sage: R = QQ['y'] 

sage: R._magma_init_(magma) # optional - magma 

'SageCreateWithNames(PolynomialRing(_sage_ref...),["y"])' 

sage: S = magma(R) # optional - magma 

sage: S # optional - magma 

Univariate Polynomial Ring in y over Rational Field 

sage: S.1 # optional - magma 

y 

sage: magma(PolynomialRing(GF(7), 'x')) # optional - magma 

Univariate Polynomial Ring in x over GF(7) 

sage: magma(PolynomialRing(GF(49,'a'), 'x')) # optional - magma 

Univariate Polynomial Ring in x over GF(7^2) 

sage: magma(PolynomialRing(PolynomialRing(ZZ,'w'), 'x')) # optional - magma 

Univariate Polynomial Ring in x over Univariate Polynomial Ring in w over Integer Ring 

 

Watch out, Magma has different semantics from Sage, i.e., in Magma 

there is a unique univariate polynomial ring, and the variable name 

has no intrinsic meaning (it only impacts printing), so can't be 

reliably set because of caching. 

 

:: 

 

sage: m = Magma() # new magma session; optional - magma 

sage: m(QQ['w']) # optional - magma 

Univariate Polynomial Ring in w over Rational Field 

sage: m(QQ['x']) # optional - magma 

Univariate Polynomial Ring in x over Rational Field 

sage: m(QQ['w']) # same magma object, now prints as x; optional - magma 

Univariate Polynomial Ring in x over Rational Field 

 

A nested example over a Givaro finite field:: 

 

sage: k.<a> = GF(9) 

sage: R.<x> = k[] 

sage: magma(a^2*x^3 + (a+1)*x + a) # optional - magma 

a^2*x^3 + a^2*x + a 

""" 

B = magma(self.base_ring()) 

Bref = B._ref() 

s = 'PolynomialRing(%s)'%(Bref) 

return magma._with_names(s, self.variable_names()) 

 

def _gap_init_(self, gap=None): 

""" 

String for representing this polynomial ring in GAP. 

 

INPUT: 

 

- ``gap`` -- (optional GAP instance) used for representing the base ring 

 

EXAMPLES:: 

 

sage: R.<z> = ZZ[] 

sage: gap(R) 

PolynomialRing( Integers, ["z"] ) 

sage: gap(R) is gap(R) 

True 

sage: gap(z^2 + z) 

z^2+z 

 

A univariate polynomial ring over a multivariate polynomial 

ring over a number field:: 

 

sage: Q.<t> = QQ[] 

sage: K.<tau> = NumberField(t^2+t+1) 

sage: P.<x,y> = K[] 

sage: S.<z> = P[] 

sage: gap(S) 

PolynomialRing( PolynomialRing( <algebraic extension over the Rationals of degree 2>, ["x", "y"] ), ["z"] ) 

sage: gap(S) is gap(S) 

True 

""" 

if gap is not None: 

base_ring = gap(self.base_ring()).name() 

else: 

base_ring = self.base_ring()._gap_init_() 

return 'PolynomialRing(%s, ["%s"])'%(base_ring, self.variable_name()) 

 

def _sage_input_(self, sib, coerced): 

r""" 

Produce an expression which will reproduce this value when 

evaluated. 

 

EXAMPLES:: 

 

sage: sage_input(GF(5)['x']['y'], verify=True) 

# Verified 

GF(5)['x']['y'] 

sage: from sage.misc.sage_input import SageInputBuilder 

sage: ZZ['z']._sage_input_(SageInputBuilder(), False) 

{constr_parent: {subscr: {atomic:ZZ}[{atomic:'z'}]} with gens: ('z',)} 

""" 

base = sib(self.base_ring()) 

sie = base[self.variable_name()] 

gens_syntax = sib.empty_subscript(base) 

return sib.parent_with_gens(self, sie, self.variable_names(), 'R', 

gens_syntax=gens_syntax) 

 

def _macaulay2_(self, m2=None): 

""" 

EXAMPLES:: 

 

sage: R = QQ['x'] 

sage: macaulay2(R) # optional - macaulay2 

QQ[x, Degrees => {1}, Heft => {1}, MonomialOrder => {MonomialSize => 32}, DegreeRank => 1] 

{GRevLex => {1} } 

{Position => Up } 

""" 

if m2 is None: 

import sage.interfaces.macaulay2 

m2 = sage.interfaces.macaulay2.macaulay2 

base_ring = m2( self.base_ring() ) 

var = self.gen() 

return m2("%s[symbol %s]"%(base_ring.name(), var)) 

 

 

def _is_valid_homomorphism_(self, codomain, im_gens): 

try: 

# all that is needed is that elements of the base ring 

# of the polynomial ring canonically coerce into codomain. 

# Since poly rings are free, any image of the gen 

# determines a homomorphism 

codomain.coerce(self.base_ring().one()) 

except TypeError: 

return False 

return True 

 

# Polynomial rings should be unique parents. Hence, 

# no need for any comparison method 

 

def __hash__(self): 

# should be faster than just relying on the string representation 

try: 

return self._cached_hash 

except AttributeError: 

pass 

h = self._cached_hash = hash((self.base_ring(),self.variable_name())) 

return h 

 

def _repr_(self): 

try: 

return self._cached_repr 

except AttributeError: 

pass 

s = "Univariate Polynomial Ring in %s over %s"%( 

self.variable_name(), self.base_ring()) 

if self.is_sparse(): 

s = "Sparse " + s 

self._cached_repr = s 

return s 

 

def _latex_(self): 

r""" 

EXAMPLES:: 

 

sage: S.<alpha12>=ZZ[] 

sage: latex(S) 

\Bold{Z}[\alpha_{12}] 

""" 

return "%s[%s]"%(latex.latex(self.base_ring()), self.latex_variable_names()[0]) 

 

def base_extend(self, R): 

""" 

Return the base extension of this polynomial ring to R. 

 

EXAMPLES:: 

 

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

Univariate Polynomial Ring in x over Real Field with 53 bits of precision 

sage: R.base_extend(CC) 

Univariate Polynomial Ring in x over Complex Field with 53 bits of precision 

sage: R.base_extend(QQ) 

Traceback (most recent call last): 

... 

TypeError: no such base extension 

sage: R.change_ring(QQ) 

Univariate Polynomial Ring in x over Rational Field 

""" 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

 

if R.has_coerce_map_from(self.base_ring()): 

return PolynomialRing(R, names=self.variable_name(), sparse=self.is_sparse()) 

else: 

raise TypeError("no such base extension") 

 

def change_ring(self, R): 

""" 

Return the polynomial ring in the same variable as self over R. 

 

EXAMPLES:: 

 

sage: R.<ZZZ> = RealIntervalField() []; R 

Univariate Polynomial Ring in ZZZ over Real Interval Field with 53 bits of precision 

sage: R.change_ring(GF(19^2,'b')) 

Univariate Polynomial Ring in ZZZ over Finite Field in b of size 19^2 

""" 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

 

return PolynomialRing(R, names=self.variable_name(), sparse=self.is_sparse()) 

 

def change_var(self, var): 

r""" 

Return the polynomial ring in variable var over the same base 

ring. 

 

EXAMPLES:: 

 

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

Univariate Polynomial Ring in x over Integer Ring 

sage: R.change_var('y') 

Univariate Polynomial Ring in y over Integer Ring 

""" 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

 

return PolynomialRing(self.base_ring(), names = var, sparse=self.is_sparse()) 

 

def extend_variables(self, added_names, order = 'degrevlex'): 

r""" 

Returns a multivariate polynomial ring with the same base ring but 

with added_names as additional variables. 

 

EXAMPLES:: 

 

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

Univariate Polynomial Ring in x over Integer Ring 

sage: R.extend_variables('y, z') 

Multivariate Polynomial Ring in x, y, z over Integer Ring 

sage: R.extend_variables(('y', 'z')) 

Multivariate Polynomial Ring in x, y, z over Integer Ring 

""" 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

 

if isinstance(added_names, str): 

added_names = added_names.split(',') 

return PolynomialRing(self.base_ring(), names = self.variable_names() + tuple(added_names), order = order) 

 

def variable_names_recursive(self, depth=sage.rings.infinity.infinity): 

r""" 

Return the list of variable names of this ring and its base rings, 

as if it were a single multi-variate polynomial. 

 

INPUT: 

 

- ``depth`` -- an integer or :mod:`Infinity <sage.rings.infinity>`. 

 

OUTPUT: 

 

A tuple of strings. 

 

EXAMPLES:: 

 

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

sage: R.variable_names_recursive() 

('x', 'y', 'z') 

sage: R.variable_names_recursive(2) 

('y', 'z') 

""" 

if depth <= 0: 

return () 

elif depth == 1: 

return self.variable_names() 

else: 

my_vars = self.variable_names() 

try: 

return self.base_ring().variable_names_recursive(depth - len(my_vars)) + my_vars 

except AttributeError: 

return my_vars 

 

def _mpoly_base_ring(self, variables=None): 

r""" 

Returns the base ring if this is viewed as a polynomial ring over 

``variables``. See also 

Polynomial._mpoly_dict_recursive 

""" 

if variables is None: 

variables = self.variable_names_recursive() 

variables = list(variables) 

var = self.variable_name() 

if not var in variables: 

return self 

else: 

try: 

return self.base_ring()._mpoly_base_ring(variables[:variables.index(var)]) 

except AttributeError: 

return self.base_ring() 

 

def characteristic(self): 

""" 

Return the characteristic of this polynomial ring, which is the 

same as that of its base ring. 

 

EXAMPLES:: 

 

sage: R.<ZZZ> = RealIntervalField() []; R 

Univariate Polynomial Ring in ZZZ over Real Interval Field with 53 bits of precision 

sage: R.characteristic() 

0 

sage: S = R.change_ring(GF(19^2,'b')); S 

Univariate Polynomial Ring in ZZZ over Finite Field in b of size 19^2 

sage: S.characteristic() 

19 

""" 

return self.base_ring().characteristic() 

 

def cyclotomic_polynomial(self, n): 

""" 

Return the nth cyclotomic polynomial as a polynomial in this 

polynomial ring. For details of the implementation, see the 

documentation for 

:func:`sage.rings.polynomial.cyclotomic.cyclotomic_coeffs`. 

 

EXAMPLES:: 

 

sage: R = ZZ['x'] 

sage: R.cyclotomic_polynomial(8) 

x^4 + 1 

sage: R.cyclotomic_polynomial(12) 

x^4 - x^2 + 1 

sage: S = PolynomialRing(FiniteField(7), 'x') 

sage: S.cyclotomic_polynomial(12) 

x^4 + 6*x^2 + 1 

sage: S.cyclotomic_polynomial(1) 

x + 6 

 

TESTS: 

 

Make sure it agrees with other systems for the trivial case:: 

 

sage: ZZ['x'].cyclotomic_polynomial(1) 

x - 1 

sage: gp('polcyclo(1)') 

x - 1 

""" 

if n <= 0: 

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

elif n == 1: 

return self.gen() - 1 

else: 

return self(cyclotomic.cyclotomic_coeffs(n), check=True) 

 

def gen(self, n=0): 

""" 

Return the indeterminate generator of this polynomial ring. 

 

EXAMPLES:: 

 

sage: R.<abc> = Integers(8)[]; R 

Univariate Polynomial Ring in abc over Ring of integers modulo 8 

sage: t = R.gen(); t 

abc 

sage: t.is_gen() 

True 

 

An identical generator is always returned. 

 

:: 

 

sage: t is R.gen() 

True 

""" 

if n != 0: 

raise IndexError("generator n not defined") 

return self.__generator 

 

def gens_dict(self): 

""" 

Return a dictionary whose entries are ``{name:variable,...}``, 

where ``name`` stands for the variable names of this 

object (as strings) and ``variable`` stands for the corresponding 

generators (as elements of this object). 

 

EXAMPLES:: 

 

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

sage: R.gens_dict() 

{'a42': a42, 'x': x, 'y': y} 

""" 

gens = self.gens() 

names = self.variable_names() 

assert len(gens) == len(names) 

return dict(zip(names, gens)) 

 

def parameter(self): 

""" 

Return the generator of this polynomial ring. 

 

This is the same as ``self.gen()``. 

""" 

return self.gen() 

 

def is_finite(self): 

""" 

Return False since polynomial rings are not finite (unless the base 

ring is 0.) 

 

EXAMPLES:: 

 

sage: R = Integers(1)['x'] 

sage: R.is_finite() 

True 

sage: R = GF(7)['x'] 

sage: R.is_finite() 

False 

sage: R['x']['y'].is_finite() 

False 

""" 

R = self.base_ring() 

if R.is_finite() and R.order() == 1: 

return True 

return False 

 

@cached_method 

def is_exact(self): 

return self.base_ring().is_exact() 

 

def is_field(self, proof = True): 

""" 

Return False, since polynomial rings are never fields. 

 

EXAMPLES:: 

 

sage: R.<z> = Integers(2)[]; R 

Univariate Polynomial Ring in z over Ring of integers modulo 2 (using GF2X) 

sage: R.is_field() 

False 

""" 

return False 

 

def is_sparse(self): 

""" 

Return true if elements of this polynomial ring have a sparse 

representation. 

 

EXAMPLES:: 

 

sage: R.<z> = Integers(8)[]; R 

Univariate Polynomial Ring in z over Ring of integers modulo 8 

sage: R.is_sparse() 

False 

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

Sparse Univariate Polynomial Ring in W over Rational Field 

sage: R.is_sparse() 

True 

""" 

return self.__is_sparse 

 

def krull_dimension(self): 

""" 

Return the Krull dimension of this polynomial ring, which is one 

more than the Krull dimension of the base ring. 

 

EXAMPLES:: 

 

sage: R.<x> = QQ[] 

sage: R.krull_dimension() 

1 

sage: R.<z> = GF(9,'a')[]; R 

Univariate Polynomial Ring in z over Finite Field in a of size 3^2 

sage: R.krull_dimension() 

1 

sage: S.<t> = R[] 

sage: S.krull_dimension() 

2 

sage: for n in range(10): 

....: S = PolynomialRing(S,'w') 

sage: S.krull_dimension() 

12 

""" 

return self.base_ring().krull_dimension() + 1 

 

def ngens(self): 

""" 

Return the number of generators of this polynomial ring, which is 1 

since it is a univariate polynomial ring. 

 

EXAMPLES:: 

 

sage: R.<z> = Integers(8)[]; R 

Univariate Polynomial Ring in z over Ring of integers modulo 8 

sage: R.ngens() 

1 

""" 

return 1 

 

def random_element(self, degree=(-1,2), *args, **kwds): 

r""" 

Return a random polynomial of given degree or with given degree bounds. 

 

INPUT: 

 

- ``degree`` - optional integer for fixing the degree or 

or a tuple of minimum and maximum degrees. By default set to 

``(-1,2)``. 

 

- ``*args, **kwds`` - Passed on to the ``random_element`` method for 

the base ring 

 

EXAMPLES:: 

 

sage: R.<x> = ZZ[] 

sage: R.random_element(10, 5,10) 

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

sage: R.random_element(6) 

x^6 - 3*x^5 - x^4 + x^3 - x^2 + x + 1 

sage: R.random_element(6) 

-2*x^6 - 2*x^5 + 2*x^4 - 3*x^3 + 1 

sage: R.random_element(6) 

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

 

If a tuple of two integers is given for the degree argument, a 

polynomial of degree in between the bound is given:: 

 

sage: R.random_element(degree=(0,8)) 

x^8 + 4*x^7 + 2*x^6 - x^4 + 4*x^3 - 5*x^2 + x + 14 

sage: R.random_element(degree=(0,8)) 

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

 

Note that the zero polynomial has degree ``-1``, so if you want to 

consider it set the minimum degree to ``-1``:: 

 

sage: any(R.random_element(degree=(-1,2),x=-1,y=1) == R.zero() for _ in range(100)) 

True 

 

TESTS:: 

 

sage: R.random_element(degree=[5]) 

Traceback (most recent call last): 

... 

ValueError: degree argument must be an integer or a tuple of 2 integers (min_degree, max_degree) 

 

sage: R.random_element(degree=(5,4)) 

Traceback (most recent call last): 

... 

ValueError: minimum degree must be less or equal than maximum degree 

 

Check that :trac:`16682` is fixed:: 

 

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

sage: for _ in range(100): 

....: d = randint(-1,20) 

....: P = R.random_element(degree=d) 

....: assert P.degree() == d, "problem with {} which has not degree {}".format(P,d) 

 

sage: R.random_element(degree=-2) 

Traceback (most recent call last): 

... 

ValueError: degree should be an integer greater or equal than -1 

""" 

R = self.base_ring() 

 

if isinstance(degree, (list, tuple)): 

if len(degree) != 2: 

raise ValueError("degree argument must be an integer or a tuple of 2 integers (min_degree, max_degree)") 

if degree[0] > degree[1]: 

raise ValueError("minimum degree must be less or equal than maximum degree") 

else: 

degree = (degree,degree) 

 

if degree[0] <= -2: 

raise ValueError("degree should be an integer greater or equal than -1") 

 

p = self([R.random_element(*args,**kwds) for _ in range(degree[1]+1)]) 

 

if p.degree() < degree[0]: 

p += R._random_nonzero_element() * self.gen()**randint(degree[0],degree[1]) 

 

return p 

 

def _monics_degree( self, of_degree ): 

""" 

Refer to monics() for full documentation. 

""" 

base = self.base_ring() 

for coeffs in sage.misc.mrange.xmrange_iter([[base.one()]]+[base]*of_degree): 

# Each iteration returns a *new* list! 

# safe to mutate the return 

coeffs.reverse() 

yield self(coeffs) 

 

def _monics_max( self, max_degree ): 

""" 

Refer to monics() for full documentation. 

""" 

for degree in range(max_degree + 1): 

for m in self._monics_degree( degree ): 

yield m 

 

def _polys_degree( self, of_degree ): 

""" 

Refer to polynomials() for full documentation. 

""" 

base = self.base_ring() 

base0 = base.zero() 

for leading_coeff in base: 

if leading_coeff != base0: 

for lt1 in sage.misc.mrange.xmrange_iter([base]*(of_degree)): 

# Each iteration returns a *new* list! 

# safe to mutate the return 

coeffs = [leading_coeff] + lt1 

coeffs.reverse() 

yield self(coeffs) 

 

def _polys_max( self, max_degree ): 

""" 

Refer to polynomials() for full documentation. 

""" 

base = self.base_ring() 

for coeffs in sage.misc.mrange.xmrange_iter([base]*(max_degree+1)): 

# Each iteration returns a *new* list! 

# safe to mutate the return 

coeffs.reverse() 

yield self(coeffs) 

 

@lazy_attribute 

def _Karatsuba_threshold(self): 

""" 

Return the default Karatsuba threshold. 

 

EXAMPLES:: 

 

sage: R.<x> = QQbar[] 

sage: R._Karatsuba_threshold 

8 

sage: MS = MatrixSpace(ZZ, 2, 2) 

sage: R.<x> = MS[] 

sage: R._Karatsuba_threshold 

0 

""" 

base_ring = self.base_ring() 

if is_PolynomialRing(base_ring): 

return 0 

from sage.matrix.matrix_space import MatrixSpace 

if isinstance(base_ring, MatrixSpace): 

return 0 

# Generic default value 

return 8 

 

def karatsuba_threshold(self): 

""" 

Return the Karatsuba threshold used for this ring by the method 

_mul_karatsuba to fall back to the schoolbook algorithm. 

 

EXAMPLES:: 

 

sage: K = QQ['x'] 

sage: K.karatsuba_threshold() 

8 

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

sage: K.karatsuba_threshold() 

0 

""" 

return self._Karatsuba_threshold 

 

def set_karatsuba_threshold(self, Karatsuba_threshold): 

""" 

Changes the default threshold for this ring in the method _mul_karatsuba 

to fall back to the schoolbook algorithm. 

 

.. warning:: 

 

This method may have a negative performance impact in polynomial 

arithmetic. So use it at your own risk. 

 

EXAMPLES:: 

 

sage: K = QQ['x'] 

sage: K.karatsuba_threshold() 

8 

sage: K.set_karatsuba_threshold(0) 

sage: K.karatsuba_threshold() 

0 

""" 

self._Karatsuba_threshold = int(Karatsuba_threshold) 

 

def polynomials( self, of_degree = None, max_degree = None ): 

""" 

Return an iterator over the polynomials of specified degree. 

 

INPUT: Pass exactly one of: 

 

 

- ``max_degree`` - an int; the iterator will generate 

all polynomials which have degree less than or equal to 

max_degree 

 

- ``of_degree`` - an int; the iterator will generate 

all polynomials which have degree of_degree 

 

 

OUTPUT: an iterator 

 

EXAMPLES:: 

 

sage: P = PolynomialRing(GF(3),'y') 

sage: for p in P.polynomials( of_degree = 2 ): print(p) 

y^2 

y^2 + 1 

y^2 + 2 

y^2 + y 

y^2 + y + 1 

y^2 + y + 2 

y^2 + 2*y 

y^2 + 2*y + 1 

y^2 + 2*y + 2 

2*y^2 

2*y^2 + 1 

2*y^2 + 2 

2*y^2 + y 

2*y^2 + y + 1 

2*y^2 + y + 2 

2*y^2 + 2*y 

2*y^2 + 2*y + 1 

2*y^2 + 2*y + 2 

sage: for p in P.polynomials( max_degree = 1 ): print(p) 

0 

1 

2 

y 

y + 1 

y + 2 

2*y 

2*y + 1 

2*y + 2 

sage: for p in P.polynomials( max_degree = 1, of_degree = 3 ): print(p) 

Traceback (most recent call last): 

... 

ValueError: you should pass exactly one of of_degree and max_degree 

 

AUTHORS: 

 

- Joel B. Mohler 

""" 

 

if self.base_ring().order() is sage.rings.infinity.infinity: 

raise NotImplementedError 

if of_degree is not None and max_degree is None: 

return self._polys_degree( of_degree ) 

if max_degree is not None and of_degree is None: 

return self._polys_max( max_degree ) 

raise ValueError("you should pass exactly one of of_degree and max_degree") 

 

def monics( self, of_degree = None, max_degree = None ): 

""" 

Return an iterator over the monic polynomials of specified degree. 

 

INPUT: Pass exactly one of: 

 

 

- ``max_degree`` - an int; the iterator will generate 

all monic polynomials which have degree less than or equal to 

max_degree 

 

- ``of_degree`` - an int; the iterator will generate 

all monic polynomials which have degree of_degree 

 

 

OUTPUT: an iterator 

 

EXAMPLES:: 

 

sage: P = PolynomialRing(GF(4,'a'),'y') 

sage: for p in P.monics( of_degree = 2 ): print(p) 

y^2 

y^2 + a 

y^2 + a + 1 

y^2 + 1 

y^2 + a*y 

y^2 + a*y + a 

y^2 + a*y + a + 1 

y^2 + a*y + 1 

y^2 + (a + 1)*y 

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

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

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

y^2 + y 

y^2 + y + a 

y^2 + y + a + 1 

y^2 + y + 1 

sage: for p in P.monics( max_degree = 1 ): print(p) 

1 

y 

y + a 

y + a + 1 

y + 1 

sage: for p in P.monics( max_degree = 1, of_degree = 3 ): print(p) 

Traceback (most recent call last): 

... 

ValueError: you should pass exactly one of of_degree and max_degree 

 

AUTHORS: 

 

- Joel B. Mohler 

""" 

 

if self.base_ring().order() is sage.rings.infinity.infinity: 

raise NotImplementedError 

if of_degree is not None and max_degree is None: 

return self._monics_degree( of_degree ) 

if max_degree is not None and of_degree is None: 

return self._monics_max( max_degree ) 

raise ValueError("you should pass exactly one of of_degree and max_degree") 

 

 

class PolynomialRing_commutative(PolynomialRing_general, commutative_algebra.CommutativeAlgebra): 

""" 

Univariate polynomial ring over a commutative ring. 

""" 

def __init__(self, base_ring, name=None, sparse=False, element_class=None, category=None): 

if base_ring not in _CommutativeRings: 

raise TypeError("Base ring %s must be a commutative ring."%repr(base_ring)) 

# We trust that, if a category is given, that it is useful. 

if category is None: 

if base_ring.is_zero(): 

category = categories.rings.Rings().Finite() 

else: 

category = polynomial_default_category(base_ring.category(), 1) 

PolynomialRing_general.__init__(self, base_ring, name=name, 

sparse=sparse, element_class=element_class, category=category) 

 

def quotient_by_principal_ideal(self, f, names=None): 

""" 

Return the quotient of this polynomial ring by the principal 

ideal (generated by) `f`. 

 

INPUT: 

 

- ``f`` - either a polynomial in ``self``, or a principal 

ideal of ``self``. 

 

EXAMPLES:: 

 

sage: R.<x> = QQ[] 

sage: I = (x^2-1)*R 

sage: R.quotient_by_principal_ideal(I) 

Univariate Quotient Polynomial Ring in xbar over Rational Field with modulus x^2 - 1 

 

The same example, using the polynomial instead of the ideal, 

and customizing the variable name:: 

 

sage: R.<x> = QQ[] 

sage: R.quotient_by_principal_ideal(x^2-1, names=('foo',)) 

Univariate Quotient Polynomial Ring in foo over Rational Field with modulus x^2 - 1 

 

TESTS: 

 

Quotienting by the zero ideal returns ``self`` (:trac:`5978`):: 

 

sage: R = QQ['x'] 

sage: R.quotient_by_principal_ideal(R.zero_ideal()) is R 

True 

sage: R.quotient_by_principal_ideal(0) is R 

True 

""" 

from sage.rings.ideal import Ideal 

I = Ideal(f) 

if I.is_zero(): 

return self 

f = I.gen() 

from sage.rings.polynomial.polynomial_quotient_ring import PolynomialQuotientRing 

return PolynomialQuotientRing(self, f, names) 

 

def weyl_algebra(self): 

""" 

Return the Weyl algebra generated from ``self``. 

 

EXAMPLES:: 

 

sage: R = QQ['x'] 

sage: W = R.weyl_algebra(); W 

Differential Weyl algebra of polynomials in x over Rational Field 

sage: W.polynomial_ring() == R 

True 

""" 

from sage.algebras.weyl_algebra import DifferentialWeylAlgebra 

return DifferentialWeylAlgebra(self) 

 

def _roots_univariate_polynomial(self, p, ring=None, multiplicities=True, algorithm=None, degree_bound=None): 

""" 

Return the list of roots of ``p``. 

 

INPUT: 

 

- ``p`` -- the polynomial whose roots are computed 

- ``ring`` -- the ring to find roots (default is the base ring of ``p``) 

- ``multiplicities`` -- bool (default: True): if ``True``, return a list of pairs ``(root, multiplicity)``; if ``False`` return a list of roots 

- ``algorithm`` -- ignored (TODO: remove) 

- ``degree_bound``-- if not ``None``, return only roots of degree at most ``degree_bound`` 

 

EXAMPLES:: 

 

sage: R.<x> = QQ[] 

sage: S.<y> = R[] 

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

sage: p.roots() 

[(x^2 - 2*x + 1, 1), (x + 1, 2)] 

sage: p.roots(multiplicities=False) 

[x^2 - 2*x + 1, x + 1] 

sage: p.roots(degree_bound=1) 

[(x + 1, 2)] 

""" 

if ring is not None and ring is not self: 

p = p.change_ring(ring) 

return p.roots(multiplicities, algorithm, degree_bound) 

roots = p._roots_from_factorization(p.factor(), multiplicities) 

if degree_bound is not None: 

if multiplicities: 

roots = [(r,m) for (r,m) in roots if r.degree() <= degree_bound] 

else: 

roots = [r for r in roots if r.degree() <= degree_bound] 

return roots 

 

 

class PolynomialRing_integral_domain(PolynomialRing_commutative, ring.IntegralDomain): 

def __init__(self, base_ring, name="x", sparse=False, implementation=None, 

element_class=None, category=None): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_integral_domain as PRing 

sage: R = PRing(ZZ, 'x'); R 

Univariate Polynomial Ring in x over Integer Ring 

sage: type(R.gen()) 

<type 'sage.rings.polynomial.polynomial_integer_dense_flint.Polynomial_integer_dense_flint'> 

 

sage: R = PRing(ZZ, 'x', implementation='NTL'); R 

Univariate Polynomial Ring in x over Integer Ring (using NTL) 

sage: type(R.gen()) 

<type 'sage.rings.polynomial.polynomial_integer_dense_ntl.Polynomial_integer_dense_ntl'> 

""" 

self._implementation_repr = '' 

if element_class is None: 

implementation = self._implementation_names(implementation, base_ring, sparse)[0] 

if base_ring is ZZ: 

if implementation == 'NTL': 

from sage.rings.polynomial.polynomial_integer_dense_ntl \ 

import Polynomial_integer_dense_ntl as element_class 

self._implementation_repr = ' (using NTL)' 

elif implementation == 'FLINT': 

element_class = Polynomial_integer_dense_flint 

PolynomialRing_commutative.__init__(self, base_ring, name=name, 

sparse=sparse, element_class=element_class, category=category) 

 

@staticmethod 

def _implementation_names_impl(implementation, base_ring, sparse): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_integral_domain 

sage: PolynomialRing_integral_domain._implementation_names_impl(None, ZZ, False) 

['FLINT', None] 

sage: PolynomialRing_integral_domain._implementation_names_impl(None, ZZ, True) 

[None, 'generic'] 

sage: PolynomialRing_integral_domain._implementation_names_impl(None, QQ, False) 

[None, 'generic'] 

sage: PolynomialRing_integral_domain._implementation_names_impl(None, QQ, True) 

[None, 'generic'] 

""" 

if base_ring is ZZ and not sparse: 

defaults = ["FLINT", None] 

if implementation in defaults: 

return defaults 

elif implementation in ["NTL", "generic"]: 

return [implementation] 

elif implementation is None or implementation == "generic": 

return [None, "generic"] 

return NotImplemented 

 

def _repr_(self): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_integral_domain as PRing 

sage: R = PRing(ZZ, 'x', implementation='NTL'); R 

Univariate Polynomial Ring in x over Integer Ring (using NTL) 

""" 

s = PolynomialRing_commutative._repr_(self) 

return s + self._implementation_repr 

 

 

class PolynomialRing_field(PolynomialRing_integral_domain, 

PolynomialRing_singular_repr, 

ring.PrincipalIdealDomain): 

def __init__(self, base_ring, name="x", sparse=False, element_class=None, category=None): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_field as PRing 

sage: R = PRing(QQ, 'x'); R 

Univariate Polynomial Ring in x over Rational Field 

sage: type(R.gen()) 

<type 'sage.rings.polynomial.polynomial_rational_flint.Polynomial_rational_flint'> 

sage: R = PRing(QQ, 'x', sparse=True); R 

Sparse Univariate Polynomial Ring in x over Rational Field 

sage: type(R.gen()) 

<class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_field_with_category.element_class'> 

sage: R = PRing(CC, 'x'); R 

Univariate Polynomial Ring in x over Complex Field with 53 bits of precision 

sage: type(R.gen()) 

<class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_field_with_category.element_class'> 

 

Demonstrate that :trac:`8762` is fixed:: 

 

sage: R.<x> = PolynomialRing(GF(next_prime(10^20)), sparse=True) 

sage: x^(10^20) # this should be fast 

x^100000000000000000000 

""" 

from sage.rings.polynomial.polynomial_singular_interface import can_convert_to_singular 

import sage.rings.complex_arb 

 

if not element_class: 

if sparse: 

element_class = polynomial_element_generic.Polynomial_generic_sparse_field 

elif isinstance(base_ring, rational_field.RationalField): 

from sage.rings.polynomial.polynomial_rational_flint import Polynomial_rational_flint 

element_class = Polynomial_rational_flint 

elif is_NumberField(base_ring): 

if base_ring.is_absolute(): 

from sage.rings.polynomial.polynomial_number_field import Polynomial_absolute_number_field_dense 

element_class = Polynomial_absolute_number_field_dense 

else: 

from sage.rings.polynomial.polynomial_number_field import Polynomial_relative_number_field_dense 

element_class = Polynomial_relative_number_field_dense 

elif is_RealField(base_ring): 

element_class = PolynomialRealDense 

elif isinstance(base_ring, sage.rings.complex_arb.ComplexBallField): 

from sage.rings.polynomial.polynomial_complex_arb import Polynomial_complex_arb 

element_class = Polynomial_complex_arb 

else: 

element_class = polynomial_element_generic.Polynomial_generic_dense_field 

 

PolynomialRing_integral_domain.__init__(self, base_ring, name=name, sparse=sparse, element_class=element_class, category=category) 

 

self._has_singular = can_convert_to_singular(self) 

 

def _ideal_class_(self, n=0): 

""" 

Returns the class representing ideals in univariate polynomial rings over fields. 

 

EXAMPLES:: 

 

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

sage: R._ideal_class_() 

<class 'sage.rings.polynomial.ideal.Ideal_1poly_field'> 

""" 

from sage.rings.polynomial.ideal import Ideal_1poly_field 

return Ideal_1poly_field 

 

def divided_difference(self, points, full_table=False): 

r""" 

Return the Newton divided-difference coefficients of the 

Lagrange interpolation polynomial through ``points``. 

 

INPUT: 

 

- ``points`` -- a list of pairs `(x_0, y_0), (x_1, y_1), 

\dots, (x_n, y_n)` of elements of the base ring of ``self``, 

where `x_i - x_j` is invertible for `i \neq j`. This method 

converts the `x_i` and `y_i` into the base ring of `self`. 

 

- ``full_table`` -- boolean (default: ``False``): If ``True``, 

return the full divided-difference table. If ``False``, 

only return entries along the main diagonal; these are the 

Newton divided-difference coefficients `F_{i,i}`. 

 

OUTPUT: 

 

The Newton divided-difference coefficients of the `n`-th 

Lagrange interpolation polynomial `P_n(x)` that passes through 

the points in ``points`` (see :meth:`lagrange_polynomial`). 

These are the coefficients `F_{0,0}, F_{1,1}, \dots, `F_{n,n}` 

in the base ring of ``self`` such that 

 

.. MATH:: 

 

P_n(x) = \sum_{i=0}^n F_{i,i} \prod_{j=0}^{i-1} (x - x_j) 

 

EXAMPLES: 

 

Only return the divided-difference coefficients `F_{i,i}`. 

This example is taken from Example 1, page 121 of [BF05]_:: 

 

sage: points = [(1.0, 0.7651977), (1.3, 0.6200860), (1.6, 0.4554022), (1.9, 0.2818186), (2.2, 0.1103623)] 

sage: R = PolynomialRing(RR, "x") 

sage: R.divided_difference(points) 

[0.765197700000000, 

-0.483705666666666, 

-0.108733888888889, 

0.0658783950617283, 

0.00182510288066044] 

 

Now return the full divided-difference table:: 

 

sage: points = [(1.0, 0.7651977), (1.3, 0.6200860), (1.6, 0.4554022), (1.9, 0.2818186), (2.2, 0.1103623)] 

sage: R = PolynomialRing(RR, "x") 

sage: R.divided_difference(points, full_table=True) 

[[0.765197700000000], 

[0.620086000000000, -0.483705666666666], 

[0.455402200000000, -0.548946000000000, -0.108733888888889], 

[0.281818600000000, 

-0.578612000000000, 

-0.0494433333333339, 

0.0658783950617283], 

[0.110362300000000, 

-0.571520999999999, 

0.0118183333333349, 

0.0680685185185209, 

0.00182510288066044]] 

 

The following example is taken from Example 4.12, page 225 of 

[MF99]_:: 

 

sage: points = [(1, -3), (2, 0), (3, 15), (4, 48), (5, 105), (6, 192)] 

sage: R = PolynomialRing(QQ, "x") 

sage: R.divided_difference(points) 

[-3, 3, 6, 1, 0, 0] 

sage: R.divided_difference(points, full_table=True) 

[[-3], 

[0, 3], 

[15, 15, 6], 

[48, 33, 9, 1], 

[105, 57, 12, 1, 0], 

[192, 87, 15, 1, 0, 0]] 

 

REFERENCES: 

 

.. [MF99] \J.H. Mathews and K.D. Fink. *Numerical Methods Using 

MATLAB*. 3rd edition, Prentice-Hall, 1999. 

 

""" 

to_base_ring = self.base_ring() 

points = [map(to_base_ring, x) for x in points] 

n = len(points) 

F = [[points[i][1]] for i in range(n)] 

for i in range(1, n): 

for j in range(1, i+1): 

numer = F[i][j-1] - F[i-1][j-1] 

denom = points[i][0] - points[i-j][0] 

F[i].append(numer / denom) 

if full_table: 

return F 

else: 

return [F[i][i] for i in range(n)] 

 

def lagrange_polynomial(self, points, algorithm="divided_difference", previous_row=None): 

r""" 

Return the Lagrange interpolation polynomial through the 

given points. 

 

INPUT: 

 

- ``points`` -- a list of pairs `(x_0, y_0), (x_1, y_1), 

\dots, (x_n, y_n)` of elements of the base ring of ``self``, 

where `x_i - x_j` is invertible for `i \neq j`. This method 

converts the `x_i` and `y_i` into the base ring of `self`. 

 

- ``algorithm`` -- (default: ``'divided_difference'``): one of 

the following: 

 

- ``'divided_difference'``: use the method of divided 

differences. 

 

- ``algorithm='neville'``: adapt Neville's method as 

described on page 144 of [BF05]_ to recursively generate 

the Lagrange interpolation polynomial. Neville's method 

generates a table of approximating polynomials, where the 

last row of that table contains the `n`-th Lagrange 

interpolation polynomial. The adaptation implemented by 

this method is to only generate the last row of this 

table, instead of the full table itself. Generating the 

full table can be memory inefficient. 

 

- ``previous_row`` -- (default: ``None``): This option is only 

relevant if used with ``algorithm='neville'``. If provided, 

this should be the last row of the table resulting from a 

previous use of Neville's method. If such a row is passed, 

then ``points`` should consist of both previous and new 

interpolating points. Neville's method will then use that 

last row and the interpolating points to generate a new row 

containing an interpolation polynomial for the new points. 

 

OUTPUT: 

 

The Lagrange interpolation polynomial through the points 

`(x_0, y_0), (x_1, y_1), \dots, (x_n, y_n)`. This is the 

unique polynomial `P_n` of degree at most `n` in ``self`` 

satisfying `P_n(x_i) = y_i` for `0 \le i \le n`. 

 

EXAMPLES: 

 

By default, we use the method of divided differences:: 

 

sage: R = PolynomialRing(QQ, 'x') 

sage: f = R.lagrange_polynomial([(0,1),(2,2),(3,-2),(-4,9)]); f 

-23/84*x^3 - 11/84*x^2 + 13/7*x + 1 

sage: f(0) 

1 

sage: f(2) 

2 

sage: f(3) 

-2 

sage: f(-4) 

9 

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

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

sage: f = R.lagrange_polynomial([(a^2+a,a),(a,1),(a^2,a^2+a+1)]); f 

a^2*x^2 + a^2*x + a^2 

sage: f(a^2+a) 

a 

sage: f(a) 

1 

sage: f(a^2) 

a^2 + a + 1 

 

Now use a memory efficient version of Neville's method:: 

 

sage: R = PolynomialRing(QQ, 'x') 

sage: R.lagrange_polynomial([(0,1),(2,2),(3,-2),(-4,9)], algorithm="neville") 

[9, 

-11/7*x + 19/7, 

-17/42*x^2 - 83/42*x + 53/7, 

-23/84*x^3 - 11/84*x^2 + 13/7*x + 1] 

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

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

sage: R.lagrange_polynomial([(a^2+a,a),(a,1),(a^2,a^2+a+1)], algorithm="neville") 

[a^2 + a + 1, x + a + 1, a^2*x^2 + a^2*x + a^2] 

 

Repeated use of Neville's method to get better Lagrange 

interpolation polynomials:: 

 

sage: R = PolynomialRing(QQ, 'x') 

sage: p = R.lagrange_polynomial([(0,1),(2,2)], algorithm="neville") 

sage: R.lagrange_polynomial([(0,1),(2,2),(3,-2),(-4,9)], algorithm="neville", previous_row=p)[-1] 

-23/84*x^3 - 11/84*x^2 + 13/7*x + 1 

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

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

sage: p = R.lagrange_polynomial([(a^2+a,a),(a,1)], algorithm="neville") 

sage: R.lagrange_polynomial([(a^2+a,a),(a,1),(a^2,a^2+a+1)], algorithm="neville", previous_row=p)[-1] 

a^2*x^2 + a^2*x + a^2 

 

TESTS: 

 

The value for ``algorithm`` must be either 

``'divided_difference'`` (default), or ``'neville'``:: 

 

sage: R = PolynomialRing(QQ, "x") 

sage: R.lagrange_polynomial([(0,1),(2,2),(3,-2),(-4,9)], algorithm="abc") 

Traceback (most recent call last): 

... 

ValueError: algorithm must be one of 'divided_difference' or 'neville' 

sage: R.lagrange_polynomial([(0,1),(2,2),(3,-2),(-4,9)], algorithm="divided difference") 

Traceback (most recent call last): 

... 

ValueError: algorithm must be one of 'divided_difference' or 'neville' 

sage: R.lagrange_polynomial([(0,1),(2,2),(3,-2),(-4,9)], algorithm="") 

Traceback (most recent call last): 

... 

ValueError: algorithm must be one of 'divided_difference' or 'neville' 

 

Make sure that :trac:`10304` is fixed. The return value 

should always be an element of ``self`` in the case of 

``divided_difference``, or a list of elements of ``self`` in 

the case of ``neville``:: 

 

sage: R = PolynomialRing(QQ, "x") 

sage: R.lagrange_polynomial([]).parent() == R 

True 

sage: R.lagrange_polynomial([(2, 3)]).parent() == R 

True 

sage: row = R.lagrange_polynomial([], algorithm='neville') 

sage: all(poly.parent() == R for poly in row) 

True 

sage: row = R.lagrange_polynomial([(2, 3)], algorithm='neville') 

sage: all(poly.parent() == R for poly in row) 

True 

 

Check that base fields of positive characteristic are treated 

correctly (see :trac:`9787`):: 

 

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

sage: R.lagrange_polynomial([[1, 0], [2, 0]]) 

0 

sage: R.lagrange_polynomial([[1, 0], [2, 0], [3, 0]]) 

0 

 

REFERENCES: 

 

.. [BF05] \R.L. Burden and J.D. Faires. *Numerical Analysis*. 

8th edition, Thomson Brooks/Cole, 2005. 

 

""" 

# Perhaps we should be slightly stricter on the input and use 

# self.base_ring().coerce here and in the divided_difference() 

# method above. However, this breaks an example in 

# sage.tests.french_book.nonlinear_doctest where the base ring 

# is CC, but the function values lie in the symbolic ring. 

to_base_ring = self.base_ring() 

points = [[to_base_ring(u) for u in x] for x in points] 

var = self.gen() 

 

# use the method of divided-difference 

if algorithm == "divided_difference": 

# Evaluate in nested form, similar to Horner's method. This is 

# more efficient than evaluation using the definition of 

# Lagrange interpolation polynomial by means of divided 

# difference. 

n = len(points) 

if n == 0: 

return self.zero() 

 

F = self.divided_difference(points) 

P = self.coerce(F[n-1]) 

for i in range(n-2, -1, -1): 

P *= (var - points[i][0]) 

P += F[i] 

return P 

 

# Evaluate using the definition of Lagrange interpolation 

# polynomial by means of divided difference. This is slow 

# compared to that above, which is in nested form. 

# P = 0 

# for i in range(n): 

# prod = 1 

# for j in range(i): 

# prod *= (var - points[j][0]) 

# P += (F[i] * prod) 

# return P 

 

# using Neville's method for recursively generating the 

# Lagrange interpolation polynomial 

elif algorithm == "neville": 

if previous_row is None: 

previous_row = [] 

N = len(points) 

M = len(previous_row) 

# During the computation, P keeps track of the previous row, 

# and Q keeps track of the current row 

P = previous_row + [None] * (N - M) # use results of previous computation if available 

Q = [None] * N 

for i in range(M, N): 

Q[0] = self.coerce(points[i][1]) # start populating the current row 

for j in range(1, 1 + i): 

numer = (var - points[i - j][0]) * Q[j - 1] - (var - points[i][0]) * P[j - 1] 

denom = points[i][0] - points[i - j][0] 

Q[j] = numer / denom 

P, Q = Q, P # the current row is complete, reuse the old P to hold the next row 

return P # return the last row in the Neville table 

 

# # use the definition of Lagrange interpolation polynomial 

# elif algorithm == "definition": 

# def Pj(j): 

# denom = 1 

# divis = 1 

# for i in range(len(points)): 

# if i!=j: 

# denom *= (var - points[i][0]) 

# divis *= (points[j][0] - points[i][0]) 

# return denom/divis 

# 

# P = 0 

# for j in range(len(points)): 

# P += Pj(j)*points[j][1] 

# return P 

 

else: 

raise ValueError("algorithm must be one of 'divided_difference' or 'neville'") 

 

def fraction_field(self): 

""" 

Returns the fraction field of self. 

 

EXAMPLES:: 

 

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

sage: R.fraction_field() 

Fraction Field of Univariate Polynomial Ring in t over Finite Field of size 5 

""" 

try: 

return self._fraction_field 

except AttributeError: 

R = self.base_ring() 

p = R.characteristic() 

if p != 0 and R.is_prime_field() and 2 < p and p < 2**16: 

from sage.rings.fraction_field_FpT import FpT 

self._fraction_field = FpT(self) 

else: 

from sage.rings.fraction_field import FractionField_1poly_field 

self._fraction_field = FractionField_1poly_field(self) 

return self._fraction_field 

 

 

class PolynomialRing_dense_finite_field(PolynomialRing_field): 

""" 

Univariate polynomial ring over a finite field. 

 

EXAMPLES:: 

 

sage: R = PolynomialRing(GF(27, 'a'), 'x') 

sage: type(R) 

<class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_dense_finite_field_with_category'> 

""" 

def __init__(self, base_ring, name="x", element_class=None, implementation=None): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_finite_field 

sage: R = PolynomialRing_dense_finite_field(GF(5), implementation='generic') 

sage: type(R(0)) 

<class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_dense_finite_field_with_category.element_class'> 

 

sage: S = PolynomialRing_dense_finite_field(GF(25, 'a'), implementation='NTL') 

sage: type(S(0)) 

<type 'sage.rings.polynomial.polynomial_zz_pex.Polynomial_ZZ_pEX'> 

 

sage: S = PolynomialRing_dense_finite_field(GF(64), implementation='superfast') 

Traceback (most recent call last): 

... 

ValueError: unknown implementation 'superfast' for dense polynomial rings over Finite Field in z6 of size 2^6 

""" 

implementation = self._implementation_names(implementation, base_ring)[0] 

if implementation == "NTL": 

from sage.libs.ntl.ntl_ZZ_pEContext import ntl_ZZ_pEContext 

from sage.libs.ntl.ntl_ZZ_pX import ntl_ZZ_pX 

from sage.rings.polynomial.polynomial_zz_pex import Polynomial_ZZ_pEX 

 

p = base_ring.characteristic() 

self._modulus = ntl_ZZ_pEContext(ntl_ZZ_pX(list(base_ring.modulus()), p)) 

element_class = Polynomial_ZZ_pEX 

PolynomialRing_field.__init__(self, base_ring, sparse=False, name=name, 

element_class=element_class) 

 

@staticmethod 

def _implementation_names_impl(implementation, base_ring, sparse): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_finite_field 

sage: PolynomialRing_dense_finite_field._implementation_names_impl("NTL", GF(4), False) 

['NTL', None] 

sage: PolynomialRing_dense_finite_field._implementation_names_impl(None, GF(4), False) 

['NTL', None] 

sage: PolynomialRing_dense_finite_field._implementation_names_impl("generic", GF(4), False) 

['generic'] 

sage: PolynomialRing_dense_finite_field._implementation_names_impl("FLINT", GF(4), False) 

NotImplemented 

sage: PolynomialRing_dense_finite_field._implementation_names_impl(None, GF(4), True) 

NotImplemented 

""" 

if sparse: 

return NotImplemented 

defaults = ["NTL", None] 

if implementation in defaults: 

return defaults 

elif implementation == "generic": 

return [implementation] 

return NotImplemented 

 

def irreducible_element(self, n, algorithm=None): 

""" 

Construct a monic irreducible polynomial of degree `n`. 

 

INPUT: 

 

- ``n`` -- integer: degree of the polynomial to construct 

 

- ``algorithm`` -- string: algorithm to use, or ``None`` 

 

- ``'random'``: try random polynomials until an irreducible 

one is found. 

 

- ``'first_lexicographic'``: try polynomials in 

lexicographic order until an irreducible one is found. 

 

OUTPUT: 

 

A monic irreducible polynomial of degree `n` in ``self``. 

 

EXAMPLES:: 

 

sage: GF(5^3, 'a')['x'].irreducible_element(2) 

x^2 + (4*a^2 + a + 4)*x + 2*a^2 + 2 

sage: GF(19)['x'].irreducible_element(21, algorithm="first_lexicographic") 

x^21 + x + 5 

sage: GF(5**2, 'a')['x'].irreducible_element(17, algorithm="first_lexicographic") 

x^17 + a*x + 4*a + 3 

 

AUTHORS: 

 

- Peter Bruin (June 2013) 

- Jean-Pierre Flori (May 2014) 

""" 

if n < 1: 

raise ValueError("degree must be at least 1") 

 

if algorithm is None: 

algorithm = "random" 

 

if algorithm == "random": 

while True: 

f = self.gen()**n + self.random_element(degree=(0, n - 1)) 

if f.is_irreducible(): 

return f 

elif algorithm == "first_lexicographic": 

for g in self.polynomials(max_degree=n-1): 

f = self.gen()**n + g 

if f.is_irreducible(): 

return f 

else: 

raise ValueError("no such algorithm for finding an irreducible polynomial: %s" % algorithm) 

 

def _roth_ruckenstein(self, p, degree_bound, precision): 

r""" 

Return all polynomials which are a solution to the, possibly modular, 

root-finding problem. 

 

This is the core of Roth-Ruckenstein's algorithm where all conversions, 

checks and parent-extraction have been done. 

 

INPUT: 

 

- ``p`` -- a nonzero polynomial over ``F[x][y]``. The polynomial ``p`` 

should be first truncated to ``precision`` 

 

- ``degree_bound`` -- a bound on the degree of the roots of ``p`` that 

the algorithm computes 

 

- ``precision`` -- if given, roots are computed modulo `x^d` where `d` is 

``precision`` (see below) 

 

OUTPUT: 

 

The list of roots of ``p`` of degree at most ``degree_bound``: 

 

- If `precision = None` actual roots are computed, i.e. all `f \in F[x]` 

such that `p(f) = 0`. 

 

- If ``precision = k`` for some integer ``k``, then all `f \in \F[x]` such 

that `Q(f) \equiv 0 \mod x^k` are computed. This set is infinite, thus it 

represented as a list of pairs in `F[x] \times \mathbb{Z}_+`, where 

`(f, d)` denotes that `Q(f + x^d h) \equiv 0 \mod x^k` for any `h \in 

F[[x]]`. 

 

EXAMPLES:: 

 

sage: F = GF(17) 

sage: Px.<x> = F[] 

sage: Pxy.<y> = Px[] 

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

sage: Px._roth_ruckenstein(p, 3, None) 

[x^3 + 4*x + 16, x^2 + x + 1] 

sage: Px._roth_ruckenstein(p, 2, None) 

[x^2 + x + 1] 

sage: Px._roth_ruckenstein(p, 1, 2) 

[(4*x + 16, 2), (2*x + 13, 2), (15*x + 4, 2), (x + 1, 2)] 

""" 

def roth_rec(p, lam, k, g): 

r""" 

Recursive core method for Roth-Ruckenstein algorithm. 

 

INPUT: 

 

- ``p`` -- the current value of the polynomial 

- ``lam`` -- is the power of x whose coefficient is being computed 

- ``k`` -- the remaining precision to handle (if ``precision`` is given) 

- ``g`` -- the root being computed 

""" 

if precision and k <= 0: 

solutions.append((g, lam)) 

return 

val = min(c.valuation() for c in p) 

if precision: 

k = k - val 

T = p.map_coefficients(lambda c:c.shift(-val)) 

Ty = T.map_coefficients(lambda c:c[0]).change_ring(F) 

if Ty.is_zero() or (precision and k <= 0): 

if precision: 

solutions.append((g, lam)) 

else: 

solutions.append(g) 

return 

roots = Ty.roots(multiplicities=False) 

for gamma in roots: 

g_new = g + gamma*x**lam 

if lam < degree_bound: 

Tg = T(x*y + gamma) 

roth_rec(Tg , lam+1, k, g_new) 

else: 

if precision: 

solutions.append((g_new, lam+1)) 

elif p(gamma).is_zero(): 

solutions.append(g_new) 

return 

 

x = self.gen() 

y = p.parent().gen() 

F = self.base_ring() 

solutions = [] 

g = self.zero() 

 

roth_rec(p, 0, precision, g) 

return solutions 

 

def _alekhnovich(self, p, degree_bound, precision=None, dc_threshold=None): 

r""" 

Use Alekhnovich's Divide & Conquer variant of Roth-Ruckenstein's 

rootfinding algorithm to find roots modulo-up-to-some-precision of a `Q \in 

F[x][y]` where `F` is a finite field. Supports a mixed strategy with 

Roth-Ruckenstein applied at lowest precision. 

 

INPUT: 

 

- ``p`` -- a nonzero polynomial over ``F[x][y]``. The polynomial ``p`` 

should be first truncated to ``precision`` 

 

- ``degree_bound`` -- a bound on the degree of the roots of ``p`` that 

the algorithm computes 

 

- ``precision`` -- if given, roots are computed modulo `x^d` where `d` is 

``precision`` (see below) 

 

- ``dc_threshold`` -- if given, the algorithm calls :meth:`_roth_ruckenetein` 

to compute roots of degree at most ``dc_threshold`` 

 

OUTPUT: 

 

The list of roots of ``p`` of degree at most ``degree_bound``: 

 

- If `precision = None` actual roots are computed, i.e. all `f \in F[x]` 

such that `p(f) = 0`. 

 

- If ``precision = k`` for some integer ``k``, then all `f \in \F[x]` such 

that `Q(f) \equiv 0 \mod x^k` are computed. This set is infinite, thus it 

represented as a list of pairs in `F[x] \times \mathbb{Z}_+`, where 

`(f, d)` denotes that `Q(f + x^d h) \equiv 0 \mod x^k` for any `h \in 

F[[x]]`. 

 

.. NOTE:: 

 

Non-exhaustive testing tends to indicate that ``dc_threhold = None`` is, 

surprisingly, the best strategy. (See the example section.) 

 

EXAMPLES:: 

 

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

sage: S.<y> = R[] 

sage: p = (y - 2*x^2 - 3*x - 14) * (y - 3*x + 2) * (y - 1) 

sage: R._alekhnovich(p, 2) 

[3*x + 15, 2*x^2 + 3*x + 14, 1] 

sage: R._alekhnovich(p, 1) 

[3*x + 15, 1] 

sage: R._alekhnovich(p, 1, precision = 2) 

[(3*x + 15, 2), (3*x + 14, 2), (1, 2)] 

 

Example of benchmark to check that `dc_threshold = None` is better:: 

 

sage: p = prod(y - R.random_element(20) for _ in range(10)) * S.random_element(10,10) # not tested 

sage: %timeit _alekhnovich(R, p, 20, dc_threshold = None) # not tested 

1 loop, best of 3: 418 ms per loop 

sage: %timeit _alekhnovich(R, p, 20, dc_threshold = 1) # not tested 

1 loop, best of 3: 416 ms per loop 

sage: %timeit _alekhnovich(R, p, 20, dc_threshold = 2) # not tested 

1 loop, best of 3: 418 ms per loop 

sage: %timeit _alekhnovich(R, p, 20, dc_threshold = 3) # not tested 

1 loop, best of 3: 454 ms per loop 

sage: %timeit _alekhnovich(R, p, 20, dc_threshold = 4) # not tested 

1 loop, best of 3: 519 ms per loop 

 

AUTHORS: 

 

- Johan Rosenkilde (2015) -- Original implementation 

- Bruno Grenet (August 2016) -- Incorporation into SageMath and polishing 

""" 

def alekh_rec(p, k, degree_bound, lvl): 

r""" 

Recursive core method for Alekhnovich algorithm." 

 

INPUT: 

 

- ``p`` -- the current value of the polynomial 

- ``k`` -- the number of coefficients left to be computed 

- ``degree_bound`` -- the current degree bound 

- ``lvl`` -- the level in the recursion tree 

""" 

if k<=0: 

return [ (self.zero(),0) ] 

elif degree_bound < 0: 

# The only possible root of (current) p, if any, is y = 0 

if p(0).is_zero() or p(0).valuation() >= k: 

return [ (self.zero(),0) ] 

else: 

return [] 

elif k == 1 or degree_bound == 0: 

#Either one coefficient left to be computed, or p has only one coefficient 

py = self([c[0] for c in p.list()]) # py = p(x=0, y) 

if py.is_zero(): 

return [ (self.zero(), 0) ] 

roots = py.roots(multiplicities=False) 

return [ (self(r),1) for r in roots ] 

elif k < dc_threshold: 

# Run Roth-Ruckenstein 

return self._roth_ruckenstein(p, degree_bound=degree_bound, precision=k) 

else: 

p = p.map_coefficients(lambda c:c.truncate(k)) 

half_roots = alekh_rec(p, k//2, degree_bound, lvl+1) 

whole_roots = [] 

for (hi, di) in half_roots: 

QhatT = p(hi + y*x**di) 

if not QhatT: 

whole_roots.append((hi,di)) 

else: 

val = min(c.valuation() for c in QhatT) 

Qhat = QhatT.map_coefficients(lambda c:c.shift(-val)) 

sec_half = alekh_rec(Qhat, k-val, degree_bound - di, lvl+1) 

whole_roots.extend([ (hi + hij.shift(di), di+dij) for (hij, dij) in sec_half ]) 

return whole_roots 

 

x = self.gen() 

y = p.parent().gen() 

 

# If precision is not given, find actual roots. To be sure, precision then 

# needs to be more than wdeg{1,degree_bound}(Q) since a root might have degree degree_bound. 

if precision is None: 

k = 1 + max( p[i].degree() + degree_bound*i for i in range(1+p.degree())) 

else: 

k = precision 

 

mod_roots = alekh_rec(p, k, degree_bound, 0) 

 

if precision is None: 

roots = [] 

for hi,_ in mod_roots: 

if p(hi).is_zero(): 

roots.append(hi) 

return roots 

else: 

return mod_roots 

 

def _roots_univariate_polynomial(self, p, ring=None, multiplicities=False, algorithm=None, degree_bound=None): 

""" 

Return the list of roots of ``p``. 

 

INPUT: 

 

- ``p`` -- the polynomial whose roots are computed 

- ``ring`` -- the ring to find roots (default is the base ring of ``p``) 

- ``multiplicities`` -- bool (default: True): currently, roots are only 

computed without their multiplicities. 

- ``algorithm`` -- the algorithm to use: either ``"Alekhnovich"`` (default) 

or ``"Roth-Ruckenstein"`` 

- ``degree_bound``-- if not ``None``, return only roots of degree at 

most ``degree_bound`` 

 

EXAMPLES:: 

 

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

sage: S.<y> = R[] 

sage: p = y^2 + (12*x^2 + x + 11)*y + x^3 + 12*x^2 + 12*x + 1 

sage: p.roots(multiplicities=False) 

[x^2 + 11*x + 1, x + 1] 

sage: p.roots(multiplicities=False, degree_bound=1) 

[x + 1] 

sage: p.roots(multiplicities=False, algorithm="Roth-Ruckenstein") 

[x^2 + 11*x + 1, x + 1] 

""" 

if multiplicities: 

raise NotImplementedError("Use multiplicities=False") 

 

if degree_bound is None: 

l = p.degree() 

dl = p[l].degree() 

degree_bound = max((p[i].degree() - dl)//(l - i) for i in range(l) if p[i]) 

 

if algorithm is None: 

algorithm = "Alekhnovich" 

 

if algorithm == "Roth-Ruckenstein": 

return self._roth_ruckenstein(p, degree_bound, None) 

 

elif algorithm == "Alekhnovich": 

return self._alekhnovich(p, degree_bound) 

 

else: 

raise ValueError("unknown algorithm '{}'".format(algorithm)) 

 

 

class PolynomialRing_cdvr(PolynomialRing_integral_domain): 

r""" 

A class for polynomial ring over complete discrete valuation rings 

""" 

def __init__(self, base_ring, name=None, sparse=False, element_class=None, category=None): 

r""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_cdvr 

 

sage: S.<x> = ZZ[] 

sage: isinstance(S, PolynomialRing_cdvr) 

False 

 

sage: S.<x> = Zp(5)[] 

sage: isinstance(S, PolynomialRing_cdvr) 

True 

""" 

if element_class is None: 

if sparse: 

from sage.rings.polynomial.polynomial_element_generic import Polynomial_generic_sparse_cdvr 

element_class = Polynomial_generic_sparse_cdvr 

else: 

from sage.rings.polynomial.polynomial_element_generic import Polynomial_generic_dense_cdvr 

element_class = Polynomial_generic_dense_cdvr 

PolynomialRing_integral_domain.__init__(self, base_ring, name, sparse, element_class=element_class, category=category) 

 

 

class PolynomialRing_cdvf(PolynomialRing_cdvr, PolynomialRing_field): 

""" 

A class for polynomial ring over complete discrete valuation fields 

""" 

def __init__(self, base_ring, name=None, sparse=False, element_class=None, category=None): 

r""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_cdvf 

 

sage: S.<x> = QQ[] 

sage: isinstance(S, PolynomialRing_cdvf) 

False 

 

sage: S.<x> = Qp(5)[] 

sage: isinstance(S, PolynomialRing_cdvf) 

True 

""" 

if element_class is None: 

if sparse: 

from sage.rings.polynomial.polynomial_element_generic import Polynomial_generic_sparse_cdvf 

element_class = Polynomial_generic_sparse_cdvf 

else: 

from sage.rings.polynomial.polynomial_element_generic import Polynomial_generic_dense_cdvf 

element_class = Polynomial_generic_dense_cdvf 

PolynomialRing_field.__init__(self, base_ring, name, sparse, element_class=element_class, category=category) 

 

 

class PolynomialRing_dense_padic_ring_generic(PolynomialRing_cdvr): 

r""" 

A class for dense polynomial ring over padic rings 

""" 

def __init__(self, base_ring, name=None, element_class=None, category=None): 

PolynomialRing_cdvr.__init__(self, base_ring, sparse=False, name=name, element_class=element_class, category=category) 

 

@staticmethod 

def _implementation_names_impl(implementation, base_ring, sparse): 

""" 

Only support ``implementation=None`` and ``sparse=False``. 

 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_padic_ring_generic 

sage: PolynomialRing_dense_padic_ring_generic._implementation_names_impl(None, Zp(2), False) 

[None] 

sage: PolynomialRing_dense_padic_ring_generic._implementation_names_impl(None, Zp(2), True) 

NotImplemented 

sage: PolynomialRing_dense_padic_ring_generic._implementation_names_impl("generic", Zp(2), False) 

NotImplemented 

""" 

if implementation is None and not sparse: 

return [None] # Not a "generic" implementation 

return NotImplemented 

 

 

class PolynomialRing_dense_padic_field_generic(PolynomialRing_cdvf): 

r""" 

A class for dense polynomial ring over padic fields 

""" 

def __init__(self, base_ring, name=None, element_class=None, category=None): 

PolynomialRing_cdvf.__init__(self, base_ring, sparse=False, name=name, element_class=element_class, category=category) 

 

@staticmethod 

def _implementation_names_impl(implementation, base_ring, sparse): 

""" 

Only support ``implementation=None`` and ``sparse=False``. 

 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_padic_field_generic 

sage: PolynomialRing_dense_padic_field_generic._implementation_names_impl(None, Qp(2), False) 

[None] 

sage: PolynomialRing_dense_padic_field_generic._implementation_names_impl(None, Qp(2), True) 

NotImplemented 

sage: PolynomialRing_dense_padic_field_generic._implementation_names_impl("generic", Qp(2), False) 

NotImplemented 

""" 

if implementation is None and not sparse: 

return [None] # Not a "generic" implementation 

return NotImplemented 

 

 

class PolynomialRing_dense_padic_ring_capped_relative(PolynomialRing_dense_padic_ring_generic): 

def __init__(self, base_ring, name=None, element_class=None, category=None): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_padic_ring_capped_relative as PRing 

sage: R = PRing(Zp(13), name='t'); R 

Univariate Polynomial Ring in t over 13-adic Ring with capped relative precision 20 

sage: type(R.gen()) 

<class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_dense_padic_ring_capped_relative_with_category.element_class'> 

""" 

if element_class is None: 

from sage.rings.polynomial.padics.\ 

polynomial_padic_capped_relative_dense import \ 

Polynomial_padic_capped_relative_dense 

element_class = Polynomial_padic_capped_relative_dense 

PolynomialRing_dense_padic_ring_generic.__init__(self, base_ring, 

name=name, element_class=element_class, category=category) 

 

 

class PolynomialRing_dense_padic_ring_capped_absolute(PolynomialRing_dense_padic_ring_generic): 

def __init__(self, base_ring, name=None, element_class=None, category=None): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_padic_ring_capped_absolute as PRing 

sage: R = PRing(Zp(13, type='capped-abs'), name='t'); R 

Univariate Polynomial Ring in t over 13-adic Ring with capped absolute precision 20 

sage: type(R.gen()) 

<class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_dense_padic_ring_capped_absolute_with_category.element_class'> 

""" 

if element_class is None: 

from sage.rings.polynomial.padics.polynomial_padic_flat import \ 

Polynomial_padic_flat 

element_class = Polynomial_padic_flat 

PolynomialRing_dense_padic_ring_generic.__init__(self, base_ring, 

name=name, element_class=element_class, category=category) 

 

 

class PolynomialRing_dense_padic_ring_fixed_mod(PolynomialRing_dense_padic_ring_generic): 

def __init__(self, base_ring, name=None, element_class=None, category=None): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_padic_ring_fixed_mod as PRing 

sage: R = PRing(Zp(13, type='fixed-mod'), name='t'); R 

Univariate Polynomial Ring in t over 13-adic Ring of fixed modulus 13^20 

 

sage: type(R.gen()) 

<class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_dense_padic_ring_fixed_mod_with_category.element_class'> 

""" 

if element_class is None: 

from sage.rings.polynomial.padics.polynomial_padic_flat import \ 

Polynomial_padic_flat 

element_class = Polynomial_padic_flat 

PolynomialRing_dense_padic_ring_generic.__init__(self, base_ring, 

name=name, element_class=element_class, category=category) 

 

 

class PolynomialRing_dense_padic_field_capped_relative(PolynomialRing_dense_padic_field_generic): 

def __init__(self, base_ring, name=None, element_class=None, category=None): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_padic_field_capped_relative as PRing 

sage: R = PRing(Qp(13), name='t'); R 

Univariate Polynomial Ring in t over 13-adic Field with capped relative precision 20 

sage: type(R.gen()) 

<class 'sage.rings.polynomial.polynomial_ring.PolynomialRing_dense_padic_field_capped_relative_with_category.element_class'> 

""" 

if element_class is None: 

from sage.rings.polynomial.padics.\ 

polynomial_padic_capped_relative_dense import \ 

Polynomial_padic_capped_relative_dense 

element_class = Polynomial_padic_capped_relative_dense 

PolynomialRing_dense_padic_field_generic.__init__(self, base_ring, 

name=name, element_class=element_class, category=category) 

 

 

class PolynomialRing_dense_mod_n(PolynomialRing_commutative): 

def __init__(self, base_ring, name=None, element_class=None, 

implementation=None, category=None): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_mod_n as PRing 

sage: R = PRing(Zmod(15), 'x'); R 

Univariate Polynomial Ring in x over Ring of integers modulo 15 

sage: type(R.gen()) 

<type 'sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint'> 

 

sage: R = PRing(Zmod(15), 'x', implementation='NTL'); R 

Univariate Polynomial Ring in x over Ring of integers modulo 15 (using NTL) 

sage: type(R.gen()) 

<type 'sage.rings.polynomial.polynomial_modn_dense_ntl.Polynomial_dense_modn_ntl_zz'> 

 

sage: R = PRing(Zmod(2**63*3), 'x', implementation='NTL'); R 

Univariate Polynomial Ring in x over Ring of integers modulo 27670116110564327424 (using NTL) 

sage: type(R.gen()) 

<type 'sage.rings.polynomial.polynomial_modn_dense_ntl.Polynomial_dense_modn_ntl_ZZ'> 

 

sage: R = PRing(Zmod(2**63*3), 'x', implementation='FLINT') 

Traceback (most recent call last): 

... 

ValueError: FLINT does not support modulus 27670116110564327424 

 

sage: R = PRing(Zmod(2**63*3), 'x'); R 

Univariate Polynomial Ring in x over Ring of integers modulo 27670116110564327424 (using NTL) 

sage: type(R.gen()) 

<type 'sage.rings.polynomial.polynomial_modn_dense_ntl.Polynomial_dense_modn_ntl_ZZ'> 

""" 

if element_class is None: 

implementation = self._implementation_names(implementation, base_ring)[0] 

if implementation == "FLINT": 

from .polynomial_zmod_flint import \ 

Polynomial_zmod_flint as element_class 

self._implementation_repr = '' 

elif implementation == "NTL": 

modulus = base_ring.order() 

from . import polynomial_modn_dense_ntl as modn_dense_ntl 

if modulus < ZZ(modn_dense_ntl.zz_p_max): 

element_class = modn_dense_ntl.Polynomial_dense_modn_ntl_zz 

else: 

element_class = modn_dense_ntl.Polynomial_dense_modn_ntl_ZZ 

self._implementation_repr = ' (using NTL)' 

PolynomialRing_commutative.__init__(self, base_ring, name=name, 

element_class=element_class, category=category) 

 

@staticmethod 

def _implementation_names_impl(implementation, base_ring, sparse): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_mod_n 

sage: PolynomialRing_dense_mod_n._implementation_names_impl("FLINT", IntegerModRing(10), False) 

['FLINT', None] 

sage: PolynomialRing_dense_mod_n._implementation_names_impl("NTL", IntegerModRing(10), False) 

['NTL'] 

sage: PolynomialRing_dense_mod_n._implementation_names_impl(None, IntegerModRing(10), False) 

['FLINT', None] 

sage: PolynomialRing_dense_mod_n._implementation_names_impl("generic", IntegerModRing(10), False) 

NotImplemented 

sage: PolynomialRing_dense_mod_n._implementation_names_impl("FLINT", IntegerModRing(10^30), False) 

Traceback (most recent call last): 

... 

ValueError: FLINT does not support modulus 1000000000000000000000000000000 

sage: PolynomialRing_dense_mod_n._implementation_names_impl("NTL", IntegerModRing(10^30), False) 

['NTL', None] 

sage: PolynomialRing_dense_mod_n._implementation_names_impl(None, IntegerModRing(10^30), False) 

['NTL', None] 

sage: PolynomialRing_dense_mod_n._implementation_names_impl("generic", IntegerModRing(10^30), False) 

NotImplemented 

sage: PolynomialRing_dense_mod_n._implementation_names_impl(None, IntegerModRing(10^30), True) 

NotImplemented 

""" 

if sparse: 

return NotImplemented 

modulus = base_ring.order() 

if modulus <= sys.maxsize: 

defaults = ["FLINT", None] 

elif implementation == "FLINT": 

raise ValueError("FLINT does not support modulus %s" % modulus) 

else: 

defaults = ["NTL", None] 

if implementation in defaults: 

return defaults 

elif implementation == "NTL": 

return [implementation] 

return NotImplemented 

 

@cached_method 

def modulus(self): 

""" 

EXAMPLES:: 

 

sage: R.<x> = Zmod(15)[] 

sage: R.modulus() 

15 

""" 

return self.base_ring().characteristic() 

 

def _repr_(self): 

""" 

TESTS:: 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_integral_domain as PRing 

sage: R = PRing(ZZ, 'x', implementation='NTL'); R 

Univariate Polynomial Ring in x over Integer Ring (using NTL) 

""" 

s = PolynomialRing_commutative._repr_(self) 

return s + self._implementation_repr 

 

def residue_field(self, ideal, names=None): 

""" 

Return the residue finite field at the given ideal. 

 

EXAMPLES:: 

 

sage: R.<t> = GF(2)[] 

sage: k.<a> = R.residue_field(t^3+t+1); k 

Residue field in a of Principal ideal (t^3 + t + 1) of Univariate Polynomial Ring in t over Finite Field of size 2 (using GF2X) 

sage: k.list() 

[0, a, a^2, a + 1, a^2 + a, a^2 + a + 1, a^2 + 1, 1] 

sage: R.residue_field(t) 

Residue field of Principal ideal (t) of Univariate Polynomial Ring in t over Finite Field of size 2 (using GF2X) 

sage: P = R.irreducible_element(8) * R 

sage: P 

Principal ideal (t^8 + t^4 + t^3 + t^2 + 1) of Univariate Polynomial Ring in t over Finite Field of size 2 (using GF2X) 

sage: k.<a> = R.residue_field(P); k 

Residue field in a of Principal ideal (t^8 + t^4 + t^3 + t^2 + 1) of Univariate Polynomial Ring in t over Finite Field of size 2 (using GF2X) 

sage: k.cardinality() 

256 

 

Non-maximal ideals are not accepted:: 

 

sage: R.residue_field(t^2 + 1) 

Traceback (most recent call last): 

... 

ArithmeticError: ideal is not maximal 

sage: R.residue_field(0) 

Traceback (most recent call last): 

... 

ArithmeticError: ideal is not maximal 

sage: R.residue_field(1) 

Traceback (most recent call last): 

... 

ArithmeticError: ideal is not maximal 

""" 

ideal = self.ideal(ideal) 

if not ideal.is_maximal(): 

raise ArithmeticError("ideal is not maximal") 

return ideal.residue_field(names) 

 

 

class PolynomialRing_dense_mod_p(PolynomialRing_dense_finite_field, 

PolynomialRing_dense_mod_n, 

PolynomialRing_singular_repr): 

def __init__(self, base_ring, name="x", implementation=None, category=None): 

""" 

TESTS:: 

 

sage: P = GF(2)['x']; P 

Univariate Polynomial Ring in x over Finite Field of size 2 (using GF2X) 

sage: type(P.gen()) 

<type 'sage.rings.polynomial.polynomial_gf2x.Polynomial_GF2X'> 

 

sage: from sage.rings.polynomial.polynomial_ring import PolynomialRing_dense_mod_p 

sage: P = PolynomialRing_dense_mod_p(GF(5), 'x'); P 

Univariate Polynomial Ring in x over Finite Field of size 5 

sage: type(P.gen()) 

<type 'sage.rings.polynomial.polynomial_zmod_flint.Polynomial_zmod_flint'> 

 

sage: P = PolynomialRing_dense_mod_p(GF(5), 'x', implementation='NTL'); P 

Univariate Polynomial Ring in x over Finite Field of size 5 (using NTL) 

sage: type(P.gen()) 

<type 'sage.rings.polynomial.polynomial_modn_dense_ntl.Polynomial_dense_mod_p'> 

 

sage: P = PolynomialRing_dense_mod_p(GF(9223372036854775837), 'x') 

sage: P 

Univariate Polynomial Ring in x over Finite Field of size 9223372036854775837 (using NTL) 

sage: type(P.gen()) 

<type 'sage.rings.polynomial.polynomial_modn_dense_ntl.Polynomial_dense_mod_p'> 

 

This caching bug was fixed in :trac:`24264`:: 

 

sage: p = 2^64 + 13 

sage: A = GF(p^2) 

sage: B = GF(p^3) 

sage: R = A.modulus().parent() 

sage: S = B.modulus().parent() 

sage: R is S 

True 

""" 

implementation = self._implementation_names(implementation, base_ring)[0] 

if implementation == "FLINT": 

from .polynomial_zmod_flint import \ 

Polynomial_zmod_flint as element_class 

self._implementation_repr = '' 

elif implementation == "NTL": 

from .polynomial_modn_dense_ntl import \ 

Polynomial_dense_mod_p as element_class 

self._implementation_repr = ' (using NTL)' 

elif implementation == "GF2X": 

from .polynomial_gf2x import \ 

Polynomial_GF2X as element_class 

self._implementation_repr = ' (using GF2X)' 

PolynomialRing_dense_mod_n.__init__(self, base_ring, name=name, 

element_class=element_class, category=category) 

 

from sage.rings.polynomial.polynomial_singular_interface import can_convert_to_singular 

self._has_singular = can_convert_to_singular(self) 

 

@staticmethod 

def _implementation_names_impl(implementation, base_ring, sparse): 

""" 

TESTS:: 

 

sage: PolynomialRing(GF(2), 'x', implementation="GF2X") 

Univariate Polynomial Ring in x over Finite Field of size 2 (using GF2X) 

sage: PolynomialRing(GF(2), 'x', implementation="NTL") 

Univariate Polynomial Ring in x over Finite Field of size 2 (using GF2X) 

sage: PolynomialRing(GF(2), 'x', implementation=None) 

Univariate Polynomial Ring in x over Finite Field of size 2 (using GF2X) 

sage: PolynomialRing(GF(2), 'x', implementation="FLINT") 

Univariate Polynomial Ring in x over Finite Field of size 2 

sage: PolynomialRing(GF(3), 'x', implementation="GF2X") 

Traceback (most recent call last): 

... 

ValueError: GF2X only supports modulus 2 

""" 

if sparse: 

return NotImplemented 

modulus = base_ring.characteristic() 

if modulus == 2: 

defaults = ["GF2X", "NTL", None] 

elif implementation == "GF2X": 

raise ValueError("GF2X only supports modulus 2") 

elif modulus <= sys.maxsize: 

defaults = ["FLINT", None] 

elif implementation == "FLINT": 

raise ValueError("FLINT does not support modulus %s" % modulus) 

else: 

defaults = ["NTL", None] 

if implementation in defaults: 

return defaults 

elif implementation in ["NTL", "FLINT"]: 

return [implementation] 

return NotImplemented 

 

def irreducible_element(self, n, algorithm=None): 

""" 

Construct a monic irreducible polynomial of degree `n`. 

 

INPUT: 

 

- ``n`` -- integer: the degree of the polynomial to construct 

 

- ``algorithm`` -- string: algorithm to use, or ``None``. 

Currently available options are: 

 

- ``'adleman-lenstra'``: a variant of the Adleman--Lenstra 

algorithm as implemented in PARI. 

 

- ``'conway'``: look up the Conway polynomial of degree `n` 

over the field of `p` elements in the database; raise a 

``RuntimeError`` if it is not found. 

 

- ``'ffprimroot'``: use the ``ffprimroot()`` function from 

PARI. 

 

- ``'first_lexicographic'``: return the lexicographically 

smallest irreducible polynomial of degree `n`. 

 

- ``'minimal_weight'``: return an irreducible polynomial of 

degree `n` with minimal number of non-zero coefficients. 

Only implemented for `p = 2`. 

 

- ``'primitive'``: return a polynomial `f` such that a root of 

`f` generates the multiplicative group of the finite field 

extension defined by `f`. This uses the Conway polynomial if 

possible, otherwise it uses ``ffprimroot``. 

 

- ``'random'``: try random polynomials until an irreducible 

one is found. 

 

If ``algorithm`` is ``None``, use `x - 1` in degree 1. In 

degree > 1, the Conway polynomial is used if it is found in 

the database. Otherwise, the algorithm ``minimal_weight`` 

is used if `p = 2`, and the algorithm ``adleman-lenstra`` if 

`p > 2`. 

 

OUTPUT: 

 

A monic irreducible polynomial of degree `n` in ``self``. 

 

EXAMPLES:: 

 

sage: GF(5)['x'].irreducible_element(2) 

x^2 + 4*x + 2 

sage: GF(5)['x'].irreducible_element(2, algorithm="adleman-lenstra") 

x^2 + x + 1 

sage: GF(5)['x'].irreducible_element(2, algorithm="primitive") 

x^2 + 4*x + 2 

sage: GF(5)['x'].irreducible_element(32, algorithm="first_lexicographic") 

x^32 + 2 

sage: GF(5)['x'].irreducible_element(32, algorithm="conway") 

Traceback (most recent call last): 

... 

RuntimeError: requested Conway polynomial not in database. 

sage: GF(5)['x'].irreducible_element(32, algorithm="primitive") 

x^32 + ... 

 

In characteristic 2:: 

 

sage: GF(2)['x'].irreducible_element(33) 

x^33 + x^13 + x^12 + x^11 + x^10 + x^8 + x^6 + x^3 + 1 

sage: GF(2)['x'].irreducible_element(33, algorithm="minimal_weight") 

x^33 + x^10 + 1 

 

In degree 1:: 

 

sage: GF(97)['x'].irreducible_element(1) 

x + 96 

sage: GF(97)['x'].irreducible_element(1, algorithm="conway") 

x + 92 

sage: GF(97)['x'].irreducible_element(1, algorithm="adleman-lenstra") 

x 

 

AUTHORS: 

 

- Peter Bruin (June 2013) 

 

- Jeroen Demeyer (September 2014): add "ffprimroot" algorithm, 

see :trac:`8373`. 

""" 

from sage.libs.pari.all import pari 

from sage.rings.finite_rings.conway_polynomials import (conway_polynomial, 

exists_conway_polynomial) 

from .polynomial_gf2x import (GF2X_BuildIrred_list, 

GF2X_BuildSparseIrred_list, 

GF2X_BuildRandomIrred_list) 

 

p = self.characteristic() 

n = int(n) 

if n < 1: 

raise ValueError("degree must be at least 1") 

 

if algorithm is None: 

if n == 1: 

return self((-1,1)) # Polynomial x - 1 

elif exists_conway_polynomial(p, n): 

algorithm = "conway" 

elif p == 2: 

algorithm = "minimal_weight" 

else: 

algorithm = "adleman-lenstra" 

elif algorithm == "primitive": 

if exists_conway_polynomial(p, n): 

algorithm = "conway" 

else: 

algorithm = "ffprimroot" 

 

if algorithm == "adleman-lenstra": 

return self(pari(p).ffinit(n)) 

elif algorithm == "conway": 

return self(conway_polynomial(p, n)) 

elif algorithm == "first_lexicographic": 

if p == 2: 

return self(GF2X_BuildIrred_list(n)) 

else: 

# Fallback to PolynomialRing_dense_finite_field.irreducible_element 

pass 

elif algorithm == "ffprimroot": 

return self(pari(p).ffinit(n).ffgen().ffprimroot().charpoly()) 

elif algorithm == "minimal_weight": 

if p == 2: 

return self(GF2X_BuildSparseIrred_list(n)) 

else: 

raise NotImplementedError("'minimal_weight' option only implemented for p = 2") 

elif algorithm == "random": 

if p == 2: 

return self(GF2X_BuildRandomIrred_list(n)) 

else: 

pass 

 

# No suitable algorithm found, try algorithms from the base class. 

return PolynomialRing_dense_finite_field.irreducible_element(self, n, algorithm) 

 

def polygen(ring_or_element, name="x"): 

""" 

Return a polynomial indeterminate. 

 

INPUT: 

 

- polygen(base_ring, name="x") 

 

- polygen(ring_element, name="x") 

 

If the first input is a ring, return a polynomial generator over 

that ring. If it is a ring element, return a polynomial generator 

over the parent of the element. 

 

EXAMPLES:: 

 

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

sage: z^3 + z +1 

z^3 + z + 1 

sage: parent(z) 

Univariate Polynomial Ring in z over Rational Field 

 

.. note:: 

 

If you give a list or comma separated string to polygen, you'll 

get a tuple of indeterminates, exactly as if you called 

polygens. 

""" 

if is_RingElement(ring_or_element): 

base_ring = ring_or_element.parent() 

elif ring.is_Ring(ring_or_element): 

base_ring = ring_or_element 

else: 

raise TypeError("input must be a ring or ring element") 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

 

t = PolynomialRing(base_ring, name) 

if t.ngens() > 1: 

return t.gens() 

return t.gen() 

 

def polygens(base_ring, names="x"): 

""" 

Return indeterminates over the given base ring with the given 

names. 

 

EXAMPLES:: 

 

sage: x,y,z = polygens(QQ,'x,y,z') 

sage: (x+y+z)^2 

x^2 + 2*x*y + y^2 + 2*x*z + 2*y*z + z^2 

sage: parent(x) 

Multivariate Polynomial Ring in x, y, z over Rational Field 

sage: t = polygens(QQ,['x','yz','abc']) 

sage: t 

(x, yz, abc) 

""" 

from sage.rings.polynomial.polynomial_ring_constructor import PolynomialRing 

return PolynomialRing(base_ring, names).gens()