Source

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
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
;; : 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))
  ;; (:use [clojure.contrib [seq :only []]])
  ;; (:use [clojure.contrib [seq-utils :only []]])
  )

;{{{ 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)
;;   )

;; This one doesn't work anymore because lazy-cons doesn't exist :-(
;; (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-2
     (cons 2
           (lazy-seq
             ((fn this[n]
                (let [potential-divisors (take-while #(<= (* % %) n) primes-2)
                      next-p (+ n 2)]
                  (if (some #(zero? (rem n %)) potential-divisors)
                    (recur next-p)
                    (cons n (lazy-seq (this next-p))))))
              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))
    (cond (< n cur)
            acc
          (> (* cur cur) n)
            (cons n acc)
          (divides? cur n)
            (recur (/ n cur) (cons cur acc) seq)
          :else
            (recur n acc (rest seq)))))

(defn factors [n]
  (if (< n 0)
      (factors-rec (- n) '(-1) primes)
    (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))))))

;; (time (palindromes))
;; "Elapsed time: 6279.906 msecs"
;; 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 (or (nil? seq)
          (nil? (first seq)))
    seq
    (let [f (first seq)
          cnt (count-uniq seq)]
      (list* (list f cnt)
             (run-length-encode (drop cnt seq))))))

(defn abs [x]
  (if (< x 0) (- x) x))

;; This is now defined
;; (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)))

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

;; 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 n) (sum-of-squares-upto n)))

;; (difference-sums-squares 100)
;; 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:
(defn large-product [list-of-nums]
  (reduce max (map *
                   (drop 0 list-of-nums)
                   (drop 1 list-of-nums)
                   (drop 2 list-of-nums)
                   (drop 3 list-of-nums)
                   (drop 4 list-of-nums))))

;; (large-product list-of-nums)
;; 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)))

;; (time (pythagorean-triple 1000))
;; "Elapsed time: 0.095 msecs"
;; (31875000)

;}}}
;{{{ 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)))

;; (time (sum-of-primes 2000000))
;; "Elapsed time: 8258.269 msecs"
;; 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)))))


(def frest (comp first rest))
(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)))))))

;; (time (largest-product))
;; "Elapsed time: 58.992 msecs"
;; 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)))))

;; (time (longest-collatz 1000000))
;; "Elapsed time: 121650.233 msecs"
;; (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 (seq triangle)
    (let [next-triangle (first triangle)
          next-accum (for [x (range (count next-triangle))]
                       (+ (nth next-triangle x)
                          (max (nth accum (- x 1) 0) (nth accum x 0))))] ; nth with out of bounds
      (recur next-accum (rest triangle)))
    (apply max accum)))

;; (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))))

;; (time (amicable-sum 10000))
;; "Elapsed time: 6286.36 msecs"
;; 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))))

;; (time (sum-of-non-abundant-sums))
;; "Elapsed time: 107783.701 msecs"
;; 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 (not (seq 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 min-first
  ([x] x)
  ([x y] (if (> (first x) (first y)) y x))
  ([x y & more] (reduce min-first (min-first x y) more))
  )

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

;; (time (find-repeating-decimals 1000))
;; "Elapsed time: 4003.65 msecs"
;; (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 (next 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 #(abs (+ (* % %) (* a %) b))
                   (range b))))

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

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

;; (time (test-quadratic 1000))
;; "Elapsed time: 2716.664 msecs"
;; -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)))))

;; (time (reduce + (filter fourth-power? (range 2 354294))))
;; "Elapsed time: 3339.717 msecs"
;; 19316

;; (time (reduce + (filter fifth-power? (range 2 354294))))
;; "Elapsed time: 3429.407 msecs"
;; 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)))))))

;; (time (pandigital-9-product))
;; "Elapsed time: 23457.702 msecs"
;; 45228

;}}}
;{{{ 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)))))

;; (time (reduce + (filter sum-of-factorials? (range 3 2540160))))
;; "Elapsed time: 30511.995 msecs"
;; 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)))))

;; (time (circular-primes 1000000))
;; "Elapsed time: 5006.545 msecs"
;; 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)))))

;; (time (sum-of-palindromes 1000000))
;; "Elapsed time: 11648.405 msecs"
;; 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)))))

;; (time (truncatable-primes))
;; "Elapsed time: 2588.425 msecs"
;; 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)))))))))))
;; (time (x-pandigital-products 9))
;; "Elapsed time: 207.523 msecs"
;; 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)))))

;; (time (perimeter-with-max-right-triangles 1000))
;; "Elapsed time: 129329.595 msecs"
;; (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)))

(def that-irrational-number
     (cons '.
           (lazy-seq
             ((fn this[n]
                (concat (to-digits n)
                        (lazy-seq (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)))))

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

;; (time (product-of-10powers-2 7))
;; "Elapsed time: 1318.285 msecs"
;; 210

;}}}
;{{{ 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)))

;; (time (largest-pandigital-prime-2))
;; "Elapsed time: 20029.519 msecs"
;; 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))))))

;; (time (triangle-words "words.txt"))
;; "Elapsed time: 34.175 msecs"
;; 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 (drop x digits)))) 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 (drop x seq)))) (rem (parse-big-integer (apply str (take 3 (drop x seq)))) p))
                      (rem (parse-big-integer (apply str (take 3 (drop x seq)))) 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 (not (seq 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) (drop 1 p))
                     ;;                 (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)

;; (time (pandigital-substring-3 4888))
;; "Elapsed time: 56.964 msecs"
;; 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
     (lazy-seq
       ((fn this[n]
          (cons (nth-pentagonal n)
                (lazy-seq (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)))))

;; (time (find-pentagonal-numbers-3 1))
;; "Elapsed time: 2.267 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
     (lazy-seq ((fn this [x]
                  (if (isprime? x)
                    (recur (+ 2 x))
                    (cons x (lazy-seq (this (+ 2 x))))))
                9)))

;; This could be simpler
(defn is-square? [n]
  (and (let [d (rem n 4)]
         (or (zero? d)
             (= 1 d)))
       (let [x (Math/round (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 #(seq (prime-plus-2-square? %)))
                  odd-composites)))

;; (time (non-goldbachs 1))
;; "Elapsed time: 0.161 msecs"
;; (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))

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

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

;; (time (distinct-prime-factors 4))
;; "Elapsed time: 1790.427 msecs"
;; 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 rrest [seq]
  (rest (rest seq)))
(defn frrest [seq]
  (first (rest (rest seq))))

(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))))))

