import Data.List (isPrefixOf)
import Graphics.Gnuplot.Simple (Attribute (Key, PNG), plotList)
-- 1ª definición
-- =============
menorPotencia :: Integer -> (Integer,Integer)
menorPotencia n =
head [(k,m) | (k,m) <- zip [0..] potenciasDe2
, cs `isPrefixOf` show m]
where cs = show n
-- potenciasDe 2 es la lista de las potencias de dos. Por ejemplo,
-- take 12 potenciasDe2 == [1,2,4,8,16,32,64,128,256,512,1024,2048]
potenciasDe2 :: [Integer]
potenciasDe2 = iterate (*2) 1
-- 2ª definición
-- =============
menorPotencia2 :: Integer -> (Integer,Integer)
menorPotencia2 n = aux (0,1)
where aux (k,m) | cs `isPrefixOf` show m = (k,m)
| otherwise = aux (k+1,2*m)
cs = show n
-- 3ª definición
-- =============
menorPotencia3 :: Integer -> (Integer,Integer)
menorPotencia3 n =
until (isPrefixOf n1 . show . snd) (\(x,y) -> (x+1,2*y)) (0,1)
where n1 = show n
-- Comparación de eficiencia
-- =========================
-- λ> maximum [fst (menorPotencia n) | n <- [1..1000]]
-- 3973
-- (3.69 secs, 1,094,923,696 bytes)
-- λ> maximum [fst (menorPotencia2 n) | n <- [1..1000]]
-- 3973
-- (5.13 secs, 1,326,382,872 bytes)
-- λ> maximum [fst (menorPotencia3 n) | n <- [1..1000]]
-- 3973
-- (4.71 secs, 1,240,498,128 bytes)
graficaMenoresExponentes :: Integer -> IO ()
graficaMenoresExponentes n =
plotList [ Key Nothing
, PNG "Menor_potencia_de_2_que_comienza_por_n.png"
]
(map (fst . menorPotencia) [1..n]) |
LocalWords: Key