euler / probs.clj

   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
;; : clojure : 0; java -cp clojure.jar clojure.lang.Repl

(ns user
  (:import (java.io BufferedReader FileReader)
           (java.util Date Date)
           (java.util Calendar Calendar)
           (java.util GregorianCalendar)
           (java.text DateFormat DateFormat)))

;{{{ problems 1-50

;{{{ problem  1 -- sum of multiples

;; If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

;; Find the sum of all the multiples of 3 or 5 below 1000.

;}}}
;{{{ problem  2 -- fibonacci sum

;; Each new term in the Fibonacci sequence is generated by adding the
;; previous two terms. By starting with 1 and 2, the first 10 terms
;; will be:

;; 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

;; Find the sum of all the even-valued terms in the sequence which do
;; not exceed four million.

(defn next-fib-sum [sum a b limit]
  (let [c (+ a b)]
    (if (> c limit)
        sum
      (recur (if (= 0 (rem c 2)) (+ sum c) sum)
             b c limit))))

(defn fib-sum-below [n]
  (next-fib-sum 0 1 1 n))

;; (fib-sum-below 4000000)
;; 4613732

;}}}
;{{{ problem  3 -- factors

;; The prime factors of 13195 are 5, 7, 13 and 29.

;; http://clj-me.blogspot.com/2008/06/primes.html
;; pointed me to contrib/
;; (ns euler.prob3
;;   (:use clojure.contrib.def)
;;   (:use clojure.contrib.lazy-seqs)
;;   )


(def primes-2 (lazy-cons 2 ((fn this[n]
  (let [potential-divisors (take-while #(<= (* % %) n) primes-2)]
    (if (some #(zero? (rem n %)) potential-divisors)
        (recur (inc n))
      (lazy-cons n (this (inc n)))))) 3)))

(def primes primes-2)

;; This runs out of memory for some reason, as does the lazy-seqs one
(defn sieve [s]
  (lazy-cons (first s)
             (sieve (filter
                     (fn [x]
                       (not
                        (= (rem x (first s)) 0)))
                     (rest s)))))
(def primes-3 (sieve (iterate inc 2)))

(defn divides? [candidate-divisor dividend]
  (zero? (rem dividend candidate-divisor)))

;; Should move this to a let function inside of factors
(defn factors-rec [n acc seq]
  (let [cur (first seq)]
;;     (debug cur)
;;     (debug n)
;;     (debug (divides? cur n))
;;     (debug acc)
;;     (debug (frest seq))
    (if (< n cur)
      acc
      (if (divides? cur n)
        (recur (/ n cur) (cons cur acc) seq)
        (recur n acc (rest seq))
        ))))

(defn factors [n]
  (factors-rec n '() primes))

(defn largest-factor [n]
  (first (factors n)))

;; (largest-factor 600851475143)
;; 6857

;; see also http://bigdingus.com/2008/07/01/finding-primes-with-erlang-and-clojure/

;}}}
;{{{ problem  4 -- palindrome

;; A palindromic number reads the same both ways. The largest palindrome
;; made from the product of two 2-digit numbers is 9009 = 91 99.

;; Find the largest palindrome made from the product of two 3-digit numbers.

(defn parse-integer [str] ; I don't like this hiding the real cause of the problem for #43
  (try (Integer/parseInt str)
       (catch NumberFormatException nfe 0)))

(defn parse-integer [str]
  (Integer/parseInt str))

(defn parse-big-integer [str]
  (BigInteger. str))

(defn num-reverse [x]
;;   (debug x)
;;   (debug (format "%d" x))
;;   (debug (reverse (format "%d" x)))
;;   (debug (apply str (reverse (format "%d" x))))
;;   (debug (parse-integer (apply str (reverse (format "%d" x)))))
  (parse-integer (apply str (reverse (format "%d" x)))))

(defn num-reverse [x]
;;   (debug x)
;;   (debug (format "%d" x))
;;   (debug (reverse (format "%d" x)))
;;   (debug (apply str (reverse (format "%d" x))))
;;   (debug (parse-integer (apply str (reverse (format "%d" x)))))
  (parse-big-integer (apply str (reverse (format "%d" x)))))

(defn palindrome? [x]
  (= x (num-reverse x)))

;; (def r (range 999 100 -1))

(defn palindromes-from [x]
  (filter #(palindrome? %)
          (map #(* x %)
               (range 999 (- x 1) -1))))

(use 'clojure.contrib.seq-utils)
(defn palindromes []
  (apply merge (map #(apply hash-set (palindromes-from %))
                 (range 999 100 -1))))


(defn palindromes []
  (apply max
         (set (flatten
               (filter (complement nil?);#(not (nil? %))
                       (map #(palindromes-from %)
                            (range 999 100 -1)))))))

;; Does this work--test it.  It's the mapcat I'm not sure about
(defn palindromes []
  (apply max
         (set (filter (complement nil?);#(not (nil? %))
                      (mapcat #(palindromes-from %)
                              (range 999 100 -1))))))
;; 906609

;}}}
;{{{ problem  5 -- lcm

;; 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

;; What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?

;; (defn encode-modified [lst]
;;   ((fn [xs accum]
;;      (if (= nil xs)
;;        accum
;;        (recur (rest xs)
;;               (concat accum
;;                       (list
;;                        (if (= (count (first xs)) 1)
;;                          (ffirst xs)
;;                          (list (count (first xs)) (ffirst xs))))))))
;;    (pack-list lst) nil))

(defn count-uniq [seq]
  (let [f (first seq)]
    (count (take-while #(= f %) seq))))

(defn run-length-encode [seq]
  (if (nil? seq)
    seq
    (let [f (first seq)
          cnt (count-uniq seq)]
      (list* (list f cnt)
             (run-length-encode (nthrest seq cnt))))))

(defn abs [x]
  (if (< x 0) (- x) x))
(defn mod [x y]
  (rem x y))

(defn gcd
  ([a] a)
  ([a b] (if (or (not (integer? a)) (not (integer? b)))
           (throw (IllegalArgumentException. "gcd requires two integers"))
           (loop [a (abs a) b (abs b)]
             (if (zero? b) a
                 (recur b (mod a b))))))
  ([a b & more] (reduce gcd (gcd a b) more)))

(defn lcm
  ([x] x)
  ([x y] (/ (* x y) (gcd x y)))
  ([x y & more] (reduce lcm (lcm x y) more)))

(defn lcm-upto [n]
  (apply lcm (range 2 (+ 1 n))))

;; (lcm-upto 20)
;; 232792560

;}}}
;{{{ problem  6 -- sum of squares

;; The sum of the squares of the first ten natural numbers is
;; 12 + 22 + ... + 102 = 385
;; The square of the sum of the first ten natural numbers is
;; (1 + 2 + ... + 10)2 = 552 = 3025
;; Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025  385 = 2640.

;; Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

(defn sum-of-squares [seq]
  (reduce + 0 (map #(* % %) seq)))
(defn square-of-sum [seq]
  (let [x (reduce + 0 seq)]
    (* x x)))


;; (- (square-of-sum (range 101))
;;    (sum-of-squares (range 101)))

;; 25164150


;; with a little help from http://mathworld.wolfram.com/PowerSum.html
(defn sum-of-squares-upto [n]
  (/ (+ (* 2 n n n) (* 3 n n) (* n)) 6))

(defn square-of-sum-upto [n]
  (let [x (/ (* n (+ n 1)) 2)]
    (* x x)))

(defn difference-sums-squares [n]
  (- (square-of-sum-upto (range n)) (sum-of-squares-upto (range n))))

;; (difference-sums-squares 101)
;; 25164150

;}}}
;{{{ problem  7 -- 10001st prime
;; By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

;; What is the 10001st prime number?

;; (nth primes 10000)                    ; 0 indexed
;; 104743

;}}}
;{{{ problem  8 -- largest product

;; Find the greatest product of five consecutive digits in the 1000-digit number.

(def string
"7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450")

(defn parse-integer [str]
  (try (Integer/parseInt str)
       (catch NumberFormatException nfe 0)))

(def list-of-nums
     (map #(parse-integer (str %)) string))

;; run this:
;; (reduce max (map *
;;                  (nthrest list-of-nums 0)
;;                  (nthrest list-of-nums 1)
;;                  (nthrest list-of-nums 2)
;;                  (nthrest list-of-nums 3)
;;                  (nthrest list-of-nums 4)))
;; 40824

;}}}
;{{{ problem  9 -- pythagorean triplet

;; A Pythagorean triplet is a set of three natural numbers, a  b  c, for which
;; a^2 + b^2 = c^2
;; For example, 32 + 42 = 9 + 16 = 25 = 52.

;; There exists exactly one Pythagorean triplet for which a + b + c = 1000.
;; Find the product abc.

(defn pythagorean-triple [n]
  (mapcat (fn [a]
            ;;          (println a)
            (mapcat (fn [b]
;;                       (println b)
                      (let [c (- n a b)]
;;                         (println a b c)
                        (if (= (+ (* a a) (* b b)) (* c c))
                          (list (* a b c)))))
                    (range a (- n a))))
          (range 1 n)))

;}}}
;{{{ problem 10 -- sum of primes

;; The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

;; Find the sum of all the primes below two million.

(defn sum-of-primes [n]
  (reduce + 0 (take-while #(< % n) primes)))

;; (sum-of-primes 2000000)
;; 142913828922

;}}}
;{{{ problem 11 -- product of 20x20 grid

;; In the 2020 grid below, four numbers along a diagonal line have
;; been marked in red.
(def grid
  '( 8  2 22 97 38 15  0 40  0 75  4  5  7 78 52 12 50 77 91  8
    49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48  4 56 62  0
    81 49 31 73 55 79 14 29 93 71 40 67 53 88 30  3 49 13 36 65
    52 70 95 23  4 60 11 42 69 24 68 56  1 32 56 71 37  2 36 91
    22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
    24 47 32 60 99  3 45  2 44 75 33 53 78 36 84 20 35 17 12 50
    32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
    67 26 20 68  2 62 12 20 95 63 94 39 63  8 40 91 66 49 94 21
    24 55 58  5 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
    21 36 23  9 75  0 76 44 20 45 35 14  0 61 33 97 34 31 33 95
    78 17 53 28 22 75 31 67 15 94  3 80  4 62 16 14  9 53 56 92
    16 39  5 42 96 35 31 47 55 58 88 24  0 17 54 24 36 29 85 57
    86 56  0 48 35 71 89  7  5 44 44 37 44 60 21 58 51 54 17 58
    19 80 81 68  5 94 47 69 28 73 92 13 86 52 17 77  4 89 55 40
     4 52  8 83 97 35 99 16  7 97 57 32 16 26 26 79 33 27 98 66
    88 36 68 87 57 62 20 72  3 46 33 67 46 55 12 32 63 93 53 69
     4 42 16 73 38 25 39 11 24 94 72 18  8 46 29 32 40 62 76 36
    20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74  4 36 16
    20 73 35 29 78 31 90  1 74 31 49 71 48 86 81 16 23 57  5 54
     1 70 54 71 83 51 54 69 16 92 33 48 61 43 52  1 89 19 67 48))

;; The product of these numbers is 26  63  78  14 = 1788696.

;; What is the greatest product of four adjacent numbers in any
;; direction (up, down, left, right, or diagonally) in the 2020 grid?

(defn get-pos [x y]
  (if (or (< x 0)
          (< y 0)
          (> x 19)
          (> y 19))
    0
    (nth grid (+ x (* 20 y)))))

(defn get-pos-offsets [x y seq]
  (reduce * (map #(get-pos (+ x (first %))
                           (+ y (frest %)))
                 seq)))


(defn largest-product []
  (reduce max (for [x (range 20)
                   y (range 20)]
               (max (get-pos-offsets x y '((0 0) (0 1) (0 2) (0 3)))
                    (get-pos-offsets x y '((0 0) (1 0) (2 0) (3 0)))
                    (get-pos-offsets x y '((0 0) (1 1) (2 2) (3 3)))
                    (get-pos-offsets x y '((0 0) (1 -1) (2 -2) (3 -3)))))))

;; 70600674

;}}}
;{{{ problem 12 -- divisors of

;; The sequence of triangle numbers is generated by adding the natural
;; numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6
;; + 7 = 28. The first ten terms would be:

;; 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

;; Let us list the factors of the first seven triangle numbers:

;;  1: 1
;;  3: 1,3
;;  6: 1,2,3,6
;; 10: 1,2,5,10
;; 15: 1,3,5,15
;; 21: 1,3,7,21
;; 28: 1,2,4,7,14,28
;; We can see that 28 is the first triangle number to have over five divisors.

;; What is the value of the first triangle number to have over five hundred divisors?

(def triangle-numbers
     (map first (iterate #(let [n (+ 1 (frest %))]
                            (list (+ n (first %)) n))
                         '(1 1))))

(defn num-divisors [n]
  (reduce * (map #(+ 1 (nth % 1))
                 (run-length-encode (factors n)))))

(defn triangle-with-num-divisors [n]
  (take 1 (filter #(> (num-divisors %) n) triangle-numbers)))

;; (triangle-with-num-divisors 500)
;; 76576500

;}}}
;{{{ problem 13 -- sum of big numbers

;; Work out the first ten digits of the sum of the following one-hundred 50-digit numbers.
(def numbers '(37107287533902102798797998220837590246510135740250
               46376937677490009712648124896970078050417018260538
               74324986199524741059474233309513058123726617309629
               91942213363574161572522430563301811072406154908250
               23067588207539346171171980310421047513778063246676
               89261670696623633820136378418383684178734361726757
               28112879812849979408065481931592621691275889832738
               44274228917432520321923589422876796487670272189318
               47451445736001306439091167216856844588711603153276
               70386486105843025439939619828917593665686757934951
               62176457141856560629502157223196586755079324193331
               64906352462741904929101432445813822663347944758178
               92575867718337217661963751590579239728245598838407
               58203565325359399008402633568948830189458628227828
               80181199384826282014278194139940567587151170094390
               35398664372827112653829987240784473053190104293586
               86515506006295864861532075273371959191420517255829
               71693888707715466499115593487603532921714970056938
               54370070576826684624621495650076471787294438377604
               53282654108756828443191190634694037855217779295145
               36123272525000296071075082563815656710885258350721
               45876576172410976447339110607218265236877223636045
               17423706905851860660448207621209813287860733969412
               81142660418086830619328460811191061556940512689692
               51934325451728388641918047049293215058642563049483
               62467221648435076201727918039944693004732956340691
               15732444386908125794514089057706229429197107928209
               55037687525678773091862540744969844508330393682126
               18336384825330154686196124348767681297534375946515
               80386287592878490201521685554828717201219257766954
               78182833757993103614740356856449095527097864797581
               16726320100436897842553539920931837441497806860984
               48403098129077791799088218795327364475675590848030
               87086987551392711854517078544161852424320693150332
               59959406895756536782107074926966537676326235447210
               69793950679652694742597709739166693763042633987085
               41052684708299085211399427365734116182760315001271
               65378607361501080857009149939512557028198746004375
               35829035317434717326932123578154982629742552737307
               94953759765105305946966067683156574377167401875275
               88902802571733229619176668713819931811048770190271
               25267680276078003013678680992525463401061632866526
               36270218540497705585629946580636237993140746255962
               24074486908231174977792365466257246923322810917141
               91430288197103288597806669760892938638285025333403
               34413065578016127815921815005561868836468420090470
               23053081172816430487623791969842487255036638784583
               11487696932154902810424020138335124462181441773470
               63783299490636259666498587618221225225512486764533
               67720186971698544312419572409913959008952310058822
               95548255300263520781532296796249481641953868218774
               76085327132285723110424803456124867697064507995236
               37774242535411291684276865538926205024910326572967
               23701913275725675285653248258265463092207058596522
               29798860272258331913126375147341994889534765745501
               18495701454879288984856827726077713721403798879715
               38298203783031473527721580348144513491373226651381
               34829543829199918180278916522431027392251122869539
               40957953066405232632538044100059654939159879593635
               29746152185502371307642255121183693803580388584903
               41698116222072977186158236678424689157993532961922
               62467957194401269043877107275048102390895523597457
               23189706772547915061505504953922979530901129967519
               86188088225875314529584099251203829009407770775672
               11306739708304724483816533873502340845647058077308
               82959174767140363198008187129011875491310547126581
               97623331044818386269515456334926366572897563400500
               42846280183517070527831839425882145521227251250327
               55121603546981200581762165212827652751691296897789
               32238195734329339946437501907836945765883352399886
               75506164965184775180738168837861091527357929701337
               62177842752192623401942399639168044983993173312731
               32924185707147349566916674687634660915035914677504
               99518671430235219628894890102423325116913619626622
               73267460800591547471830798392868535206946944540724
               76841822524674417161514036427982273348055556214818
               97142617910342598647204516893989422179826088076852
               87783646182799346313767754307809363333018982642090
               10848802521674670883215120185883543223812876952786
               71329612474782464538636993009049310363619763878039
               62184073572399794223406235393808339651327408011116
               66627891981488087797941876876144230030984490851411
               60661826293682836764744779239180335110989069790714
               85786944089552990653640447425576083659976645795096
               66024396409905389607120198219976047599490197230297
               64913982680032973156037120041377903785566085089252
               16730939319872750275468906903707539413042652315011
               94809377245048795150954100921645863754710598436791
               78639167021187492431995700641917969777599028300699
               15368713711936614952811305876380278410754449733078
               40789923115535562561142322423255033685442488917353
               44889911501440648020369068063960672322193204149535
               41503128880339536053299340368006977710650566631954
               81234880673210146739058568557934581403627822703280
               82616570773948327592232845941706525094512325230608
               22918802058777319719839450180888072429661980811197
               77158542502016545090413245809786882778948721859617
               72107838435069186155435662884062257473692284509516
               20849603980134001723930671666823555245252804609722
               53503534226472524250874054075591789781264330331690
               ))

(defn sum-of-big-numbers []
  (apply str (take 10 (format "%d" (reduce + numbers)))))

;; (sum-of-big-numbers)
;; "5537376230"

;}}}
;{{{ problem 14 -- collatz

;; The following iterative sequence is defined for the set of positive integers:

;; n  n/2 (n is even)
;; n  3n + 1 (n is odd)

;; Using the rule above and starting with 13, we generate the following sequence:
;; 13  40  20  10  5  16  8  4  2  1
;; It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

;; Which starting number, under one million, produces the longest chain?

;; NOTE: Once the chain starts the terms are allowed to go above one million.

(defn max-count
  ([a] a)
  ([a b] (if (> (count a) (count b)) a b)))

(defn collatz [n]
  (take-while #(> % 1)
              (iterate
               #(if (zero? (rem % 2))
                  (/ % 2)
;;                   (/ (+ (* % 3) 1) 2)   ;This will cut off the same number of iterations so the longest will still be the longest
                  (+ (* % 3) 1)
                  )
               n)))

(defn longest-collatz [n]
  (reduce max-count (map collatz (range 1 (+ 1 n)))))

;; (longest-collatz 1000000)
;; (837799 2513398 1256699 3770098 1885049 5655148 2827574 1413787 4241362 2120681 6362044 3181022 1590511 4771534 2385767 7157302 3578651 10735954 5367977 16103932 8051966 4025983 12077950 6038975 18116926 9058463 27175390 13587695 40763086 20381543 61144630 30572315 91716946 45858473 137575420 68787710 34393855 103181566 51590783 154772350 77386175 232158526 116079263 348237790 174118895 522356686 261178343 783535030 391767515 1175302546 587651273 1762953820 881476910 440738455 1322215366 661107683 1983323050 991661525 2974984576 1487492288 743746144 371873072 185936536 92968268 46484134 23242067 69726202 34863101 104589304 52294652 26147326 13073663 39220990 19610495 58831486 29415743 88247230 44123615 132370846 66185423 198556270 99278135 297834406 148917203 446751610 223375805 670127416 335063708 167531854 83765927 251297782 125648891 376946674 188473337 565420012 282710006 141355003 424065010 212032505 636097516 318048758 159024379 477073138 238536569 715609708 357804854 178902427 536707282 268353641 805060924 402530462 201265231 603795694 301897847 905693542 452846771 1358540314 679270157 2037810472 1018905236 509452618 254726309 764178928 382089464 191044732 95522366 47761183 143283550 71641775 214925326 107462663 322387990 161193995 483581986 241790993 725372980 362686490 181343245 544029736 272014868 136007434 68003717 204011152 102005576 51002788 25501394 12750697 38252092 19126046 9563023 28689070 14344535 43033606 21516803 64550410 32275205 96825616 48412808 24206404 12103202 6051601 18154804 9077402 4538701 13616104 6808052 3404026 1702013 5106040 2553020 1276510 638255 1914766 957383 2872150 1436075 4308226 2154113 6462340 3231170 1615585 4846756 2423378 1211689 3635068 1817534 908767 2726302 1363151 4089454 2044727 6134182 3067091 9201274 4600637 13801912 6900956 3450478 1725239 5175718 2587859 7763578 3881789 11645368 5822684 2911342 1455671 4367014 2183507 6550522 3275261 9825784 4912892 2456446 1228223 3684670 1842335 5527006 2763503 8290510 4145255 12435766 6217883 18653650 9326825 27980476 13990238 6995119 20985358 10492679 31478038 15739019 47217058 23608529 70825588 35412794 17706397 53119192 26559596 13279798 6639899 19919698 9959849 29879548 14939774 7469887 22409662 11204831 33614494 16807247 50421742 25210871 75632614 37816307 113448922 56724461 170173384 85086692 42543346 21271673 63815020 31907510 15953755 47861266 23930633 71791900 35895950 17947975 53843926 26921963 80765890 40382945 121148836 60574418 30287209 90861628 45430814 22715407 68146222 34073111 102219334 51109667 153329002 76664501 229993504 114996752 57498376 28749188 14374594 7187297 21561892 10780946 5390473 16171420 8085710 4042855 12128566 6064283 18192850 9096425 27289276 13644638 6822319 20466958 10233479 30700438 15350219 46050658 23025329 69075988 34537994 17268997 51806992 25903496 12951748 6475874 3237937 9713812 4856906 2428453 7285360 3642680 1821340 910670 455335 1366006 683003 2049010 1024505 3073516 1536758 768379 2305138 1152569 3457708 1728854 864427 2593282 1296641 3889924 1944962 972481 2917444 1458722 729361 2188084 1094042 547021 1641064 820532 410266 205133 615400 307700 153850 76925 230776 115388 57694 28847 86542 43271 129814 64907 194722 97361 292084 146042 73021 219064 109532 54766 27383 82150 41075 123226 61613 184840 92420 46210 23105 69316 34658 17329 51988 25994 12997 38992 19496 9748 4874 2437 7312 3656 1828 914 457 1372 686 343 1030 515 1546 773 2320 1160 580 290 145 436 218 109 328 164 82 41 124 62 31 94 47 142 71 214 107 322 161 484 242 121 364 182 91 274 137 412 206 103 310 155 466 233 700 350 175 526 263 790 395 1186 593 1780 890 445 1336 668 334 167 502 251 754 377 1132 566 283 850 425 1276 638 319 958 479 1438 719 2158 1079 3238 1619 4858 2429 7288 3644 1822 911 2734 1367 4102 2051 6154 3077 9232 4616 2308 1154 577 1732 866 433 1300 650 325 976 488 244 122 61 184 92 46 23 70 35 106 53 160 80 40 20 10 5 16 8 4 2)

;}}}
;{{{ problem 15 -- grid routes

;; Starting in the top left corner of a 2x2 grid, there are 6 routes
;; (without backtracking) to the bottom right corner.

;; How many routes are there through a 20x20 grid?

(defn factorial [x]
  (reduce * (range 1 (+ x 1))))

(defn choose [a b]
  (/ (factorial a) (factorial b) (factorial (- a b))))

(defn pascal [a b]
  (choose (+ a b) a)) ; or b

(defn pascal [a b]
  (/ (factorial (+ a b)) (factorial a) (factorial b)))

;; (pascal 20 20)
;; 137846528820

;}}}
;{{{ problem 16 -- sum of digits of 2^1000

;; 2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.

;; What is the sum of the digits of the number 2^1000?

(defn to-digits [number]
  (map #(parse-integer (str %))
       (format "%d" number)))

(defn sum-of-digits [n]
  (reduce + (to-digits n)))

;; (sum-of-digits (bit-shift-left 1 1000))
;; 1366

;}}}
;{{{ problem 17 -- letters to write words

;; If the numbers 1 to 5 are written out in words: one, two, three
;; four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in
;; total.

;; If all the numbers from 1 to 1000 (one thousand) inclusive were
;; written out in words, how many letters would be used?

;; NOTE: Do not count spaces or hyphens. For example, 342 (three
;; hundred and forty-two) contains 23 letters and 115 (one hundred and
;; fifteen) contains 20 letters. The use of "and" when writing out
;; numbers is in compliance with British usage.
(def number-to-word-list {0 ""
                          1 "one"
                          2 "two"
                          3 "three"
                          4 "four"
                          5 "five"
                          6 "six"
                          7 "seven"
                          8 "eight"
                          9 "nine"

                          10 "ten"
                          11 "eleven"
                          12 "twelve"
                          13 "thirteen"
                          14 "fourteen"
                          15 "fifteen"
                          16 "sixteen"
                          17 "seventeen"
                          18 "eighteen"
                          19 "nineteen"

                          20 "twenty"
                          30 "thirty"
                          40 "forty"
                          50 "fifty"
                          60 "sixty"
                          70 "seventy"
                          80 "eighty"
                          90 "ninety"


                          ;; This needs to be one hundred
                          :hundred "hundred"
                          :and "and"
                          1000 "onethousand" ;hard code this one (though it's cheap)
                          })


(defn num2letters [n]
  (cond (number-to-word-list n)
          (number-to-word-list n)
        (< n 100)
          (let [ones (rem n 10)]
            (concat (num2letters (- n ones))
                    (num2letters ones)))
        (< n 1000)
          (let [tens (rem n 100)
                hundreds (quot n 100)]
            (concat (number-to-word-list hundreds)
                    (number-to-word-list :hundred)
                    (if (zero? (count (num2letters tens))) "" (number-to-word-list :and))
                    (num2letters tens)))))

(defn count-num-letters [n]
  (count (apply str (mapcat num2letters (range 1 (inc n))))))

(defn count-num-letters-2 [n]
  (reduce + (map count (map num2letters (range 1 (inc n))))))

;; (count-num-letters 1000)
;; 21124

;}}}
;{{{ problem 18 -- triangle path maximizing

;; By starting at the top of the triangle below and moving to adjacent numbers on the row below, the maximum total from top to bottom is 23.

;; 3
;; 7 5
;; 2 4 6
;; 8 5 9 3

;; That is, 3 + 7 + 4 + 9 = 23.

;; Find the maximum total from top to bottom of the triangle below:
(def path-triangle '((75)
                     (95 64)
                     (17 47 82)
                     (18 35 87 10)
                     (20  4 82 47 65)
                     (19  1 23 75  3 34)
                     (88  2 77 73  7 63 67)
                     (99 65  4 28  6 16 70 92)
                     (41 41 26 56 83 40 80 70 33)
                     (41 48 72 33 47 32 37 16 94 29)
                     (53 71 44 65 25 43 91 52 97 51 14)
                     (70 11 33 28 77 73 17 78 39 68 17 57)
                     (91 71 52 38 17 14 91 43 58 50 27 29 48)
                     (63 66  4 68 89 53 67 30 73 16 69 87 40 31)
                     ( 4 62 98 27 23  9 70 98 73 93 38 53 60  4 23)
                     ))
;; NOTE: As there are only 16384 routes, it is possible to solve this
;; problem by trying every route. However, Problem 67, is the same
;; challenge with a triangle containing one-hundred rows; it cannot be
;; solved by brute force, and requires a clever method! ;o)

(defn path-helper [accum triangle]
  (if (nil? triangle)
    (apply max accum)
    (let [;prev (cons 0 accum)
          next (first triangle)
          bob  (for [x (range (count next))]
                 (+ (nth next x)
                    (max (nth accum (- x 1) 0) (nth accum x 0))))] ; nth with out of bounds
      (recur bob (rest triangle)))))

;; (path-helper nil path-triangle)
;; 1074

;}}}
;{{{ problem 19 -- Sundays the first in 1900's

;; You are given the following information, but you may prefer to do
;; some research for yourself.

;; 1 Jan 1900 was a Monday.
;; Thirty days has September
;; April, June and November.
;; All the rest have thirty-one
;; Saving February alone
;; Which has twenty-eight, rain or shine.
;; And on leap years, twenty-nine.

;; A leap year occurs on any year evenly divisible by 4, but not on a
;; century unless it is divisible by 400.

;; How many Sundays fell on the first of the month during the
;; twentieth century (1 Jan 1901 to 31 Dec 2000)?

(defn print-date [calendar]
  (let [formatter (. DateFormat getDateInstance)]
    (prn (. formatter (format (. calendar getTime))))))


(defn sunday-the-firsts [start end accum]
;;   (print-date start)
  (let [is-sunday (=  (. start (get (. GregorianCalendar DAY_OF_WEEK)))
                      (. GregorianCalendar SUNDAY))
        new-accum (if is-sunday (inc accum) accum)]
    (cond (> (. start (compareTo end)) 0)
          accum
          (zero? (. start (compareTo end)))
          new-accum
          :else
          (do (. start (add (. GregorianCalendar MONTH) 1))
              (recur start end new-accum)))))

(defn century-sundays []
  (let [start (GregorianCalendar. 1901  0  1)
        end   (GregorianCalendar. 2000 11 31)]
;;     (print-date start)
;;     (print-date end)
    (sunday-the-firsts start end 0)))

;; (century-sundays)
;; 171

;}}}
;{{{ problem 20 -- sum of digits in 100!

;; n! means n  (n  1)  ...  3  2  1

;; Find the sum of the digits in the number 100!

;; (sum-of-digits (factorial 100))
;; 648


;}}}
;{{{ problem 21 -- amicable numbers

;; Let d(n) be defined as the sum of proper divisors of n (numbers
;; less than n which divide evenly into n).

;; If d(a) = b and d(b) = a, where a b, then a and b are an amicable
;; pair and each of a and b are called amicable numbers.

;; For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20
;; 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of
;; 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

;; Evaluate the sum of all the amicable numbers under 10000.
(defn proper-divisors [n]
  (filter #(zero? (rem n %)) (range 1 (+ 1 (/ n 2)))))

(defn divisors [n]
  (cons n proper-divisors))

(defn amicable-partner [x]
  (reduce + (proper-divisors x)))

(defn perfect? [x]
  (= (amicable-partner x) x))

(defn amicable? [x]
  (and (= (amicable-partner (amicable-partner x)) x)
       (not= (amicable-partner x) x)))

(defn amicable-sum [n]
  (reduce + 0 (filter amicable? (range 1 n))))

;; (amicable-sum 10000)
;; 31626

;}}}
;{{{ problem 22 -- name scores

;; Using names.txt (right click and 'Save Link/Target As...'), a 46K
;; text file containing over five-thousand first names, begin by
;; sorting it into alphabetical order. Then working out the
;; alphabetical value for each name, multiply this value by its
;; alphabetical position in the list to obtain a name score.

;; For example, when the list is sorted into alphabetical order
;; COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name
;; in the list. So, COLIN would obtain a score of 938 53 = 49714.

;; What is the total of all the name scores in the file?
(defn char2num [char]
  (let [i (int char)
        a (int \a)
        A (int \A)
        off (- i a)
        Off (- i A)
        modulus (if (< off 0) Off off)]
    (inc modulus)))

(defn word2num [word]
  (reduce + (map char2num word)))

(defn name-scores [file]
  (reduce +
          (map *
               (map word2num (sort (re-seq #"\w+" (slurp file))))
               (iterate inc 1))))

;; (name-scores "names.txt")
;; 871198282

;}}}
;{{{ problem 23 -- abundant numbers

;; A perfect number is a number for which the sum of its proper
;; divisors is exactly equal to the number. For example, the sum of
;; the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which
;; means that 28 is a perfect number.

;; A number whose proper divisors are less than the number is called
;; deficient and a number whose proper divisors exceed the number is
;; called abundant.

;; As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the
;; smallest number that can be written as the sum of two abundant
;; numbers is 24. By mathematical analysis, it can be shown that all
;; integers greater than 28123 can be written as the sum of two
;; abundant numbers. However, this upper limit cannot be reduced any
;; further by analysis even though it is known that the greatest
;; number that cannot be expressed as the sum of two abundant numbers
;; is less than this limit.

;; Find the sum of all the positive integers which cannot be written
;; as the sum of two abundant numbers.

(defn abundant? [n]
  (> (amicable-partner n) n))

(def abundant-numbers
     (filter abundant? (iterate inc 1)))

(defn sorted-intersect? [seq1 seq2]
  (let [f1 (first seq1)
        f2 (first seq2)]
    (cond
     (or (nil? f1) (nil? f2))
     nil
     (= f1 f2)
     f1
     (< f1 f2)
      (recur (rest seq1) seq2)
     (> f1 f2)
      (recur seq1 (rest seq2)))))


(defn sum-of-abundants? [n]
  (sorted-intersect? abundant-numbers
                     (reverse (take-while #(> % 0)
                                          (map #(- n %)
                                               abundant-numbers)))))

(defn sum-of-non-abundant-sums []
  (reduce + 0 (filter (complement sum-of-abundants?);#(not (sum-of-abundants? %))
                      (range 1 28124))))

;; (sum-of-non-abundant-sums)
;; 4179871

;}}}
;{{{ problem 24 -- lexigraphic permutations

;; A permutation is an ordered arrangement of objects. For example
;; 3124 is one possible permutation of the digits 1, 2, 3 and 4. If
;; all of the permutations are listed numerically or alphabetically
;; we call it lexicographic order. The lexicographic permutations of
;; 0, 1 and 2 are:

;; 012   021   102   120   201   210

;; What is the millionth lexicographic permutation of the digits 0, 1
;; 2, 3, 4, 5, 6, 7, 8 and 9?

(defn nth-lexigraphic-permutation [n seq]
  (if (or (nil? seq)
          (zero? n))
    seq
    (let [num-perms-lower (factorial (dec (count seq)))
          dividend (quot n num-perms-lower)
          remainder (rem n num-perms-lower)
          head (nth seq dividend)
          tail (filter #(not= head %) seq)]
      (cons head (nth-lexigraphic-permutation remainder tail))))) ; not a tail call, though it would be easy to make it such

;; (apply str (nth-lexigraphic-permutation 999999 "0123456789"))
;; "2783915460"

;}}}
;{{{ problem 25 -- Fibonacci

;; The Fibonacci sequence is defined by the recurrence relation:

;; Fn = Fn1 + Fn2, where F1 = 1 and F2 = 1.
;; Hence the first 12 terms will be:

;; F1 = 1
;; F2 = 1
;; F3 = 2
;; F4 = 3
;; F5 = 5
;; F6 = 8
;; F7 = 13
;; F8 = 21
;; F9 = 34
;; F10 = 55
;; F11 = 89
;; F12 = 144
;; The 12th term, F12, is the first term to contain three digits.

;; What is the first term in the Fibonacci sequence to contain 1000 digits?

(def fibonacci-numbers
     (map first (iterate #(list (frest %) (reduce + %))
                         '(1 1))))

(defn first-where [pred seq]
  (cond (nil? seq)
          seq
        (pred (first seq))
          (first seq)
        :else
          (recur pred (rest seq))))

(defn first-fib-with-n-digits [n]
  (first-where #(>= (count (format "%s" %)) n)
               fibonacci-numbers))

(defn which-fib-with-n-digits [n]
  (+ 1 (count (take-while #(< (count (format "%s" %)) n)
                          fibonacci-numbers))))

;; (which-fib-with-n-digits 1000)
;; 4782

;}}}
;{{{ problem 26 -- repeating decimals

;; A unit fraction contains 1 in the numerator. The decimal
;; representation of the unit fractions with denominators 2 to 10 are
;; given:

;; 1/2  = 0.5
;; 1/3  = 0.(3)
;; 1/4  = 0.25
;; 1/5  = 0.2
;; 1/6  = 0.1(6)
;; 1/7  = 0.(142857)
;; 1/8  = 0.125
;; 1/9  = 0.(1)
;; 1/10 = 0.1

;; Where 0.1(6) means 0.166666..., and has a 1-digit recurring cycle. It
;; can be seen that 1/7 has a 6-digit recurring cycle.

;; Find the value of d < 1000 for which 1/d contains the longest recurring
;; cycle in its decimal fraction part.

;; (filter #(not (zero? (rem 10000000 %)))
;;         (range 1 1000))

;; (defn num-repeating-digits [n]
;;   (if (zero? (rem 10000000 %))
;;     nil
;;     ))

(defn int? [x]
  (zero? (rem x 1)))

(defn num-repeating-decimals
  ([x]
     (num-repeating-decimals x 10))
  ([x mult]
     (cond (int? (* x mult))
             0
           (int? (* x (dec mult)))
             (dec (count (to-digits mult))) ; (int (Math/log10 mult))
           (int? (* x mult (dec mult))) ; This will ensure that I actually find the smallest, i.e. 0.1234567_34_ (where the 34 repeats) will give
             (recur (* mult x) 10)
           :else
             (recur x (* 10 mult)))))

(defn max-first
  ([x] x)
  ([x y] (if (< (first x) (first y)) y x))
  ([x y & more] (reduce max-first (max-first x y) more))
  )

(defn find-repeating-decimals [n]
  (reduce max-first
          (map #(list (num-repeating-decimals (/ %)) %)
                         (range 1 n))))

;; (find-repeating-decimals 1000)
;; (982 983)

;}}}
;{{{ problem 27 -- quadratic prime generator

;; Euler published the remarkable quadratic formula:

;; n² + n + 41

;; It turns out that the formula will produce 40 primes for the
;; consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41
;; = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41
;; 41² + 41 + 41 is clearly divisible by 41.

;; Using computers, the incredible formula n² - 79n + 1601 was discovered
;; which produces 80 primes for the consecutive values n = 0 to 79. The
;; product of the coefficients, -79 and 1601, is -126479.

;; Considering quadratics of the form:

;; n² + an + b, where |a|  1000 and |b|  1000

;; where |n| is the modulus/absolute value of n
;; e.g. |11| = 11 and |-4| = 4

;; Find the product of the coefficients, a and b, for the quadratic
;; expression that produces the maximum number of primes for
;; consecutive values of n, starting with n = 0.

(defn isprime?-1 [n]
  (= 1 (count (factors n))))

(def isprime? isprime?-1)

(defn isprime?-2 [n]
  (filter #(= % n) (take-while #(<= % n) primes)))

(defn isprime?-3
  ([n] (isprime? n primes))
  ([n seq] (cond (= n (first seq))
                   n
                 (< n (first seq))
                   nil
                 :else
                   (recur n (rest seq)))))

(defn isprime?-4 [n]
  (let [max (Math/sqrt n)]
    (and (not= n 1)
         (not (some #(zero? (rem n %))
                    (take-while #(<= % max) primes))))))

(def isprime? isprime?-4)

;; This one isn't really a true test (I don't think)
;; (defn isprime? [n]
;;   (= 1 (count (factors (abs n)))))

(defn primes-generated [a b]
  (take-while isprime?
              (map #(+ (* % % ) (* a %) b)
                   (range b))))

(defn num-primes-generated [a b]
  (count (primes-generated a b)))

(defn test-quadratic [n]
  (reduce max-first
          (for [a (range (- 1 n) n)
                ;;         b (range (- 1 n) n)
                b (take-while #(< % n) primes)
                ]
            (list (num-primes-generated a b) a b))))

(defn test-quadratic [n]
  (reduce * (rest
             (reduce max-first
                     (for [a (range (- 1 n) n)
                           ;;         b (range (- 1 n) n)
                           b (take-while #(< % n) primes)
                           ]
                       (list (num-primes-generated a b) a b))))))

;; (test-quadratic 1000)
;; -59231

;}}}
;{{{ problem 28 -- spiral product

;; Starting with the number 1 and moving to the right in a clockwise
;; direction a 5 by 5 spiral is formed as follows:

;; 21 22 23 24 25
;; 20  7  8  9 10
;; 19  6  1  2 11
;; 18  5  4  3 12
;; 17 16 15 14 13

;; It can be verified that the sum of both diagonals is 101.

;; What is the sum of both diagonals in a 1001 by 1001 spiral formed
;; in the same way?

;; we have 1, +2,+2,+2,+2, +4,+4,+4,+4, etc.

(defn spiral-product-helper [cur sum i limit]
  (if (> i limit)
    sum
    (recur (+ cur (* 8 i))
           (+ sum (* 4 cur) (* 20 i))
           (inc i)
           limit)))

;; size must be odd
(defn spiral-product [size]
  (spiral-product-helper 1 1 1 (/ (- size 1) 2)))

;; (spiral-product 1001)
;; 669171001

;}}}
;{{{ problem 29 -- integer combinations

;; Consider all integer combinations of a^b for 2 <= a <= 5 and 2 <= b <= 5:

;;  2^2=4,  2^3=8,   2^4=16,  2^5=32
;;  3^2=9,  3^3=27,  3^4=81,  3^5=243
;;  4^2=16, 4^3=64,  4^4=256, 4^5=1024
;;  5^2=25, 5^3=125, 5^4=625, 5^5=3125

;; If they are then placed in numerical order, with any repeats
;; removed, we get the following sequence of 15 distinct terms:

;; 4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125

;; How many distinct terms are in the sequence generated by ab for 2 a
;; 100 and 2 b 100?

(defn big-integer-pow [a b]
  (. (. java.math.BigInteger (valueOf a)) (pow b)))

(defn num-integer-combinations [n]
  (count (set
          (for [a (range 2 (+ 1 n))
                b (range 2 (+ 1 n))]
            (big-integer-pow a b)))))

;; (num-integer-combinations 100)
;; 9183

;}}}
;{{{ problem 30 -- sums of 5th powers

;; Surprisingly there are only three numbers that can be written as
;; the sum of fourth powers of their digits:

;; 1634 = 14 + 64 + 34 + 44
;; 8208 = 84 + 24 + 04 + 84
;; 9474 = 94 + 44 + 74 + 44
;; As 1 = 14 is not a sum it is not included.

;; The sum of these numbers is 1634 + 8208 + 9474 = 19316.

;; Find the sum of all the numbers that can be written as the sum of
;; fifth powers of their digits.



;; 6*9^5 = 354294 < 999999 so they must be less than 354294
(defn fourth-power? [n]
  (= n (reduce + (map #(* % % % %) (to-digits n)))))

(defn fifth-power? [n]
  (= n (reduce + (map #(* % % % % %) (to-digits n)))))

;; (reduce + (filter fourth-power? (range 2 354294)))
;; 19316

;; (reduce + (filter fifth-power? (range 2 354294)))
;; 443839

;}}}
;{{{ problem 31 -- currency

;; In England the currency is made up of pound, £, and pence, p, and
;; there are eight coins in general circulation:

;; 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p).

(def denominations '(200 100 50 20 10 5 2 1))

;; It is possible to make £2 in the following way:

;; 1£1 + 150p + 220p + 15p + 12p + 31p
;; How many different ways can £2 be made using any number of coins?

(defn coins [value denominations]
;;   (println value denominations (range (inc (/ value (first denominations)))))
;;   (println )
  (cond
   (< value 0)
     0
   (= value 0)
     1
   (= 1 (count denominations))
     1
   :else
     (reduce + (map #(coins (- value (* % (first denominations)))
                            (rest denominations))
                    (range (inc (/ value (first denominations))))))))

;; (coins 200 denominations)
;; 73682

;}}}
;{{{ problem 32 -- pandigital numbers

;; We shall say that an n-digit number is pandigital if it makes use
;; of all the digits 1 to n exactly once; for example, the 5-digit
;; number, 15234, is 1 through 5 pandigitial.

;; The product 7254 is unusual, as the identity, 39 * 186 = 7254
;; containing multiplicand, multiplier, and product is 1 through 9
;; pandigital.

;; Find the sum of all products whose multiplicand/multiplier/product
;; identity can be written as a 1 through 9 pandigital.

;; HINT: Some products can be obtained in more than one way so be sure
;; to only include it once in your sum.

(defn pandigital? [& more]
  (let [digits (mapcat to-digits more)
        c (count digits)
        needed-digits (range 1 (inc c))]
    (= needed-digits (sort digits))))

(defn pandigital-09? [& more]
  (let [digits (mapcat to-digits more)
        c (count digits)
        needed-digits (range (inc c))]
    (= needed-digits (sort digits))))

(defn x-pandigital? [x & more]
  (let [digits (mapcat to-digits more)
        needed-digits (range 1 (inc x))]
    (= needed-digits (sort digits))))

(defn pandigital-9-product []
  (reduce + (distinct (map first
                           (filter #(apply x-pandigital? 9 %)
                                   (for [x (range 1 100)
                                         y (range x 10000)]
                                     (list (* x y) x y)))))))

;}}}
;{{{ problem 33 -- weird cancelling fractions

;; The fraction 49/98 is a curious fraction, as an inexperienced
;; mathematician in attempting to simplify it may incorrectly believe
;; that 49/98 = 4/8, which is correct, is obtained by cancelling the
;; 9s.

;; We shall consider fractions like, 30/50 = 3/5, to be trivial
;; examples.

;; There are exactly four non-trivial examples of this type of
;; fraction, less than one in value, and containing two digits in the
;; numerator and denominator.

;; If the product of these four fractions is given in its lowest
;; common terms, find the value of the denominator.

(defn weird-cancelling-fractions []
  (reduce *
          (for [x (range 10)
                y (range 1 10)
                z (range 1 10)]
            (let [num (+ (* 10 x) y)
                  denom (+ (* 10 y) z)
                  reduced (/ x z)]
              (if (= reduced (/ num denom))
                reduced
                1)))))

;; (weird-cancelling-fractions)
;; 1/100

;}}}
;{{{ problem 34 -- sums of factorials

;; 145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.

;; Find the sum of all numbers which are equal to the sum of the factorial of their digits.

;; Note: as 1! = 1 and 2! = 2 are not sums they are not included.

;; user> (factorial 9)
;; 362880
;; user> (* 7 (factorial 9))
;; 2540160
;; user> (* 8 (factorial 9))
;; 2903040

;; so they must be less than 2540160
(defn sum-of-factorials? [n]
  (= n (reduce + (map factorial (to-digits n)))))

;; (reduce + (filter sum-of-factorials? (range 3 2540160)))
;; 40730

;}}}
;{{{ problem 35 -- circular primes

;; The number, 197, is called a circular prime because all rotations
;; of the digits: 197, 971, and 719, are themselves prime.

;; There are thirteen such primes below 100: 2, 3, 5, 7, 11, 13, 17
;; 31, 37, 71, 73, 79, and 97.

;; How many circular primes are there below one million?

(defn next-circular [n]
  (parse-integer (format "%d%d" (rem n 10) (quot n 10))))

(defn circulars [n]
  (take (count (format "%d" n))
        (iterate next-circular n)))

(defn primes-below [n]
  (take-while #(< % n) primes))

(defn circular-primes [n]
  (count (distinct
          (filter #(every? isprime? (circulars %))
                  (primes-below n)))))

;; (circular-primes 1000000)
;; 55

;}}}
;{{{ problem 36 -- base 10 and 2 palindromes

;; The decimal number, 585 = 10010010012 (binary), is palindromic in
;; both bases.

;; Find the sum of all numbers, less than one million, which are
;; palindromic in base 10 and base 2.

;; (Please note that the palindromic number, in either base, may not
;; include leading zeros.)

(defn to-binary-digits
  ([n] (to-binary-digits n nil))
  ([n accum]  (if (zero? n)
                accum
                (recur (bit-shift-right n 1) (cons (bit-and n 1) accum)))))

(defn base-2-palindrome? [x]
  (cond (zero? (bit-and x 1))
          nil
        :else
          (let [bin-digits (to-binary-digits x)
                rev-digits (reverse bin-digits)]
            (= bin-digits rev-digits))))

(defn sum-of-palindromes [n]
  (reduce + (filter base-2-palindrome?
                    (filter palindrome? (range n)))))

;; (sum-of-palindromes 1000000)
;; 872187

;}}}
;{{{ problem 37 -- truncatable primes

;; The number 3797 has an interesting property. Being prime itself, it
;; is possible to continuously remove digits from left to right, and
;; remain prime at each stage: 3797, 797, 97, and 7. Similarly we can
;; work from right to left: 3797, 379, 37, and 3.

;; Find the sum of the only eleven primes that are both truncatable
;; from left to right and right to left.

;; NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

(defn left-truncations [x]
  (take-while (complement zero?)
              (iterate #(quot % 10) x)))

(defn right-truncations [x]
  (take-while #(not= x %)
              (map #(rem x %)
                   (iterate #(* 10 %) 10))))

(defn truncations [x]
  (concat (left-truncations x) (right-truncations x)))

(defn truncatable-prime? [x]
  (every? isprime? (truncations x)))

(defn truncatable-primes []
  (reduce + (take 11 (filter truncatable-prime? (drop 4 primes)))))


;; (truncatable-primes)
;; 748317

;}}}
;{{{ problem 38 -- pandigital products

;; Take the number 192 and multiply it by each of 1, 2, and 3:

;; 192  1 = 192
;; 192  2 = 384
;; 192  3 = 576

;; By concatenating each product we get the 1 to 9 pandigital
;; 192384576. We will call 192384576 the concatenated product of 192
;; and (1,2,3)

;; The same can be achieved by starting with 9 and multiplying by 1
;; 2, 3, 4, and 5, giving the pandigital, 918273645, which is the
;; concatenated product of 9 and (1,2,3,4,5).

;; What is the largest 1 to 9 pandigital 9-digit number that can be
;; formed as the concatenated product of an integer with (1,2, ... n)
;; where n > 1?

(defn int-concat [& rest]
  (parse-integer (apply str (mapcat #(format "%d" %) rest))))

(defn big-int-concat [& rest]
  (parse-big-integer (apply str (mapcat #(format "%d" %) rest))))

(defn x-pandigital-products [x-pandigital]
  (reduce max (map #(apply int-concat %)
                   (filter #(apply x-pandigital? x-pandigital %)
                           (apply concat
                                  (for [n (range 2 5)]
                                    (let [max-digits (quot x-pandigital n)
                                          max-num (Math/pow 10 max-digits)]
                                      (for [y (range 1 max-num)]
                                        (map #(* y %) (range 1 (inc n)))))))))))

;; (x-pandigital-products 9)
;; 932718654

;}}}
;{{{ problem 39 -- right triangle perimeters

;; If p is the perimeter of a right angle triangle with integral
;; length sides, {a,b,c}, there are exactly three solutions for p =
;; 120.

;; {20,48,52}, {24,45,51}, {30,40,50}

;; For which value of p <= 1000, is the number of solutions maximised?
(defn max-first
  ([a] a)
  ([a b] (if (< (first a) (first b)) b a)))


(defn num-right-triangles [p]
  (reduce + (for [a (range 1 (dec p))
                  b (range 1 a)]
              (let [c (- p a b)]
                (if (= (+ (* a a) (* b b)) (* c c))
                  1 0)))))

(defn perimeter-with-max-right-triangles [n]
  (reduce max-first
          (map #(list (num-right-triangles %) %)
               (range 3 (inc n)))))

;; (perimeter-with-max-right-triangles 1000)
;; (8 840)

;}}}
;{{{ problem 40 -- irrational digits

;; An irrational decimal fraction is created by concatenating the positive integers:

;; 0.123456789101112131415161718192021...

;; It can be seen that the 12th digit of the fractional part is 1.

;; If dn represents the nth digit of the fractional part, find the
;; value of the following expression.

;; d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000

(def that-irrational-number
     (lazy-cons '.
                ((fn this[n]
                   (lazy-cat (to-digits n) (this (inc n)))) 1)))

(defn product-of-10powers [n]
  (take n (map #(nth that-irrational-number %)
               (iterate #(* 10 %) 10))))

(defn product-of-10powers-2 [n]
  (reduce * (take n (map #(nth (lazy-cons '. ((fn this[n]
                                                (lazy-cat (to-digits n) (this (inc n)))) 1))
                               %)
                         (iterate #(* 10 %) 1)))))

;; (product-of-10powers 7)
;; (1 1 5 3 7 2 1)

;; (take n  (iterate #(* 10 %) 1))

;}}}
;{{{ problem 41 -- pandigital primes

;; We shall say that an n-digit number is pandigital if it makes use
;; of all the digits 1 to n exactly once. For example, 2143 is a
;; 4-digit pandigital and is also prime.

;; What is the largest n-digit pandigital prime that exists?

(defn largest-pandigital-prime []
  (reduce max (filter pandigital? (primes-below 1000000000))))

;; There's a better way to do this --
(defn permutations [seq]
  (let [c (factorial (count seq))]
    (for [x (range c)]
      (nth-lexigraphic-permutation x seq))))

(defn permutations [seq]
  ;;   (prn 'seq seq)
  (if (= 1 (count seq))
    (list seq)
    (apply concat (for [x seq]
                    (do
                      ;;         (prn 'x x)
                      (let [tail (filter #(not= x %) seq)]
                        ;;         (prn 'tail tail 'perm (permutations tail))
                        (map #(cons x %)
                             (permutations tail))))))))


(def pandigitals
     (map #(apply int-concat %)
          (mapcat #(permutations %)
                  (map #(take % '(1 2 3 4 5 6 7 8 9))
                       (range 1 10)))))

(defn largest-pandigital-prime-2 []
  (reduce max (filter isprime? pandigitals)))

;; (largest-pandigital-prime-2)
;; 7652413

;}}}
;{{{ problem 42 -- triangle words

;; The nth term of the sequence of triangle numbers is given by, tn =
;; ½n(n+1); so the first ten triangle numbers are:

;; 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...

;; By converting each letter in a word to a number corresponding to
;; its alphabetical position and adding these values we form a word
;; value. For example, the word value for SKY is 19 + 11 + 25 = 55 =
;; t_10. If the word value is a triangle number then we shall call the
;; word a triangle word.

;; Using words.txt (right click and 'Save Link/Target As...'), a 16K
;; text file containing nearly two-thousand common English words, how
;; many are triangle words?

(defn file-lines [file-name]
  (line-seq (BufferedReader. (FileReader. file-name))))

;; ((take 3 (file-lines "words.txt")))
;; (read (concat "'(" (slurp "words.txt") ")"))

(defn triangular? [T]
  (let [D   (+ 1 (* 8 T))
        num (+ -1 (Math/sqrt D))]
    (zero? (rem num 2))))

(defn triangle-words [file]
  (count (filter triangular?
                 (map word2num
                      (re-seq #"\w+" (slurp file))))))

;; (triangle-words "words.txt")
;; 162

;}}}
;{{{ problem 43 -- pandigital substring divisibility

;; The number, 1406357289, is a 0 to 9 pandigital number because it is
;; made up of each of the digits 0 to 9 in some order, but it also has
;; a rather interesting sub-string divisibility property.

;; Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this
;; way, we note the following:

;; d2d3d4=406 is divisible by 2
;; d3d4d5=063 is divisible by 3
;; d4d5d6=635 is divisible by 5
;; d5d6d7=357 is divisible by 7
;; d6d7d8=572 is divisible by 11
;; d7d8d9=728 is divisible by 13
;; d8d9d10=289 is divisible by 17
;; Find the sum of all 0 to 9 pandigital numbers with this property.


;; TODO: make this more constructive (e.g. make a list of numbers
;; divisible by 17, 13, 11, etc. and stitch them together)

(defn substring-divisible? [n]
  (let [digits (to-digits n)]
    (every? zero?
            (map (fn [x p]
                   (rem (parse-big-integer (apply str (take 3 (nthrest digits x)))) p))
                 (range 1 8)
                 primes))))


;; The problem with all these was parse-integer!
(defn pandigital-substring []
  (take 4
;;   (reduce +
          (filter substring-divisible?
                  (map #(parse-big-integer (apply str %))
                       (drop (factorial 9) ;The first 9! are too small
                             (permutations "0123456789"))))))


(defn substring-divisible?-2 [seq]
  (and (not (zero? (first seq)))
       (every? zero?
               (map (fn [x p]
;;                       (prn x p (parse-big-integer (apply str (take 3 (nthrest seq x)))) (rem (parse-big-integer (apply str (take 3 (nthrest seq x)))) p))
                      (rem (parse-big-integer (apply str (take 3 (nthrest seq x)))) p))
                    (range 1 8)
                    primes))))

(defn pandigital-substring-2 []
;;   (reduce +
  (take 4
          (map #(apply int-concat %)
               (filter substring-divisible?-2
                       (permutations '(0 1 2 3 4 5 6 7 8 9))))))


(defn to-3-unique-digits [n]
  (let [d (to-digits n)
        c (count d)]
    (cond (= c 3)
            d
          (= c 2)
            (cons 0 d)
          :else
            nil)))

(defn make-pandigital [seq]
  (if (= 9 (count (distinct seq)))
    (list (apply big-int-concat
                 (concat (filter #(not (contains? (zipmap seq seq) %)) (range 10))
                         seq)))
    nil))

(defn prime-list-to-stuff [prime-lists accum]
  ;; I need to do something special when prime-list2 is empty
  (if (nil? prime-lists)
    (make-pandigital accum)

    (let [prime-list (first prime-lists)]
      (apply concat
             (if (nil? accum)
               (for [p prime-list]
                 (prime-list-to-stuff (rest prime-lists) p))

               (for [p prime-list :when (= (take 2 accum) (nthrest p 1))
                     ;;                 (and (not-contains? accum (first p)))
                     ]
                 (prime-list-to-stuff (rest prime-lists)
                                      (cons (first p) accum))))))))

(defn pandigital-substring-3 [n]
  (reduce +
          (let [primes '(17 13 11 7 5 3 2)
                prime-lists (for [p primes]
                              (filter #(= 3 (count (distinct %)))
                                      (map to-3-unique-digits
                                           (take-while #(< % 987)
                                                       (iterate #(+ p %) p)))))]
            (prime-list-to-stuff (take n prime-lists) nil))))


;; Actually I could do all this with no lists, just numbers, rem and a
;; multiplier (though some things would be harder)

;; (pandigital-substring)
;; 16695334890

;}}}
;{{{ problem 44 -- pentagonal numbers ******

;; Pentagonal numbers are generated by the formula, Pn=n(3n-1)/2. The
;; first ten pentagonal numbers are:

;; 1, 5, 12, 22, 35, 51, 70, 92, 117, 145, ...

;; It can be seen that P4 + P7 = 22 + 70 = 92 = P8. However, their
;; difference, 70 - 22 = 48, is not pentagonal.

;; Find the pair of pentagonal numbers, Pj and Pk, for which their sum
;; and difference is pentagonal and D = |Pk-Pj| is minimised; what is
;; the value of D?

(defn nth-pentagonal [n]
;;   (prn n)
  (* 1/2 n (dec (* 3 n))))

(def pentagonal-numbers
     ((fn this[n]
       (lazy-cons (nth-pentagonal n)
                  (this (inc n))))
      1))

(defn pentagonal? [P]
  (let [D   (+ 1 (* 24 P))
        num (+ 1 (Math/sqrt D))]
    (zero? (rem num 6))))

;; Difference between 2 pentagonal numbers is 3n+1

;; 2*P_j + D
;; This finds consecutive pentagonals, we need any pair
(defn find-consecutive-pentagonal-numbers [max]
  (take 1
;;         (filter #(every? pentagonal? %)
           (for [D pentagonal-numbers  :when (and (>= D 4) (= (rem D 3) 1))]
            (let [P2 (nth pentagonal-numbers (/ (- D 1) 3))
                  P3 (+ P2 P2 D)]
              (list D (- P2 D) P2 P3)))))


;; TODO: why is this so slow!?
(defn find-pentagonal-numbers [num]
  (nth
   ;;         (filter #(every? pentagonal? %)
   (for [D  pentagonal-numbers     ;:when (and (>= D 4))
         P2 pentagonal-numbers :while (<= P2 (nth-pentagonal (int (/ (- D 1) 3))))
         :when (and (> P2 D)
                    (pentagonal? (- P2 D))
;;                     (pentagonal? (+ P2 P2 (- D)))
                    )
         ]
;;      (list (pentagonal? (- P2 D))
;;            D (- P2 D) P2 (+ P2 P2 (- D)))
     (list (pentagonal? (+ P2 P2 (- D)))
           D (- P2 D) P2 (+ P2 P2 (- D)))
     )
   num))

;; This assumes that D < P1
(defn find-pentagonal-numbers-2 [num]
  (take num
        (apply concat ;;         (filter #(every? pentagonal? %)
               (for [D  pentagonal-numbers]
                 (let [max-pent (nth-pentagonal (int (/ (- D 1) 3)))]
                   ;;             (prn max-pent)
                   (for [P2 pentagonal-numbers
                         :while (<= P2 max-pent)
                         :when (and (> P2 D)
                                    (pentagonal? (- P2 D))
                                    ;;                                (pentagonal? (+ P2 P2 (- D)))
                                    )
                         ]
                     (list (pentagonal? (+ P2 P2 (- D)))
                           (nth pentagonal-numbers (/ (- D 1) 3))
                           D (- P2 D) P2 (+ P2 P2 (- D)))))))))


;; This is totally wrong!  Why does it give the right answer?  Luck most likely
(defn find-pentagonal-numbers-3 [num]
  (take num
        (for [P1 pentagonal-numbers
              P2 pentagonal-numbers
              :while (<= P2 P1)
              :when (and (pentagonal? (- P1 P2))
                         (pentagonal? (+ P2 P1))
                         )
              ]
          (list (- P1 P2) P2 P1 (+ P1 P2)))))

;; (find-pentagonal-numbers 1)
;;
;; (time (find-pentagonal-numbers-3 1))
;; "Elapsed time: 1035.227 msecs"
;; ((5482660 1560090 7042750 8602840))


;}}}
;{{{ problem 45 -- triangle, pentagonal and hexagonal numbers

;; Triangle, pentagonal, and hexagonal numbers are generated by the following formulae:

;; Triangle   Tn=n(n+1)/2    1, 3, 6, 10, 15, ...
;; Pentagonal Pn=n(3n-1)/2   1, 5, 12, 22, 35, ...
;; Hexagonal  Hn=n(2n-1)     1, 6, 15, 28, 45, ...
;; It can be verified that T285 = P165 = H143 = 40755.

;; Find the next triangle number that is also pentagonal and hexagonal.



(defn hexagonal? [H]
  (let [D   (+ 1 (* 8 H))
        num (+ 1 (Math/sqrt D))]
    (zero? (rem num 4))))

(defn triple-threats [n]
  (take n (filter pentagonal? (filter hexagonal? triangle-numbers))))

;; (triple-threats 3)
;; (1 40755 1533776805)

;}}}
;{{{ problem 46 -- prime + twice a square

;; It was proposed by Christian Goldbach that every odd composite
;; number can be written as the sum of a prime and twice a square.

;; 9  =  7 + 2*1^2
;; 15 =  7 + 2*2^2
;; 21 =  3 + 2*3^2
;; 25 =  7 + 2*3^2
;; 27 = 19 + 2*2^2
;; 33 = 31 + 2*1^2
;; It turns out that the conjecture was false.

;; What is the smallest odd composite that cannot be written as the
;; sum of a prime and twice a square?

(def odd-composites
     ((fn this [x]
        (if (isprime? x)
          (recur (+ 2 x))
          (lazy-cons x (this (+ 2 x)))))
      9))

;; This could be simpler
(defn is-square? [n]
  (let [x (int (Math/sqrt n))]
    (= (* x x) n)))

(defn prime-plus-2-square? [n]
  (filter is-square?
          (map #(bit-shift-right (- n %) 1)
               (primes-below n))))

(defn non-goldbachs [x]
  (take x (filter (complement prime-plus-2-square?)
                  odd-composites)))

;; (non-goldbachs 1)
;; (5777)

;}}}
;{{{ problem 47 -- four distinct prime factors

;; The first two consecutive numbers to have two distinct prime factors are:

;; 14 = 2  7
;; 15 = 3  5

;; The first three consecutive numbers to have three distinct prime factors are:

;; 644 = 2²  7  23
;; 645 = 3  5  43
;; 646 = 2  17  19.

;; Find the first four consecutive integers to have four distinct
;; primes factors.  What is the first of these numbers?

(def integer-quads
     ((fn this[num]
        (lazy-cons (range num (+ 4 num))
                   (this (inc num))))
      1))

(defn distinct-prime-factors [n]
  (ffirst
        (filter #(every? (fn [x] (= n (count (distinct (factors x)))))
                         %)
                integer-quads)))

;; (distinct-prime-factors 4)
;; 134043

;}}}
;{{{ problem 48 -- last ten digits of big number

;; The series, 1^1 + 2^2 + 3^3 + ... + 10^10 = 10405071317.

;; Find the last ten digits of the series, 1^1 + 2^2 + 3^3 + ... + 1000^1000.

(defn big-sum [n mod]
  (rem (reduce + (map #(rem (big-integer-pow % %) mod) (range 1 (inc n))))
       mod))

;; (big-sum 1000 10000000000)
;; 9110846700

;}}}
;{{{ problem 49 -- arithmetic prime sequences w/four digits permutations

;; The arithmetic sequence, 1487, 4817, 8147, in which each of the
;; terms increases by 3330, is unusual in two ways: (i) each of the
;; three terms are prime, and, (ii) each of the 4-digit numbers are
;; permutations of one another.

;; There are no arithmetic sequences made up of three 1-, 2-, or
;; 3-digit primes, exhibiting this property, but there is one other
;; 4-digit increasing sequence.

;; What 12-digit number do you form by concatenating the three terms
;; in this sequence?

(defn arithmetic-prime-seq []
  (filter #(and (isprime? (first (rrest %)))
                (< (first (rrest %)) 10000)
                (= (sort (to-digits (first %)))
                   (sort (to-digits (frest %)))
                   (sort (to-digits (first (rrest %))))))

          (let [p (filter #(> % 999) (primes-below 10000))
                c (count p)]
            (for [x (range c)
                  y (range c) :when (> y x)]
              (let [p1 (nth p x)
                    p2 (nth p y)
                    d (- p2 p1)
                    p3 (+ p2 d)]
                (list p1 p2 p3))))))

;; (arithmetic-prime-seq)
;; ((1487 4817 8147) (2969 6299 9629))

;}}}
;{{{ problem 50 -- sum of most consecutive prime that's prime

;; The prime 41, can be written as the sum of six consecutive primes:

;; 41 = 2 + 3 + 5 + 7 + 11 + 13
;; This is the longest sum of consecutive primes that adds to a prime
;; below one-hundred.

;; The longest sum of consecutive primes below one-thousand that adds
;; to a prime, contains 21 terms, and is equal to 953.

;; Which prime, below one-million, can be written as the sum of the
;; most consecutive primes?

(defn consecutive-prime-sums-below-helper [seq n accum]
  (if (zero? (count seq))
    accum
    (recur (rest seq) n
         (list (reduce max-first
                 (concat (for [x (range (count seq))
                               :while (< (reduce + (take x seq)) n)
                               :when  (isprime? (reduce + (take x seq)))]
                           (list x (reduce + (take x seq))))
                         accum))))))

(defn consecutive-prime-sums-below [n]
  (first (rfirst (consecutive-prime-sums-below-helper (primes-below n) n nil))))

;; (time (consecutive-prime-sums-below 1000000))
;; "Elapsed time: 537056.241 msecs"
;; 997651

;}}}
;}}}

;{{{ problem 51 -- prime replace gives prime *

;; By replacing the 1st digit of *57, it turns out that six of the
;; possible values: 157, 257, 457, 557, 757, and 857, are all prime.

;; By replacing the 3rd and 4th digits of 56**3 with the same digit
;; this 5-digit number is the first example having seven primes
;; yielding the family: 56003, 56113, 56333, 56443, 56663, 56773, and
;; 56993. Consequently 56003, being the first member of this family
;; is the smallest prime with this property.

;; Find the smallest prime which, by replacing part of the number (not
;; necessarily adjacent digits) with the same digit, is part of an
;; eight prime value family.


;}}}
;{{{ problem 51 -- same digits for 2x, 3x, 4x, 5x, 6x

;; It can be seen that the number, 125874, and its double, 251748
;; contain exactly the same digits, but in a different order.

;; Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x
;; and 6x, contain the same digits.

(defn have-same-digits? [n]
  (apply = (map #(sort (to-digits (* n %))) (range 2 7))))

(defn find-same-digits []
  (first
        (filter have-same-digits? (iterate inc 1))))

;; (find-same-digits)
;; 142857

;}}}
;{{{ problem 52 -- n Choose r > 1 M

;; There are exactly ten ways of selecting three from five, 12345:

;; 123, 124, 125, 134, 135, 145, 234, 235, 245, and 345

;; In combinatorics, we use the notation, 5C3 = 10.

;; In general

;; nCr = n! / r!(n-r)!
;; ,where r <= n, n! = n(n-1)...3 2 1, and 0! = 1.
;It is not until n = 23, that a value exceeds one-million: 23C10 =
;1144066.

;; How many, not necessarily distinct, values of nCr, for 1 n 100, are
;; greater than one-million?

(defn big-chooses [x min]
  (count (filter #(> % min)
                 (for [n (range 1 (inc x))
                       r (range 1 (inc x))]
                   (choose n r)))))

;; (big-chooses 100 1000000)
;; 4075

;}}}
;{{{ problem 54 -- poker hands

;; In the card game poker, a hand consists of five cards and are
;; ranked, from lowest to highest, in the following way:

;; High Card: Highest value card.
;; One Pair: Two cards of the same value.
;; Two Pairs: Two different pairs.
;; Three of a Kind: Three cards of the same value.
;; Straight: All cards are consecutive values.
;; Flush: All cards of the same suit.
;; Full House: Three of a kind and a pair.
;; Four of a Kind: Four cards of the same value.
;; Straight Flush: All cards are consecutive values of same suit.
;; Royal Flush: Ten, Jack, Queen, King, Ace, in same suit.

(defn high-card [hand]
  (ffirst hand))

(defn high-card-compare [p1 p2]
  (. (high-card p1) (compareTo (high-card p2))))

(defn flush? [hand]
  (= 1 (count (distinct (map frest hand)))))

(defn straight? [hand]
  (let [h (high-card hand)]
    (= (reverse (map first hand))
       (range (- h 4) (inc h)))))

(defn straight-flush? [hand]
  (and (straight? hand)
       (flush? hand)))

(defn royal-flush? [hand]
  (and (straight-flush? hand)
       (= 14 (high-card hand))))

(defn get-tuples [hand]
  (reverse (sort-by frest ;; TODO: ensure this is a stable sort
                    (reverse (run-length-encode (map first hand))))))

(defn num-same [hand]
  (filter #(> % 1)
          (map frest (get-tuples hand))))

(defn high-tuple-card-compare [p1 p2]
  (let [h1 (map first (get-tuples p1))
        h2 (map first (get-tuples p2))]
    (first (filter (complement zero?)
                   (map (fn [x y] (. x (compareTo y)))
                        h1 h2)))))

(defn poker-compare [p1 p2]
  (cond (royal-flush? p1)
          (if (royal-flush? p2) 0 1)      ;this would be a tie and we are guaranteed none
        (royal-flush? p2)
          -1
        (straight-flush? p1)
          (if (straight-flush? p2) (high-card-compare p1 p2) 1)
        (straight-flush? p2)
          -1
        (= '(4) (num-same p1))
          (if (= '(4) (num-same p2)) (high-tuple-card-compare p1 p2) 1)
        (= '(4) (num-same p2))
          -1
        (= '(3 2) (num-same p1))
          (if (= '(3 2) (num-same p2)) (high-tuple-card-compare p1 p2) 1)
        (= '(3 2) (num-same p2))
          -1
        (flush? p1)
          (if (flush? p2) (high-card-compare p1 p2) 1)
        (flush? p2)
          -1
        (straight? p1)
          (if (straight? p2) (high-card-compare p1 p2) 1)
        (straight? p2)
          -1
        (= '(3) (num-same p1))
          (if (= '(3) (num-same p2)) (high-tuple-card-compare p1 p2) 1)
        (= '(3) (num-same p2))
          -1
        (= '(2 2) (num-same p1))
          (if (= '(2 2) (num-same p2)) (high-tuple-card-compare p1 p2) 1)
        (= '(2 2) (num-same p2))
          -1
        (= '(3) (num-same p1))
          (if (= '(3) (num-same p2)) (high-tuple-card-compare p1 p2) 1)
        (= '(3) (num-same p2))
          -1
        (= '(2) (num-same p1))
          (if (= '(2) (num-same p2)) (high-tuple-card-compare p1 p2) 1)
        (= '(2) (num-same p2))
          -1
        :else
          (high-card-compare p1 p2)))

;; The cards are valued in the order:
;; 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.

;; If two players have the same ranked hands then the rank made up of
;; the highest value wins; for example, a pair of eights beats a pair
;; of fives (see example 1 below). But if two ranks tie, for example
;; both players have a pair of queens, then highest cards in each hand
;; are compared (see example 4 below); if the highest cards tie then
;; the next highest cards are compared, and so on.

;; Consider the following five hands dealt to two players:

;; Hand     Player 1        Player 2        Winner
;; 1        5H 5C 6S 7S KD
;; Pair of Fives
;;      2C 3S 8S 8D TD
;; Pair of Eights
;;      Player 2

;; 2        5D 8C 9S JS AC
;; Highest card Ace
;;      2C 5C 7D 8S QH
;; Highest card Queen
;;      Player 1

;; 3        2D 9C AS AH AC
;; Three Aces
;;      3D 6D 7D TD QD
;; Flush with Diamonds
;;      Player 2

;; 4        4D 6S 9H QH QC
;; Pair of Queens
;; Highest card Nine
;;      3D 6D 7H QD QS
;; Pair of Queens
;; Highest card Seven
;;      Player 1

;; 5        2H 2D 4C 4D 4S
;; Full House
;; With Three Fours
;;      3C 3D 3S 9S 9D
;; Full House
;; with Three Threes
;;      Player 1

;; The file, poker.txt, contains one-thousand random hands dealt to
;; two players. Each line of the file contains ten cards (separated by
;; a single space): the first five are Player 1's cards and the last
;; five are Player 2's cards. You can assume that all hands are valid
;; (no invalid characters or repeated cards), each player's hand is in
;; no specific order, and in each hand there is a clear winner.

;; How many hands does Player 1 win?

;; Cards will look like '(num suit)
(defn parse-card [card]
  (let [num (first card)
        suit (frest card)]

    ;; The cards are valued in the order:
    ;; 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King, Ace.
    (list (cond (= num \T) 10
                (= num \J) 11
                (= num \Q) 12
                (= num \K) 13
                (= num \A) 14
                :else      (parse-integer (str num)))
          suit)))

(defn parse-poker-line [line]
  (map parse-card (re-seq #"[^ ]+" line)))

(defn poker [file]
  (count (filter #(= % 1)
                 (for [l (file-lines file)]
                   (let [cards (parse-poker-line l)
                         player1 (reverse (sort-by first (take 5 cards)))
                         player2 (reverse (sort-by first (nthrest cards 5)))]
;;                      (list player1 player2 (poker-compare player1 player2))
                     (poker-compare player1 player2)
                     )))))

;; (poker "poker.txt")
;; 376

;}}}
;{{{ problem 55 -- Lychrel numbers

;; If we take 47, reverse and add, 47 + 74 = 121, which is
;; palindromic.

;; Not all numbers produce palindromes so quickly. For example

;; 349 + 943 = 1292
;; 1292 + 2921 = 4213
;; 4213 + 3124 = 7337

;; That is, 349 took three iterations to arrive at a palindrome.

;; Although no one has proved it yet, it is thought that some numbers
;; like 196, never produce a palindrome. A number that never forms a
;; palindrome through the reverse and add process is called a Lychrel
;; number. Due to the theoretical nature of these numbers, and for the
;; purpose of this problem, we shall assume that a number is Lychrel
;; until proven otherwise. In addition you are given that for every
;; number below ten-thousand, it will either (i) become a palindrome
;; in less than fifty iterations, or, (ii) no one, with all the
;; computing power that exists, has managed so far to map it to a
;; palindrome. In fact, 10677 is the first number to be shown to
;; require over fifty iterations before producing a palindrome:
;; 4668731596684224866951378664 (53 iterations, 28-digits).

;; Surprisingly, there are palindromic numbers that are themselves
;; Lychrel numbers; the first example is 4994.

;; How many Lychrel numbers are there below ten-thousand?

;; NOTE: Wording was modified slightly on 24 April 2007 to emphasise
;; the theoretical nature of Lychrel numbers.

(defn lychrel? [n]
  ((fn [n iterations]
     (cond (> iterations 50)
             true
           (palindrome? n)
             false
           :else
             (recur (+ n (num-reverse n)) (inc iterations))))
   (+ n (num-reverse n)) 0))

(defn how-many-lychrels [n]
  (count (filter lychrel? (range 0 n))))

;; (how-many-lychrels 10000)
;; 249

;}}}
;{{{ problem 56 -- digital sums of powers

;; A googol (10^100) is a massive number: one followed by one-hundred
;; zeros; 100100 is almost unimaginably large: one followed by
;; two-hundred zeros. Despite their size, the sum of the digits in
;; each number is only 1.

;; Considering natural numbers of the form, a^b, where a, b < 100, what
;; is the maximum digital sum?

(defn digital-sums-of-powers [n]
  (reduce max (for [a (range 1 n)
                    b (range 1 n)]
                (sum-of-digits (big-integer-pow a b)))))

;; (digital-sums-of-powers 100)
;; 972

;}}}
;{{{ problem 57 -- continued fractions

;; It is possible to show that the square root of two can be expressed
;; as an infinite continued fraction.

;;  2 = 1 + 1/(2 + 1/(2 + 1/(2 + ... ))) = 1.414213...

;; By expanding this for the first four iterations, we get:

;; 1 + 1/2 = 3/2 = 1.5
;; 1 + 1/(2 + 1/2) = 7/5 = 1.4
;; 1 + 1/(2 + 1/(2 + 1/2)) = 17/12 = 1.41666...
;; 1 + 1/(2 + 1/(2 + 1/(2 + 1/2))) = 41/29 = 1.41379...

;; The next three expansions are 99/70, 239/169, and 577/408, but the
;; eighth expansion, 1393/985, is the first example where the number
;; of digits in the numerator exceeds the number of digits in the
;; denominator.

;; In the first one-thousand expansions, how many fractions contain a
;; numerator with more digits than denominator?

(defn continued-fractions [x limit accum]
  (if (zero? limit)
    accum
    (let [next-n (inc (/ (inc x)))
          next-accum (if (> (count (to-digits (. x numerator)))
                            (count (to-digits (. x denominator))))
                       (inc accum) accum)]
      (recur next-n (dec limit) next-accum))))

;; (continued-fractions 3/2 1000 0)
;; 153

;}}}
;{{{ problem 58 -- prime spiral arms

;; Starting with 1 and spiralling anticlockwise in the following way
;; a square spiral with side length 7 is formed.

;; 37' 36  35  34  33  32  31'
;; 38  17' 16  15  14  13' 30
;; 39  18   5'  4   3' 12  29
;; 40  19   6   1   2  11  28
;; 41  20   7'  8   9  10  27
;; 42  21  22  23  24  25  26
;; 43' 44  45  46  47  48  49

;; It is interesting to note that the odd squares lie along the bottom
;; right diagonal, but what is more interesting is that 8 out of the
;; 13 numbers lying along both diagonals are prime; that is, a ratio
;; of 8/13 62%.

;; If one complete new layer is wrapped around the spiral above, a
;; square spiral with side length 9 will be formed. If this process is
;; continued, what is the side length of the square spiral for which
;; the ratio of primes along both diagonals first falls below 10%?


;; We have 1, +2,+2,+2,+2, +4,+4,+4,+4, etc.

(def spiral-diagonals
     (lazy-cons 1
                ((fn this[cur amt]
                  (let [new-seq (map #(+ cur (* amt %)) (range 1 5))]
                    (lazy-cat (map #(+ cur (* amt %)) (range 1 5))
                              (this (nth new-seq 3) (+ 2 amt)))))
                 1 2)))

(def spiral-diagonals
     (lazy-cons '(1)
                ((fn this[cur amt]
                  (let [new-seq (map #(+ cur (* amt %)) (range 1 5))]
                    (lazy-cons (map #(+ cur (* amt %)) (range 1 5))
                              (this (nth new-seq 3) (+ 2 amt)))))
                 1 2)))

(defn bob [n]
  (take n
        (map (fn [diags len cnt]
               (list (count (filter isprime? (distinct diags))) len cnt)) ;(if (isprime? d) 1 0)
             spiral-diagonals
             (iterate #(+ 2 %) 1)
             (iterate #(+ 4 %) 1))))


(defn find-spiral-prime-ratio [ratio]
  ((fn this[diags primes cnt len]
     (let [cur-primes (+ primes (count (filter isprime? (first diags))))
           cur-cnt (+ 4 cnt)
           cur-len (+ 2 len)]
       (if (< (/ cur-primes cur-cnt) ratio)
         cur-len
         (recur (rest diags) cur-primes cur-cnt cur-len))))
   (drop 1 spiral-diagonals) 0 1 1))

;; (find-spiral-prime-ratio 1/10)
;; 26241

;}}}
;{{{ problem 59 -- encryption

;; Each character on a computer is assigned a unique code and the
;; preferred standard is ASCII (American Standard Code for Information
;; Interchange). For example, uppercase A = 65, asterisk (*) = 42, and
;; lowercase k = 107.

;; A modern encryption method is to take a text file, convert the
;; bytes to ASCII, then XOR each byte with a given value, taken from a
;; secret key. The advantage with the XOR function is that using the
;; same encryption key on the cipher text, restores the plain text;
;; for example, 65 XOR 42 = 107, then 107 XOR 42 = 65.

;; For unbreakable encryption, the key is the same length as the plain
;; text message, and the key is made up of random bytes. The user
;; would keep the encrypted message and the encryption key in
;; different locations, and without both "halves", it is impossible to
;; decrypt the message.

;; Unfortunately, this method is impractical for most users, so the
;; modified method is to use a password as a key. If the password is
;; shorter than the message, which is likely, the key is repeated
;; cyclically throughout the message. The balance for this method is
;; using a sufficiently long password key for security, but short
;; enough to be memorable.

;; Your task has been made easy, as the encryption key consists of
;; three lower case characters. Using cipher1.txt (right click and
;; 'Save Link/Target As...'), a file containing the encrypted ASCII
;; codes, and the knowledge that the plain text must contain common
;; English words, decrypt the message and find the sum of the ASCII
;; values in the original text.

(defn max-frest
  ([a] a)
  ([a b] (if (< (frest a) (frest b)) b a)))

(defn find-key [seq]
  (let [rle (run-length-encode (sort seq))
        most-popular (first (reduce max-frest rle))]
    (bit-xor most-popular (int \space )))) ; All too easy -- didn't really solve the problem though...

(defn map-no-exhaust [f & seqs]
  (lazy-cons (apply f (map first seqs))
   (if (every? nil? (map first seqs))
     nil
     (apply map-no-exhaust f (map rest seqs)))))

(defn decipher-xor [file n]
  (let [numbers (re-seq #"\d+" (slurp file))]
    (apply str
           (apply map-no-exhaust str ; This doesn't find all the input since it only uses sequences while they all have data
                  (for [x (range n)]
                    (let [stream (map parse-integer (take-nth n (drop x numbers)))
                          key (find-key stream)]
                      (map #(char (bit-xor key %)) stream)))))))

;; (reduce + (map int (decipher-xor "cipher1.txt" 3)))
;; 107359

;}}}
;{{{ problem 60 -- prime concatenation *

;; The primes 3, 7, 109, and 673, are quite remarkable. By taking any
;; two primes and concatenating them in any order the result will
;; always be prime. For example, taking 7 and 109, both 7109 and 1097
;; are prime. The sum of these four primes, 792, represents the lowest
;; sum for a set of four primes with this property.

;; Find the lowest sum for a set of five primes for which any two
;; primes concatenate to produce another prime.

(def primes-concatenated {})
(defn prime-concatenation [n]
;;   (sort-by first
  (let [primes-concatenated {}]
    (for [p1 (primes-below n)
          p2 (primes-below p1) :when (and (isprime? (int-concat p1 p2))
                                          (isprime? (int-concat p2 p1)))]
      (do
        (update-in primes-concatenated [p1]
                   #(cons p2 %))
        (update-in primes-concatenated [p2]
                   #(cons p1 %))
        (update-in primes-concatenated [p1]
                   #(cons p2 %))))
    primes-concatenated))

;}}}

;{{{ problem 61 -- cyclic figurate numbers *

;; Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal
;; numbers are all figurate (polygonal) numbers and are generated by
;; the following formulae:

;; Triangle         P3,n=n(n+1)/2        1, 3, 6, 10, 15, ...
;; Square           P4,n=n^2             1, 4, 9, 16, 25, ...
;; Pentagonal       P5,n=n(3n-1)/2       1, 5, 12, 22, 35, ...
;; Hexagonal        P6,n=n(2n-1)         1, 6, 15, 28, 45, ...
;; Heptagonal       P7,n=n(5n-3)/2       1, 7, 18, 34, 55, ...
;; Octagonal        P8,n=n(3n-2)         1, 8, 21, 40, 65, ...

;; The ordered set of three 4-digit numbers: 8128, 2882, 8281, has
;; three interesting properties.

;; The set is cyclic, in that the last two digits of each number is
;; the first two digits of the next number (including the last number
;; with the first).

;; Each polygonal type: triangle (P3,127=8128), square (P4,91=8281)
;; and pentagonal (P5,44=2882), is represented by a different number
;; in the set.

;; This is the only set of 4-digit numbers with this property.

;; Find the sum of the only ordered set of six cyclic 4-digit numbers
;; for which each polygonal type: triangle, square, pentagonal
;; hexagonal, heptagonal, and octagonal, is represented by a different
;; number in the set.



;}}}
;{{{ problem 62 -- permuting cubes

;; The cube, 41063625 (345^3), can be permuted to produce two other
;; cubes: 56623104 (384^3) and 66430125 (405^3). In fact, 41063625 is
;; the smallest cube which has exactly three permutations of its
;; digits which are also cube.

;; Find the smallest cube for which exactly five permutations of its digits are cube.

(defn permutations-with-repeats [seq]
  ;;   (prn 'seq seq)
  (if (= 1 (count seq))
    (list seq)
    (apply concat (for [x (distinct seq)]
                    (do
;;                       (prn 'x x)
                      (let [tail (filter #(not= x %) seq)
                            repeats (dec (count (filter #(= x %) seq)))
                            real-tail (concat tail (take repeats (repeat x)))]

;;                         (prn 'repeats repeats 'real-tail real-tail 'tail tail 'perm (permutations-with-repeats tail))
                        (map #(cons x %)
                             (permutations-with-repeats real-tail))))))))

(def cubes (map #(* % % %) (iterate inc 1)))

(defn cube? [n]
  (let [x (Math/round (Math/pow n 1/3))]
    (= (* x x x) n)))

(defn num-permuted-cubes [n]
  (prn 'num-permuted-cubes n)
  (count (filter #(and (>= % n) (cube? %))
                 (map #(apply int-concat %)
                      (permutations-with-repeats (to-digits n))))))

(defn smallest-permutable-cube [n]
  (first (filter #(= n (num-permuted-cubes %))
                  cubes)))

(defn smallest-permutable [limit seq]
  ((fn this [m seq]
     (let [n (first seq)
           sorted-digits (sort (to-digits n))
           new-map (update-in m [sorted-digits] #(cons n %))]
       (if (and (= limit (count (new-map sorted-digits)))
;;                 (= 1 (num-permuted-cubes n)) ;; just to make sure it's exactly 5... (because this only counts those >= self)
                )
         (reduce min (new-map sorted-digits)) ;; This isn't actually the smallest
         (recur new-map (rest seq)))))
   {} seq))

;; (smallest-permutable 5 cubes)
;; 127035954683

;}}}
;{{{ problem 63 -- n-digit n-th powers

;; The 5-digit number, 16807=7^5, is also a fifth power. Similarly
;; the 9-digit number, 134217728=8^9, is a ninth power.

;; How many n-digit positive integers exist which are also an nth power?

(defn n-digit-nth-powers-of [n]
  ((fn this [n power num-digits accum]
;;      (prn n power num-digits (count accum))
;;      (flush)
     (cond (= num-digits (count (to-digits power)))
             (recur n (* n power) (inc num-digits) (cons power accum))
;;            (> num-digits 100)
;;              accum
;;            (< num-digits (count (to-digits power)))
;;              (recur n (* n power) (inc num-digits) accum)
           :else
             accum))
   n n 1 '()))


;; TODO: maybe I should make a map from sorted digits of cubes and
;; check everytime to see if there are 5, etc.
(defn num-n-digit-nth-powers []
  (count (distinct (mapcat n-digit-nth-powers-of (range 1 10)))))

;; (num-n-digit-nth-powers)
;; 49

;}}}
;{{{ problem 64 -- periods of continued fractions *

;; All square roots are periodic when written as continued fractions
;; and can be written in the form:

;; N = a0 +
;; 1
;;      a1 +
;; 1
;;          a2 +
;; 1
;;              a3 + ...
;; For example, let us consider 23:

;; 23 = 4 + 23 - 4 = 4 +
;; 1
;;  = 4 +
;; 1

;; 1
;; 23-4
;;      1 +
;; 23 - 3
;; 7
;; If we continue we would get the following expansion:

;; 23 = 4 +
;; 1
;;      1 +
;; 1
;;          3 +
;; 1
;;              1 +
;; 1
;;                  8 + ...
;; The process can be summarised as follows:

;; a0 = 4
;; 1
;; 23-4
;;  =
;; 23+4
;; 7
;;  = 1 +
;; 23-3
;; 7
;; a1 = 1
;; 7
;; 23-3
;;  =
;; 7(23+3)
;; 14
;;  = 3 +
;; 23-3
;; 2
;; a2 = 3
;; 2
;; 23-3
;;  =
;; 2(23+3)
;; 14
;;  = 1 +
;; 23-4
;; 7
;; a3 = 1
;; 7
;; 23-4
;;  =
;; 7(23+4)
;; 7
;;  = 8 +   23-4
;; a4 = 8
;; 1
;; 23-4
;;  =
;; 23+4
;; 7
;;  = 1 +
;; 23-3
;; 7
;; a5 = 1
;; 7
;; 23-3
;;  =
;; 7(23+3)
;; 14
;;  = 3 +
;; 23-3
;; 2
;; a6 = 3
;; 2
;; 23-3
;;  =
;; 2(23+3)
;; 14
;;  = 1 +
;; 23-4
;; 7
;; a7 = 1
;; 7
;; 23-4
;;  =
;; 7(23+4)
;; 7
;;  = 8 +   23-4
;; It can be seen that the sequence is repeating. For conciseness, we
;; use the notation 23 = [4;(1,3,1,8)], to indicate that the block
;; (1,3,1,8) repeats indefinitely.

;; The first ten continued fraction representations of (irrational) square roots are:

;; 2=[1;(2)], period=1
;; 3=[1;(1,2)], period=2
;; 5=[2;(4)], period=1
;; 6=[2;(2,4)], period=2
;; 7=[2;(1,1,1,4)], period=4
;; 8=[2;(1,4)], period=2
;; 10=[3;(6)], period=1
;; 11=[3;(3,6)], period=2
;; 12= [3;(2,6)], period=2
;; 13=[3;(1,1,1,1,6)], period=5

;; Exactly four continued fractions, for N  13, have an odd period.

;; How many continued fractions for N  10000 have an odd period?


;}}}
;{{{ problem 65 -- continued fractions for e

;; The square root of 2 can be written as an infinite continued fraction.

;; 2 = 1 +
;; 1
;;      2 +
;; 1
;;          2 +
;; 1
;;              2 +
;; 1
;;                  2 + ...

;; The infinite continued fraction can be written, 2 = [1;(2)], (2)
;; indicates that 2 repeats ad infinitum. In a similar way, sqrt(23) =
;; [4;(1,3,1,8)].

;; It turns out that the sequence of partial values of continued
;; fractions for square roots provide the best rational
;; approximations. Let us consider the convergents for 2.

;; 1 +
;; 1/2
;; = 3/2

;; 1 +
;; 1
;; = 7/5
;;      2 +
;; 1

;; 2
;; 1 +
;; 1
;; = 17/12
;;      2 +
;; 1

;;          2 +
;; 1



;; 2

;; 1 +
;; 1

;; = 41/29
;;      2 +
;; 1

;;          2 +
;; 1


;;              2 +
;; 1



;; 2

;; Hence the sequence of the first ten convergents for sqrt(2) are:

;; 1, 3/2, 7/5, 17/12, 41/29, 99/70, 239/169, 577/408, 1393/985, 3363/2378, ...
;; What is most surprising is that the important mathematical constant
;; e = [2; 1,2,1, 1,4,1, 1,6,1 , ... , 1,2k,1, ...].

;; The first ten terms in the sequence of convergents for e are:

;; 2, 3, 8/3, 11/4, 19/7, 87/32, 106/39, 193/71, 1264/465, 1457/536, ...
;; The sum of digits in the numerator of the 10th convergent is 1+4+5+7=17.

;; Find the sum of digits in the numerator of the 100th convergent of
;; the continued fraction for e.

(def continued-fraction-e
     (lazy-cons 2
                ((fn this[n]
                  (lazy-cat (list 1 n 1)
                            (this (+ 2 n))))
                 2)))

(defn continued-fraction-nth-convergent [seq limit]
  (/ ((fn this[seq accum]
        (if seq
           (recur (rest seq) (/ (+ (first seq) accum)))
          accum))
      (reverse (take limit seq)) 0)))

(defn nth-e-convergent [n]
  (sum-of-digits (. (continued-fraction-nth-convergent continued-fraction-e n) numerator)))

;; (nth-e-convergent 100)
;; 272

;}}}
;{{{ problem 66 -- Diaphontine equations *

;; Consider quadratic Diophantine equations of the form:

;; x^2 - Dy^2 = 1

;; For example, when D=13, the minimal solution in x is 6492 - 131802 = 1.

;; It can be assumed that there are no solutions in positive integers
;; when D is square.

;; By finding minimal solutions in x for D = {2, 3, 5, 6, 7}, we
;; obtain the following:

;; 3^2 - 2*2^2 = 1
;; 2^2 - 3*1^2 = 1
;; 9^2 - 5*4^2 = 1  <--
;; 5^2 - 6*2^2 = 1
;; 8^2 - 7*3^2 = 1

;; Hence, by considering minimal solutions in x for D <= 7, the largest x
;; is obtained when D=5.

;; Find the value of D <= 1000 in minimal solutions of x for which the
;; largest value of x is obtained.

;}}}
;{{{ problem 67 -- more triangle path maximizing

;; By starting at the top of the triangle below and moving to adjacent
;; numbers on the row below, the maximum total from top to bottom is
;; 23.

;; 3
;; 7 5
;; 2 4 6
;; 8 5 9 3

;; That is, 3 + 7 + 4 + 9 = 23.

;; Find the maximum total from top to bottom in triangle.txt (right
;; click and 'Save Link/Target As...'), a 15K text file containing a
;; triangle with one-hundred rows.

;; NOTE: This is a much more difficult version of Problem 18. It is
;; not possible to try every route to solve this problem, as there are
;; 299 altogether! If you could check one trillion (1012) routes every
;; second it would take over twenty billion years to check them
;; all. There is an efficient algorithm to solve it. ;o)

(defn path-maximizer [file]
  (path-helper nil
               (map #(map parse-integer (re-seq #"\d+" %))
                    (file-lines file))))

;; (path-maximizer "triangle.txt")
;; 7273

;}}}
;{{{ problem 68 -- magic n-gons *

;; Consider the following "magic" 3-gon ring, filled with the numbers
;; 1 to 6, and each line adding to nine.

;;     4
;;     |
;; 5-1-3
;;    \|
;;     2
;;       \
;;        6

;; Working clockwise, and starting from the group of three with the
;; numerically lowest external node (4,3,2 in this example), each
;; solution can be described uniquely. For example, the above solution
;; can be described by the set: 4,3,2; 6,2,1; 5,1,3.

;; It is possible to complete the ring with four different totals: 9
;; 10, 11, and 12. There are eight solutions in total.

;; Total	Solution Set
;; 9	4,2,3; 5,3,1; 6,1,2
;; 9	4,3,2; 6,2,1; 5,1,3
;; 10	2,3,5; 4,5,1; 6,1,3
;; 10	2,5,3; 6,3,1; 4,1,5
;; 11	1,4,6; 3,6,2; 5,2,4
;; 11	1,6,4; 5,4,2; 3,2,6
;; 12	1,5,6; 2,6,4; 3,4,5
;; 12	1,6,5; 3,5,4; 2,4,6

;; By concatenating each group it is possible to form 9-digit strings;
;; the maximum string for a 3-gon ring is 432621513.

;; Using the numbers 1 to 10, and depending on arrangements, it is
;; possible to form 16- and 17-digit strings. What is the maximum
;; 16-digit string for a "magic" 5-gon ring?




;}}}
;{{{ problem 69 -- totient *

;; Euler's Totient function, φ(n) [sometimes called the phi function]
;; is used to determine the number of numbers less than n which are
;; relatively prime to n. For example, as 1, 2, 4, 5, 7, and 8, are
;; all less than nine and relatively prime to nine, φ(9)=6.

;; n    Relatively Prime  φ(n)   n/φ(n)
;; 2      1               1      2
;; 3      1,2             2      1.5
;; 4      1,3             2      2
;; 5      1,2,3,4         4      1.25
;; 6      1,5             2      3
;; 7      1,2,3,4,5,6     6      1.1666...
;; 8      1,3,5,7         4      2
;; 9      1,2,4,5,7,8     6      1.5
;; 10     1,3,7,9         4      2.5

;; It can be seen that n=6 produces a maximum n/φ(n) for n <= 10.

;; Find the value of n <= 1,000,000 for which n/φ(n) is a maximum.

(defn totient [n]                       ; TODO: this isn't quite right... I have to take repeated factors into account
  (reduce * (map #(- % 1) (factors n))))


;}}}
;{{{ problem 70 -- totient *

;; Euler's Totient function, φ(n) [sometimes called the phi function]
;; is used to determine the number of positive numbers less than or
;; equal to n which are relatively prime to n. For example, as 1, 2
;; 4, 5, 7, and 8, are all less than nine and relatively prime to
;; nine, φ(9)=6.

;; The number 1 is considered to be relatively prime to every positive
;; number, so φ(1)=1.

;; Interestingly, φ(87109)=79180, and it can be seen that 87109 is a permutation of 79180.

;; Find the value of n, 1 < n < 10^7, for which φ(n) is a permutation of n and the ratio n/φ(n) produces a minimum.

;; (map #(list % (totient %))
;;      (range 2 10000000))

;}}}
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.