;; (time (arithmetic-prime-seq))
;; "Elapsed time: 2.644 msecs"
;; ((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 frfirst [seq]
  (first (rest (first seq))))

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

;; (time (consecutive-prime-sums-below 1000000))
;; "Elapsed time: 421993.041 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.

(defn is-k-member-family? [k n]
  (let [possible-digits (if (= (first n) "*")
                          (range 1 10)
                          (range 10))
        fam (filter isprime?
                    (map #(apply int-concat %)
                         (for [x possible-digits]
                           (map #(if (= "*" %) x %) n))))]
    (if (>= (count fam) k)
      fam)))

;; (is-k-member-family? 6 '("*" 5 7))
;; (is-k-member-family? 6 '(2))
;; (is-k-member-family? 7 '(5 6 "*" "*" 3))

;; TODO
(defn possible-substitutions
  ([digits]
     (filter
      (fn [x] (some #(= "*" %) x))
      (possible-substitutions digits nil)))
  ([digits filter]
     (if (<= (count digits) 1)
        ;; base case
        (if (or (nil? filter)
                (= filter (first digits)))
          (list '("*") digits)
          (list digits))
        ;; recursive case
        (let [r (possible-substitutions (rest digits) filter)
              f (first digits)]
          (concat
           ;; We omit if possible
           (if (or (nil? filter)
                   (= f filter)) ;; f == filter so it's okay in both situations
             (map #(cons "*" %) (possible-substitutions (rest digits) f)))
           ;; Those where we don't omit
           (map #(cons (first digits) %) r))))))

;; (possible-substitutions (to-digits 12332))
;; (possible-substitutions (to-digits 1))

(defn has-k-member-family? [k n]
  (let [digits (to-digits n)]
    (some #(is-k-member-family? k %)
          (possible-substitutions digits))))

;; (has-k-member-family? 7 56113)
;; (has-k-member-family? 7 56003)
;; (has-k-member-family? 6 157)

(defn smallest-prime-k-family [k]
  (first
   (filter #(has-k-member-family? k %)
           primes)))

;; (has-k-member-family? 6 (smallest-prime-k-family 6)) (13 23 43 53 73 83)
;; (has-k-member-family? 7 (smallest-prime-k-family 7)) (56003 56113 56333 56443 56663 56773 56993)
;; (has-k-member-family? 8 (smallest-prime-k-family 8))  (121313 222323 323333 424343 525353 626363 828383 929393)

;; (time (smallest-prime-k-family 8))
;; Elapsed time: 17258.831 msecs
;; 121313

;; TODO: maybe I should compare the primes against each other instead...

;}}}
;{{{ 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 (drop 5 cards)))]
;;                      (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
     (cons 1
           ((fn this[cur amt]
              (let [new-seq (map #(+ cur (* amt %)) (range 1 5))]
                (concat (map #(+ cur (* amt %)) (range 1 5))
                        (lazy-seq (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)))
(def spiral-diagonals
     (cons '(1)
           ((fn this[cur amt]
              (let [new-seq (map #(+ cur (* amt %)) (range 1 5))]
                (cons (map #(+ cur (* amt %)) (range 1 5))
                      (lazy-seq (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))

;; (time (find-spiral-prime-ratio 1/10))
;; "Elapsed time: 5979.02 msecs"
;; 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-seq
    (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)))))))

;; (time (reduce + (map int (decipher-xor "cipher1.txt" 3))))
;; "Elapsed time: 46.001 msecs"
;; 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))

;; (time (smallest-permutable 5 cubes))
;; "Elapsed time: 294.208 msecs"
;; 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?
(defn sqrt-period [n]
  (if (is-square? n)
    0))



;}}}
;{{{ 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
     (cons 2
           ((fn this[n]
              (concat (list 1 n 1)
                      (lazy-seq (this (+ 2 n)))))
            2)))

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

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

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

;}}}


;{{{ pipeline

;; (defmacro pipeline
;;   "Meant to facilitate long map filter reduce pipelines, especially
;; indentation and unncessary nesting.  Each keyword is changed into a
;; call to the function of the same name with the two arguments, 1 next
;; item in the macro body and the result of pipeline applied recursively
;; to the rest of the body."
;;   [& body]
;;   (let [one (and body (first body))
;;         two (and body (rest body) (frest body))
;;         three (and body (rest body) (rrest body))]
;;     (if (keyword? one)
;;       (if (nil? two)                    ;Or maybe I could check to see if two is keyword?
;;           (list (symbol (name one))
;;                 `(pipeline ~@three))
;;         (list (symbol (name one))
;;               two
;;               `(pipeline ~@three)))
;;       `(do ~@body))))


(defmacro pipeline
  "Meant to facilitate long map filter reduce pipelines, especially
indentation and unncessary nesting.  Each keyword is changed into a
call to the function of the same name with the two arguments, 1 next
item in the macro body and the result of pipeline applied recursively
to the rest of the body."
  [& body]
  (if (keyword? (and body (first body)))
    (let [pieces (split-with (complement keyword?) (rest body))]
      (if (zero? (count (pieces 1)))
          `(~(symbol (name (first body))) ~@(pieces 0))
        `(~(symbol (name (first body))) ~@(pieces 0) (pipeline ~@(pieces 1)))))
    `(do ~@body)))

;; This one is from http://richhickey.github.com/clojure/clojure.core-api.html
;; I'm not sure why I don't have it
;; (defmacro ->>
;;   "Threads the expr through the forms. Inserts x as the
;;   last item in the first form, making a list of it if it is not a
;;   list already. If there are more forms, inserts the first form as the
;;   last item in second form, etc."
;;   ([x form] (if (seq? form)
;;               (with-meta `(~(first form) ~@(next form)  ~x) (meta form))
;;               (list form x)))
;;   ([x form & more] `(->> (->> ~x ~form) ~@more)))


;}}}


;{{{ 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 649^2 - 13*180^2 = 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.

(defn first-intersection [seq1 seq2]
  (cond (< (first seq1) (first seq2))
          (recur (rest seq1) seq2)
        (> (first seq1) (first seq2))
          (recur seq1 (rest seq2))
        :else ;; they must be equal
          (first seq1)))

(defn minimum-x-with-solution-2 [D]
  (list
   (first-intersection (map #(* % %) (iterate inc 1))
                       (map #(+ 1 (* D % %))
                            (iterate inc 1)))
   D))


;; (/ (- (* x x) 1) D)                     ;; must be square so


(defn no-solution-for [y]
  (fn [D]
    (not (is-square? (+ 1 (* D y y))))))

(defn minimum-D
  ([n] (minimum-D 1
                  (filter (complement is-square?)
                          (range 2 (inc n)))))
  ([y seq]
     (if (= 1 (count seq))
    (first seq)
    (recur (inc y)
           (filter (no-solution-for y) seq)))))

;; (time (minimum-D 1000))
;;

(defn minimum-x-with-solution [D]
  (list
   (pipeline
     :first
     :filter is-square?
     :map #(+ 1 (* D % %))
     (iterate inc 1))
   D))

(defn minimal-diaphontine-x [n]
  (pipeline
    :frest
    :reduce max-first
    :map minimum-x-with-solution
    :filter (complement is-square?)
    (range (inc n))))

;; (time (minimal-diaphontine-x 100))
;; "Elapsed time: 256626.027 msecs"
;; 61




(defn largest-factor [D]
  (reduce max 1
          (pipeline
            :map #(big-integer-pow (first %) (frest %))
            :filter #(and (not (nil? (first %)))
                          (not= 2 (first %)))
            (run-length-encode (factors D)))))


(defn minimum-x-with-solution [D]
  (let [incrementer (largest-factor D)]
    (list
     (take 2

           (for [xx (take-while #(< % 100) (iterate #(+ incrementer %) 1))]
             (do ;(prn D incrementer xx (/ (* xx (+ xx 2)) D) (/ (* xx (- xx 2)) D))
;;                (prn xx (/ (* xx (+ xx 2)) D) (/ (* xx (- xx 2)) D))
               (cond (is-square? (/ (* xx (+ xx 2)) D))
                       (list (inc xx) D)
                     (is-square? (/ (* xx (- xx 2)) D))
                       (list (dec xx) D)
                     :else
                     nil))))
     D)))



(defn minimum-x-with-solution [D]
  (let [incrementer (largest-factor D)]
    (pipeline :first
              :filter (complement nil?)
              :map #(cond (is-square? (/ (* % (+ % 2)) D))
                            (list (inc %) D)
                          (is-square? (/ (* % (- % 2)) D))
                            (list (dec %) D)
                          :else
                            nil)
              (iterate #(+ incrementer %) incrementer))))


;; (map largest-factor )
(defn minimal-diaphontine-x [n]
  (pipeline

;;     :frest nil
;;     :reduce max-first

;;     :reverse nil
;;     :sort-by first

    :map minimum-x-with-solution
    :filter (complement is-square?)
    (range (inc n))))

;; (time (minimal-diaphontine-x 100))

;}}}
;{{{ 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?

(defn permutations-summing-rec [n must-start must-finish seq accum]
  (cond (= (count seq) 1)
          (if (= n (+ must-start must-finish (first seq)))
            (list (reverse (cons (list (first seq) must-start must-finish) accum)))
            nil)
        (< (count seq) 1)
          (prn 'impossible)
        :else
          (for [x seq
                y seq :when (and (not= x y)
                                 (= n (+ must-start x y)))]
            (apply concat
                   (permutations-summing-rec n y must-finish
                                             (filter #(and (not= x %)
                                                           (not= y %)) seq)
                                             (cons (list x must-start y)
                                                   accum))))))

(defn has-smallest-first? [s]
  (not (or (not (seq s))
           (seq (let [firsts (map first s)
                      ff (first firsts)]
                  (filter #(> ff %) firsts))))))

(defn permutations-summing [seq]
  (apply concat (for [x seq
                      y seq :when (not= x y)
                      z seq :when (and (not= z x) (not= z y))]
                  (let [n (+ x y z)
                        smaller-seq (filter #(and (not= x %)
                                                  (not= y %)
                                                  (not= z %)) seq)]
                    (filter (complement nil?)
                            (permutations-summing-rec n z y smaller-seq (list (list x y z))))))))

(defn largest-n-gon [n]
  (pipeline
    :reduce max
    :filter #(< % 10000000000000000)
    :map #(apply big-int-concat (apply concat %))
    :filter has-smallest-first?
    (permutations-summing (range 1 (inc (* 2 n))))))

;; (largest-n-gon 3)
;; 432621513

;; (largest-n-gon 5)
;; 6531031914842725 -- without 16 digit restraint => 28797161103104548

;}}}
;{{{ problem 69 -- totient quotient

;; 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]
  (if (= n 1)
    1
    (reduce * (map #(* (dec (first %))
                       (big-integer-pow (first %) (dec (frest %))))
                   (run-length-encode (factors n))))))

(defn totient-quotient [n]
  (reduce * (map #(/ % (dec %))
                 (distinct (factors n)))))

(defn max-totient-quotient [n]
  (frest (reduce max-first
                 (map #(list (totient-quotient %) %)
                      (range 2 (inc n))))))

;; (time (max-totient-quotient 1000000))
;; "Elapsed time: 25152.347 msecs"
;; "Elapsed time: 25949.301 msecs"
;; 510510
;; (factors 510510) (17 13 11 7 5 3 2)

;}}}
;{{{ problem 70 -- permuted totient quotient

;; 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))

(defn min-permuted-totient-quotient [n]
  (pipeline
    :frest
    :reduce min-first
    :map #(list (/ (frest %) (first %)) (frest %))
    :filter #(= (sort (to-digits (first %)))
                (sort (to-digits (frest %))))
    :map #(list (totient %) %)
    (range 2 n)))

(defn min-permuted-totient-quotient [n]
  (->>
    (range 2 n)
    (map #(list (totient %) %))
    (filter #(= (sort (to-digits (first %)))
                (sort (to-digits (frest %)))))
    (map #(list (/ (frest %) (first %)) (frest %)))
    (reduce min-first)
    frest
    ))

;; (min-permuted-totient-quotient 10000)

;; (time (min-permuted-totient-quotient 10000000))
;; "Elapsed time: 513006.925 msecs"
;; 8319823

;}}}

;{{{ problem 71 -- ordering fractions

;; Consider the fraction, n/d, where n and d are positive integers. If
;; nd and HCF(n,d)=1, it is called a reduced proper fraction.

;; If we list the set of reduced proper fractions for d <= 8 in ascending
;; order of size, we get:

;; 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5
;; 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8

;; It can be seen that 2/5 is the fraction immediately to the left of 3/7.

;; By listing the set of reduced proper fractions for d <= 1,000,000
;; in ascending order of size, find the numerator of the fraction
;; immediately to the left of 3/7.

(defn next-smallest-fraction [a b d]
  (- (/ a b)
     (/ (inc (rem (dec (* a d)) b))
        (* b d))))

(defn next-smallest-fraction-in-range [frac n]
  (let [a (. frac numerator)
        b (. frac denominator)]
    (pipeline
      :reduce max
      :map #(next-smallest-fraction a b %)
      (range 2 (inc n)))))

;; (time (next-smallest-fraction-in-range 3/7 1000000))
;; "Elapsed time: 5159.219 msecs"
;; 428570/999997

;}}}
;{{{ problem 72 -- number of reduced fractions

;; Consider the fraction, n/d, where n and d are positive integers. If
;; nd and HCF(n,d)=1, it is called a reduced proper fraction.

;; If we list the set of reduced proper fractions for d <= 8 in ascending
;; order of size, we get:

;; 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5
;; 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8

;; It can be seen that there are 21 elements in this set.

;; How many elements would be contained in the set of reduced proper
;; fractions for d <= 1,000,000?

(defn num-fractions [n]
  (pipeline
  :reduce +
  :map totient
  (range 2 (inc n))))

;; (time (num-fractions 1000000))
;; "Elapsed time: 20946.636 msecs"
;; 303963552391

;}}}
;{{{ problem 73 -- number of reduced fractions

;; Consider the fraction, n/d, where n and d are positive integers. If
;; n/d and HCF(n,d)=1, it is called a reduced proper fraction.

;; If we list the set of reduced proper fractions for d <= 8 in ascending
;; order of size, we get:

;; 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, **1/3, 3/8, 2/5, 3/7, 1/2**, 4/7, 3/5
;; 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8

;; It can be seen that there are 3 fractions between 1/3 and 1/2.

;; How many fractions lie between 1/3 and 1/2 in the sorted set of
;; reduced proper fractions for d <= 10,000?

(defn next-smallest-numerator [a b d]
  (let [x (dec (* a d))]
    (/ (- x (rem x b)) b)))

(defn next-largest-numerator [a b d]
  (let [x (* a d)]
    (inc (/ (- x (rem x b)) b))))

(defn reduced-fractions-between [d]
  (pipeline
    :count
    :filter #(= 1 (gcd d %))
    (range (next-largest-numerator 1 3 d)
           (inc (next-smallest-numerator 1 2 d)))))

(defn fractions-between [d]
  (pipeline
    :reduce +
    :map reduced-fractions-between
    (range 2 (inc d))))

;; (time (fractions-between 10000))
;; "Elapsed time: 5036.473 msecs"
;; 5066251

;}}}
;{{{ problem 74 -- sum of factorials of digits

;; The number 145 is well known for the property that the sum of the
;; factorial of its digits is equal to 145:

;; 1! + 4! + 5! = 1 + 24 + 120 = 145

;; Perhaps less well known is 169, in that it produces the longest
;; chain of numbers that link back to 169; it turns out that there are
;; only three such loops that exist:

;; 169  363601  1454  169
;; 871  45361  871
;; 872  45362  872

;; It is not difficult to prove that EVERY starting number will
;; eventually get stuck in a loop. For example

;; 69  363600  1454  169  363601 ( 1454)
;; 78  45360  871  45361 ( 871)
;; 540  145 ( 145)

;; Starting with 69 produces a chain of five non-repeating terms, but
;; the longest non-repeating chain with a starting number below one
;; million is sixty terms.

;; How many chains, with a starting number below one million, contain
;; exactly sixty non-repeating terms?

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

(defn member? [elt seq]
  (contains? (zipmap seq seq) elt))

(defn chain [item fn-or-map]
  ((fn this [item accum]
     (let [next (fn-or-map item)]
       (if (member? next accum)
           accum
         (recur next (cons next accum)))))
   item (list item)))

(defn chain-length [item fn-or-map]
  (count (chain item fn-or-map)))

(defn find-chains-of-length-less-than [x n]
  (pipeline
    :count
    :filter #(= x %)
    :map #(chain-length % sum-of-factorials-of-digits)
    (range n)))

;; (time (find-chains-of-length-less-than 60 1000000))
;; "Elapsed time: 545063.311 msecs"
;; 402

;}}}

;{{{ problem 75 -- wire right triangles

;; It turns out that 12 cm is the smallest length of wire that can be
;; bent to form an integer sided right angle triangle in exactly one
;; way, but there are many more examples.

;; 12 cm: (3,4,5)
;; 24 cm: (6,8,10)
;; 30 cm: (5,12,13)
;; 36 cm: (9,12,15)
;; 40 cm: (8,15,17)
;; 48 cm: (12,16,20)

;; In contrast, some lengths of wire, like 20 cm, cannot be bent to
;; form an integer sided right angle triangle, and other lengths allow
;; more than one solution to be found; for example, using 120 cm it is
;; possible to form exactly three different integer sided right angle
;; triangles.

;; 120 cm: (30,40,50), (20,48,52), (24,45,51)

;; Given that L is the length of the wire, for how many values of L <=
;; 2,000,000 can exactly one integer sided right angle triangle be
;; formed?


;; TOO SLOW!
;; (defn pythagorean-triples [n]
;;   ;; (count-uniq seq)
;;   (count
;;    (filter #(= 1 (frest %))
;;            (run-length-encode
;;             (sort (filter #(<= % n)
;;                           (for [x (iterate inc 1) :while (< x n)
;;                                 y (iterate inc 1) :while (and (<= y x)
;;                                                               (<= (+ x y) n))
;;                                                   :when (is-square? (+ (* x x) (* y y)))]
;;                             (+ x y (Math/round (Math/sqrt (+ (* x x) (* y y))))))))))))

;; I cheated on this one: http://en.wikipedia.org/wiki/Pythagorean_triple
(defn primitive-pythagorean-triples-below [max]
  (sort (for [m (range 1 max) ;; this could be improved...
              n (range 1 m)
              :while (<= (* 2 m (+ m n)) max)
              :when (and (= 1 (gcd m n))
                         (= 1 (+ (rem m 2)
                                 (rem n 2))))
              ]
          ;;     (+ (* 2 m n) (* 2 m m))
          (* 2 m (+ m n)))))

(defn multiples-below [n max]
  (take-while #(<= % max)
              (iterate #(+ % n) n)))

(defn run-length-encode-no-recur [s]
  ((fn [s accum]
    (if (or (empty? s)
            (nil? (first s)))
      (reverse accum)
      (let [f (first s)
            cnt (count-uniq s)]
        (recur (drop cnt s) (list* (list f cnt) accum)))))
   s (list)))

(defn pythagorean-triples [n]
  (pipeline
    :count
    :filter #(= 1 (frest %))
    :run-length-encode-no-recur
    :sort
    (mapcat #(multiples-below % n)
            (primitive-pythagorean-triples-below n))))

;; (time (pythagorean-triples 2000000))
;; "Elapsed time: 7997.541 msecs"
;; 214954

;}}}
;{{{ problem 76 -- partitions

;; It is possible to write five as a sum in exactly six different
;; ways:

;; 4 + 1
;; 3 + 2
;; 3 + 1 + 1
;; 2 + 2 + 1
;; 2 + 1 + 1 + 1
;; 1 + 1 + 1 + 1 + 1

;; How many different ways can one hundred be written as a sum of at
;; least two positive integers?

(defn partitions [n]
  ((fn this[n max]
     (cond (zero? n)
             (list (list))
           (< n 0)
             nil
           (= n 1)
             (list (list n))
           (= max 1)
             (list (replicate max 1))
           :else
             (reduce concat (for [x (range 1 (inc max))]
                             (map #(cons x %)
                                  (this (- n x) x))))))
   n n))

;; (defn num-partitions [n]
;;   (count (partitions n)))

(def num-partitions-helper
  (memoize
   (fn [n max]
     (cond (< n 0)
           0
           (or (zero? n)
               (= n 1)
               (= max 1))
           1
           :else
           (reduce + (for [x (range 1 (inc max))]
                       (num-partitions-helper (- n x) x)))))))

(defn num-partitions [n]
  (num-partitions-helper n n))

;; (defn num-partitions [n]
;;   ((fn this[n max]
;;      (cond (< n 0)
;;            0
;;            (or (zero? n)
;;                (= n 1)
;;                (= max 1))
;;            1
;;            :else
;;            (reduce + (for [x (range 1 (inc max))]
;;                        (this (- n x) x)))))
;;    n n))

;; (time (dec (num-partitions 100)))
;; "Elapsed time: 152553.962 msecs"
;; 190569291

;}}}
;{{{ problem 77 -- prime partitions

;; It is possible to write ten as the sum of primes in exactly five
;; different ways:

;; 7 + 3
;; 5 + 5
;; 5 + 3 + 2
;; 3 + 3 + 2 + 2
;; 2 + 2 + 2 + 2 + 2

;; What is the first value which can be written as the sum of primes
;; in over five thousand different ways?

(defn prime-partitions [n]
  ((fn this[n max]
     (cond (zero? n)
             (list (list))
           (and (= n 2) (= n 3))
             (list (list n))
           (or (= n 1) (< n 0))         ;the second should never happen
             nil
           :else
             (apply concat (for [x (primes-below (inc max))]
               (map #(cons x %)
                    (this (- n x) x))))))
   n n))

(defn find-prime-partitions [n]
  (pipeline
    :first
    :filter #(>= (first %) n)
    :map #(list (count (prime-partitions %)) %)
    (iterate inc 1)))

;; (time (find-prime-partitions 5000))
;; "Elapsed time: 1272.905 msecs"
;; (5007 71)

;}}}
;{{{ problem 78 -- number of partitions divisible by 1,000,000

;; Let p(n) represent the number of different ways in which n coins
;; can be separated into piles. For example, five coins can separated
;; into piles in exactly seven different ways, so p(5)=7.

;; OOOOO
;; OOOO   O
;; OOO   OO
;; OOO   O   O
;; OO   OO   O
;; OO   O   O   O
;; O   O   O   O   O

;; Find the least value of n for which p(n) is divisible by one million.

;; Cheated on this one: http://home.att.net/~numericana/answer/numbers.htm#partitions
;; linked to from http://en.wikipedia.org/wiki/Partition_(number_theory)#Partition_function
(def partition-number
  (memoize
   (fn [i]
     (if (<= i 1)
       1
       ;;     :else
       (let [signs (iterate #(- %) 1)
             t1 (reduce +
                        (map * signs
                             (map partition-number
                                  (take-while #(>= % 0)
                                              (map #(- i (/ (+ (* 3 % %) %) 2)) (iterate inc 1)))))
                        )
             t2 (reduce +
                        (map * signs
                             (map partition-number
                                  (take-while #(>= % 0)
                                              (map #(- i (/ (- (* 3 % %) %) 2)) (iterate inc 1)))))
                        )
             ]
         (+ t1 t2))))))

;; (defn find-big-partitions [n]
;;   (pipeline
;;     :first
;;     :filter #(zero? (rem (frest %) n))
;;     :map #(list % (partition-number %))
;;     (iterate inc 1)))

(defn find-big-partitions [n]
  (first (for [x (iterate inc 1) :when (zero? (rem (partition-number x) n))]
           x)))

;; (time (find-big-partitions 2000000))
;; "Elapsed time: 43391.771 msecs"
;; 55374

;}}}
;{{{ problem 79 -- shortest possible password *

;; A common security method used for online banking is to ask the user
;; for three random characters from a passcode. For example, if the
;; passcode was 531278, they may asked for the 2nd, 3rd, and 5th
;; characters; the expected reply would be: 317.

;; The text file, keylog.txt, contains fifty successful login attempts.

;; Given that the three characters are always asked for in order
;; analyse the file so as to determine the shortest possible secret
;; passcode of unknown length.


;}}}
;{{{ problem 80 -- square root sums *

;; It is well known that if the square root of a natural number is not
;; an integer, then it is irrational. The decimal expansion of such
;; square roots is infinite without any repeating pattern at all.

;; The square root of two is 1.41421356237309504880..., and the
;; digital sum of the first one hundred decimal digits is 475.

;; For the first one hundred natural numbers, find the total of the
;; digital sums of the first one hundred decimal digits for all the
;; irrational square roots.

(defn square-root-sum [n digits]
  )


(defn bob [n]
  (pipeline
    :map #(square-root-sum % 100)
    :filter (complement is-square?)
    (range 1 (inc n))))

;}}}

;{{{ problem 81 -- minimal path -- down, right *

;; In the 5 by 5 matrix below, the minimal path sum from the top left
;; to the bottom right, by only moving to the right and down, is
;; indicated in red and is equal to 2427.

;; 131 673 234 103 18
;; 201 96  342 965 150
;; 630 803 746 422 111
;; 537 699 497 121 956
;; 805 732 524 37  331

;; Find the minimal path sum, in matrix.txt (right click and 'Save
;; Link/Target As...'), a 31K text file containing a 80 by 80 matrix
;; from the top left to the bottom right by only moving right and
;; down.

(defn read-matrix [file]
  (map #(re-seq #"[0-9]+" %)
       (re-seq #".+" (slurp file))))

(def matrix (read-matrix "matrix.txt"))

(def small-matrix
     '((131 673 234 103 18)
       (201 96  342 965 150)
       (630 803 746 422 111)
       (537 699 497 121 956)
       (805 732 524 37  331)))

(defn get-row [matrix n]
  (nth matrix n))

(defn get-column [matrix n]
  (map #(nth % n) matrix))



;}}}
;{{{ problem 82 -- minimal path -- up, down, right *

;; NOTE: This problem is a more challenging version of Problem 81.

;; The minimal path sum in the 5 by 5 matrix below, by starting in any
;; cell in the left column and finishing in any cell in the right
;; column, and only moving up, down, and right, is indicated in red;
;; the sum is equal to 994.

;; 131  673 234 103 18
;; 201  96  342 965 150
;; 630  803 746 422 111
;; 537  699 497 121 956
;; 805  732 524 37  331

;; Find the minimal path sum, in matrix.txt (right click and 'Save
;; Link/Target As...'), a 31K text file containing a 80 by 80 matrix
;; from the left column to the right column.

;}}}
;{{{ problem 83 -- minimal path -- up, down, left, right *

;; NOTE: This problem is a significantly more challenging version of
;; Problem 81.

;; In the 5 by 5 matrix below, the minimal path sum from the top left
;; to the bottom right, by moving left, right, up, and down, is
;; indicated in red and is equal to 2297.

;; 131  673 234 103 18
;; 201  96  342 965 150
;; 630  803 746 422 111
;; 537  699 497 121 956
;; 805  732 524 37  331

;; Find the minimal path sum, in matrix.txt (right click and 'Save
;; Link/Target As...'), a 31K text file containing a 80 by 80 matrix
;; from the top left to the bottom right by moving left, right, up
;; and down.

;}}}
;{{{ problem 84 -- monopoly probabilities *

;; In the game, Monopoly, the standard board is set up in the following way:

;; GO  A1  CC1  A2  T1  R1  B1  CH1  B2  B3  JAIL
;; H2                                        C1
;; T2                                        U1
;; H1                                        C2
;; CH3                                       C3
;; R4                                        R2
;; G3                                        D1
;; CC3                                       CC2
;; G2                                        D2
;; G1                                        D3
;; G2J  F3  U2  F2  F1  R3  E3  E2  CH2  E1  FP

;; A player starts on the GO square and adds the scores on two 6-sided
;; dice to determine the number of squares they advance in a clockwise
;; direction. Without any further rules we would expect to visit each
;; square with equal probability: 2.5%. However, landing on G2J (Go To
;; Jail), CC (community chest), and CH (chance) changes this
;; distribution.

;; In addition to G2J, and one card from each of CC and CH, that
;; orders the player to go to directly jail, if a player rolls three
;; consecutive doubles, they do not advance the result of their 3rd
;; roll. Instead they proceed directly to jail.

;; At the beginning of the game, the CC and CH cards are
;; shuffled. When a player lands on CC or CH they take a card from the
;; top of the respective pile and, after following the instructions
;; it is returned to the bottom of the pile. There are sixteen cards
;; in each pile, but for the purpose of this problem we are only
;; concerned with cards that order a movement; any instruction not
;; concerned with movement will be ignored and the player will remain
;; on the CC/CH square.

;; Community Chest (2/16 cards):
;; Advance to GO
;; Go to JAIL
;; Chance (10/16 cards):
;; Advance to GO
;; Go to JAIL
;; Go to C1
;; Go to E3
;; Go to H2
;; Go to R1
;; Go to next R (railway company)
;; Go to next R
;; Go to next U (utility company)
;; Go back 3 squares.

;; The heart of this problem concerns the likelihood of visiting a
;; particular square. That is, the probability of finishing at that
;; square after a roll. For this reason it should be clear that, with
;; the exception of G2J for which the probability of finishing on it
;; is zero, the CH squares will have the lowest probabilities, as 5/8
;; request a movement to another square, and it is the final square
;; that the player finishes at on each roll that we are interested
;; in. We shall make no distinction between "Just Visiting" and being
;; sent to JAIL, and we shall also ignore the rule about requiring a
;; double to "get out of jail", assuming that they pay to get out on
;; their next turn.

;; By starting at GO and numbering the squares sequentially from 00 to
;; 39 we can concatenate these two-digit numbers to produce strings
;; that correspond with sets of squares.

;; Statistically it can be shown that the three most popular squares
;; in order, are JAIL (6.24%) = Square 10, E3 (3.18%) = Square 24, and
;; GO (3.09%) = Square 00. So these three most popular squares can be
;; listed with the six-digit modal string: 102400.

;; If, instead of using two 6-sided dice, two 4-sided dice are used
;; find the six-digit modal string.

;}}}
;{{{ problem 85 -- number of rectangles

;; By counting carefully it can be seen that a rectangular grid
;; measuring 3 by 2 contains eighteen rectangles:

;; Although there exists no rectangular grid that contains exactly two
;; million rectangles, find the area of the grid with the nearest
;; solution.

(defn num-rectangles [a b]
  (reduce + (for [x (range 1 (inc a))
                  y (range 1 (inc b))]
              (* x y))))

(defn find-big-retangles [n num]
  (pipeline
;;     :frest
    :reduce min-first
    :take num
    (for [a (iterate inc 1)
          b (range 1 (inc a))]
      (list (abs (- n (num-rectangles a b))) (* a b)))))

;; (time (find-big-retangles 2000000 3000))
;; "Elapsed time: 2405.318 msecs"
;; (2 2772)

;}}}

;{{{ problem 86 -- cuboid path *

;; A spider, S, sits in one corner of a cuboid room, measuring 6 by 5
;; by 3, and a fly, F, sits in the opposite corner. By travelling on
;; the surfaces of the room the shortest "straight line" distance from
;; S to F is 10 and the path is shown on the diagram.

;; However, there are up to three "shortest" path candidates for any
;; given cuboid and the shortest route is not always integer.

;; By considering all cuboid rooms up to a maximum size of M by M by
;; M, there are exactly 2060 cuboids for which the shortest distance
;; is integer when M=100, and this is the least value of M for which
;; the number of solutions first exceeds two thousand; the number of
;; solutions is 1975 when M=99.

;; Find the least value of M such that the number of solutions first
;; exceeds one million.



;}}}
;{{{ problem 87 -- prime square, cube and fourth power **

;; The smallest number expressible as the sum of a prime square, prime
;; cube, and prime fourth power is 28. In fact, there are exactly four
;; numbers below fifty that can be expressed in such a way:

;; 28 = 2^2 + 2^3 + 2^4
;; 33 = 3^2 + 2^3 + 2^4
;; 49 = 5^2 + 2^3 + 2^4
;; 47 = 2^2 + 3^3 + 2^4
;; How many numbers below fifty million can be expressed as the sum of
;; a prime square, prime cube, and prime fourth power?

(defn prime-squares-cubes-fourths-below [n]
  (pipeline
    :count
    :distinct
;;     :sort
    (for [a primes :while (< (* a a) n)
          b primes :while (< (+ (* a a) (* b b b)) n)
          c primes :while (< (+ (* a a) (* b b b) (* c c c c)) n)
          ]
      (+ (* a a) (* b b b) (* c c c c)))))

;; (time (prime-squares-cubes-fourths-below 50000000))

;}}}
;{{{ problem 88 -- minimal product sum *

;; A natural number, N, that can be written as the sum and product of
;; a given set of at least two natural numbers, {a1, a2, ... , ak} is
;; called a product-sum number: N = a1 + a2 + ... + ak = a1 a2 ... ak.

;; For example, 6 = 1 + 2 + 3 = 1  2  3.

;; For a given set of size, k, we shall call the smallest N with this
;; property a minimal product-sum number. The minimal product-sum
;; numbers for sets of size, k = 2, 3, 4, 5, and 6 are as follows.

;; k=2: 4 = 2  2 = 2 + 2
;; k=3: 6 = 1  2  3 = 1 + 2 + 3
;; k=4: 8 = 1  1  2  4 = 1 + 1 + 2 + 4
;; k=5: 8 = 1  1  2  2  2 = 1 + 1 + 2 + 2 + 2
;; k=6: 12 = 1  1  1  1  2  6 = 1 + 1 + 1 + 1 + 2 + 6

;; Hence for 2 <= k <= 6, the sum of all the minimal product-sum
;; numbers is 4+6+8+12 = 30; note that 8 is only counted once in the
;; sum.

;; In fact, as the complete set of minimal product-sum numbers for
;; 2 <= k <= 12 is {4, 6, 8, 12, 15, 16}, the sum is 61.

;; What is the sum of all the minimal product-sum numbers for 2 <= k <= 12000?

;}}}
;{{{ problem 89 -- roman numerals in minimal form

;; The rules for writing Roman numerals allow for many ways of writing
;; each number (see FAQ: Roman Numerals). However, there is always a
;; "best" way of writing a particular number.

;; For example, the following represent all of the legitimate ways of
;; writing the number sixteen:

;; IIIIIIIIIIIIIIII
;; VIIIIIIIIIII
;; VVIIIIII
;; XIIIIII
;; VVVI
;; XVI

;; The last example being considered the most efficient, as it uses
;; the least number of numerals.

;; The 11K text file, roman.txt (right click and 'Save Link/Target
;; As...'), contains one thousand numbers written in valid, but not
;; necessarily minimal, Roman numerals; that is, they are arranged in
 ;; descending units and obey the subtractive pair rule (see FAQ for
;; the definitive rules for this problem).

;; Find the number of characters saved by writing each of these in
;; their minimal form.

;; Note: You can assume that all the Roman numerals in the file
;; contain no more than four consecutive identical units.

;; {{{ FAQ:

;; Traditional Roman numerals are made up of the following denominations:

;; I = 1
;; V = 5
;; X = 10
;; L = 50
;; C = 100
;; D = 500
;; M = 1000

;; You will read about many different rules concerning Roman numerals
;; but the truth is that the Romans only had one simple rule:

;; Numerals must be arranged in descending order of size.

;; For example, three ways that sixteen could be written are XVI
;; XIIIIII, VVVI; the first being the preferred form as it uses the
;; least number of numerals.

;; The "descending size" rule was introduced to allow the use of
;; subtractive combinations. For example, four can be written IV
;; because it is one before five. As the rule requires that the
;; numerals be arranged in order of size it should be clear to a
;; reader that the presence of a smaller numeral out of place, so to
;; speak, was unambiguously to be subtracted from the following
;; numeral. For example, nineteen could be written XIX = X + IX
;; (9). Note also how the rule requires X (ten) be placed before IX
;; (nine), and IXX would not be an acceptable configuration.

;; Generally the Romans tried to use as few numerals as possible when
;; displaying numbers. For this reason, XIX would be the preferred
;; form of nineteen over other valid combinations, like XVIIII or
;; XVIV. However, this was NOT a rule and there still remain in Rome
;; many examples where economy of numerals has not been employed. For
;; example, in the famous Colesseum the the numerals above the
;; forty-ninth entrance is written XXXXVIIII and not IL nor XLIX (see
;; rules below).

;; Despite this, over time we have continued to introduce new
;; restrictive rules. By mediaeval times it had become standard
;; practice to avoid more than three consecutive identical
;; numerals. That is, IV would be written instead of IIII, IX would be
;; used instead of VIIII, and so on. In addition, the subtractive
;; combinations had the following rules superimposed:

;; * Only I, X, and C can be used as the leading numeral in part of a subtractive pair.
;; * I can only be placed before V and X.
;; * X can only be placed before L and C.
;; * C can only be placed before D and M.

;; These last four rules are considered to be law, and generally it is
;; preferred, but not necessary, to display numbers using the minimum
;; number of numerals. Which means that IL is considered an invalid
;; way of writing forty-nine, and whereas XXXXVIIII, XXXXIX, XLVIIII
;; and XLIX are all quite legitimate, the latter is the preferred
;; (minimal) form.

;; It is also expected that higher denominations should be used
;; whenever possible; for example, L should be used in place of XXXXX
;; or C should be used in place of LL. However, even this "rule" has
;; been flaunted: in the church of Sant'Agnese fuori le Mura (St
;; Agnes' outside the walls), found in Rome, the date, MCCCCCCVI
;; (1606), is written on the gilded and coffered wooden ceiling; I am
;; sure that many would argue that it should have been written MDCVI.

;; However, if we believe the adage, "when in Rome do as the Romans
;; do," and we see how the Romans write numerals, then it clearly
;; gives us much more freedom than many would care to admit.

;; }}}

(defn roman2num [roman]
  ((fn [accum x r]
     (cond (empty? r)
             (+ accum x)
           (and (not= 0 x)
                (< x (first r)))
             (recur (- accum x) (first r) (rest r))
           :else
             (recur (+ accum x) (first r) (rest r))))
   0 0
   (for [letter roman]
     (condp = letter
              \I 1
              \V 5
              \X 10
              \L 50
              \C 100
              \D 500
              \M 1000
              ;; default
              0))))

(defn romanize-ten [num one five ten]
  (let [r (rem num 5)]
    (if (= r 4)
      (list one (if (> num 5) ten five))
      (concat (if (>= num 5) (list five)) (take r (repeat one))))))

(defn num2roman [num]
  (concat
   (take (int (quot num 1000)) (repeat \M))
   (romanize-ten (rem (quot num 100) 10) \C \D \M)
   (romanize-ten (rem (quot num 10)  10) \X \L \C)
   (romanize-ten (rem       num      10) \I \V \X)))

(defn roman-shrink [roman]
;;   (prn roman)
;;   (prn (num2roman (roman2num roman)))
  (- (count roman)
     (count (num2roman (roman2num roman)))))

(defn roman-savings [file]
  (pipeline
    :reduce +
    :map roman-shrink
    (re-seq #"\w+" (slurp file))))

;; (time (roman-savings "roman.txt"))
;; "Elapsed time: 98.535 msecs"
;; 743

;}}}
;{{{ problem 90 -- two cubes to make a square

;; Each of the six faces on a cube has a different digit (0 to 9)
;; written on it; the same is done to a second cube. By placing the
;; two cubes side-by-side in different positions we can form a variety
;; of 2-digit numbers.

;; For example, the square number 64 could be formed:


;; In fact, by carefully choosing the digits on both cubes it is
;; possible to display all of the square numbers below one-hundred:
;; 01, 04, 09, 16, 25, 36, 49, 64, and 81.

;; For example, one way this can be achieved is by placing {0, 5, 6
;; 7, 8, 9} on one cube and {1, 2, 3, 4, 8, 9} on the other cube.

;; However, for this problem we shall allow the 6 or 9 to be turned
;; upside-down so that an arrangement like {0, 5, 6, 7, 8, 9} and {1
;; 2, 3, 4, 6, 7} allows for all nine square numbers to be displayed;
;; otherwise it would be impossible to obtain 09.

;; In determining a distinct arrangement we are interested in the
;; digits on each cube, not the order.

;; {1, 2, 3, 4, 5, 6} is equivalent to {3, 6, 4, 1, 2, 5}
;; {1, 2, 3, 4, 5, 6} is distinct from {1, 2, 3, 4, 5, 9}

;; But because we are allowing 6 and 9 to be reversed, the two
;; distinct sets in the last example both represent the extended set
;; {1, 2, 3, 4, 5, 6, 9} for the purpose of forming 2-digit numbers.

;; How many distinct arrangements of the two cubes allow for all of
;; the square numbers to be displayed?

(def must-create '((0 1) (0 4) (0 6)
                   (1 6) (2 5) (3 6)
                   (4 6) (6 4) (8 1)))

(defn rfirst [seq]
  (next (first seq)))

(defn generate-cubes [s die1 die2]
;;   (prn s die1 die2)
  (if (seq s)
    (concat (generate-cubes (rest s)
                       (map #(cons (ffirst s) %) die1)
                       (map #(cons (first (rfirst s)) %) die2))
            (generate-cubes (rest s)
                       (map #(cons (ffirst s) %) die2)
                       (map #(cons (first (rfirst s)) %) die1)))
    (list (list die1 die2))))

(defn expound-cube [cube]
  (cond (> (count cube) 6)
        nil
        (= (count cube) 6) ; Here I need to check for a six, and if so add one with a nine
        (if (and (cube 6)
                 (not (cube 9)))
            (list cube
                  (set (filter #(not= % 6) (cons 9 cube)))) ; This seems like it should be much simpler than it is
          (list cube))
        :else
        (apply concat (for [x (range 10) :when (not (cube x))]
                  (expound-cube (set (cons x cube)))))))

(defn expound-cubes [cubes]
  (let [cube1s (expound-cube (first cubes))
        cube2s (expound-cube (frest cubes))]
    (for [x cube1s
          y cube2s]
      (list x y))))

(defn num-cubes []
  (pipeline
    :count
    :set
    :map set
    :mapcat expound-cubes
;;     :filter #(and (<= (count (first %)) 7)
;;                   (<= (count (frest %)) 7))
    :map #(set (list (set (ffirst %))
                     (set (first (frest %)))))
    (generate-cubes must-create '(()) '(()))))

;; (time (num-cubes))
;; "Elapsed time: 693.771 msecs"
;; 1217

;}}}






;; memoize
;; (comp f g h) -> f(g(h(*)))



;; This is perhaps a similar problem.

;; http://www.cs.umd.edu/~gasarch/BLOGPAPERS/17x17almost.txt
;; http://bit-player.org/2009/the-17x17-challenge

;; 00000111122223333
;; 01111122223333000
;; 02222133320003111
;; 03333100021113222
;; 10123212332300301
;; 11032221033210032
;; 12301230130120123
;; 13210203231030210
;; 20231313002011312
;; 21320320303101021
;; 22013331200231130
;; 23102302101321203
;; 30312010212132320
;; 31203023113022013
;; 32130032010312102
;; 33021001311202231
;; 0123+012301230123

;; The + is the point that is not colored. I got this grid by trying to add a
;; row to a 4-coloring of a 16x17 grid.




;; http://clojars.org/
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.