/
problem29.lhs
105 lines (75 loc) · 2.68 KB
/
problem29.lhs
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
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Module : problem29
%% Copyright : (c) 2010 David M. Rosenberg
%% License : BSD3
%%
%% Maintainer : David Rosenberg <rosenbergdm@uchicago.edu>
%% Stability : experimental
%% Portability : portable
%% Created : Sat Mar 27 08:58:25 CDT 2010
%%
%% Description :
%% Project euler problem solution.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\documentclass{article}
%include colorcode.fmt
\usepackage{graphicx}
\usepackage{color}
\usepackage{pgf}
\begin{document}
\section{Problem}
Consider all integer combinations of $a^b$ for $2 \leq a \leq 5$
and $2 \leq b \leq 5$:
\begin{tabular}{llll}
$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$
\end{tabular}
If they are then placed in numerical order, with any repeats removed, we get
the following sequence of 15 distinct terms:
\begin{displaymath}
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
\end{displaymath}
How many distinct terms are in the sequence generated by $a^b$ for
$2 \leq a \leq 100$ and $2 \leq b \leq 100$?
\section{Solution}
\colorhs
\begin{code}
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import System.Environment
import Data.Numbers
import qualified Data.Set as Set
isPerfectPower :: Integer -> Bool
isPerfectPower x =
let pf = group $ primeFactors x
pl = max 2 (length $ maximumBy (\a b -> compare (length a) (length b)) pf)
unitFactors = filter (\z -> length z /= pl) pf
in unitFactors == []
getPerfectExponent :: Integer -> Int
getPerfectExponent x = (length . head . group . primeFactors) x
numUniqueEntries a b
| not $ isPerfectPower a = b - 1
| otherwise = unEls
where pexp = getPerfectExponent a
fset = Set.fromList [pexp * i | i <- [2..b]]
nonUnique = Set.fromList [i * j | i <- [2..b], j <- [1..(pexp-1)] ]
unEls = Set.size $ Set.difference fset nonUnique
main = do
let nUnique = sum $ map (\a -> numUniqueEntries a 100) [2..100]
putStrLn $ "There are a total of " ++ show nUnique ++
" distinct elements in the set {a^b | 2 <= a <= 100, 2 <= b <= 100}."
\end{code}
\section{Result}
\begin{verbatim}
runhaskell problem29.lhs
There are a total of 9183 distinct elements in the set {a^b | 2 <= a <= 100, 2 <= b <= 100}.
\end{verbatim}
There are a total of 9183 distinct elements in the set
$$
\{ a^b : 2 \leq a \leq 100, 2 \leq b \leq 100 \}
$$
\end{document}
% vim: ft=lhaskell softtabstop=2 shiftwidth=2