{"id":7409,"date":"2022-09-22T07:00:46","date_gmt":"2022-09-22T05:00:46","guid":{"rendered":"http:\/\/www.glc.us.es\/~jalonso\/exercitium\/?p=7409"},"modified":"2022-12-14T14:26:16","modified_gmt":"2022-12-14T12:26:16","slug":"divisores-de-un-numero","status":"publish","type":"post","link":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/divisores-de-un-numero\/","title":{"rendered":"Divisores de un n\u00famero"},"content":{"rendered":"<p>Definir la funci\u00f3n<\/p>\n<pre lang=\"text\">\n   divisores :: Integer -> [Integer]\n<\/pre>\n<p>tal que <code>divisores n<\/code> es la lista de los divisores de <code>n<\/code>. Por ejemplo,<\/p>\n<pre lang=\"text\">\n  divisores 30  ==  [1,2,3,5,6,10,15,30]\n  length (divisores (product [1..10]))  ==  270\n  length (divisores (product [1..25]))  ==  340032\n<\/pre>\n<p><b>Soluciones<\/b><\/p>\n<p>A continuaci\u00f3n se muestran las <a href=\"#haskell\">soluciones en Haskell<\/a> y las <a href=\"#python\">soluciones en Python<\/a>.<\/p>\n<p><a name=\"haskell\"><\/a><br \/>\n<b>Soluciones en Haskell<\/b><\/p>\n<pre lang=\"haskell\">\nimport Data.List (group, inits, nub, sort, subsequences)\nimport Data.Numbers.Primes (primeFactors)\nimport Data.Set (toList)\nimport Math.NumberTheory.ArithmeticFunctions (divisors)\nimport Test.QuickCheck\n\n-- 1\u00aa soluci\u00f3n\n-- ===========\n\ndivisores1 :: Integer -> [Integer]\ndivisores1 n = [x | x <- [1..n], n `rem` x == 0]\n\n-- 2\u00aa soluci\u00f3n\n-- ===========\n\ndivisores2 :: Integer -> [Integer]\ndivisores2 n = [x | x <- [1..n], x `esDivisorDe` n]\n\n-- (esDivisorDe x n) se verifica si x es un divisor de n. Por ejemplo,\n--    esDivisorDe 2 6  ==  True\n--    esDivisorDe 4 6  ==  False\nesDivisorDe :: Integer -> Integer -> Bool\nesDivisorDe x n = n `rem` x == 0\n\n-- 3\u00aa soluci\u00f3n\n-- ===========\n\ndivisores3 :: Integer -> [Integer]\ndivisores3 n = filter (`esDivisorDe` n) [1..n]\n\n-- 4\u00aa soluci\u00f3n\n-- ===========\n\ndivisores4 :: Integer -> [Integer]\ndivisores4 = filter <$> flip esDivisorDe <*> enumFromTo 1\n\n-- 5\u00aa soluci\u00f3n\n-- ===========\n\ndivisores5 :: Integer -> [Integer]\ndivisores5 n = xs ++ [n `div` y | y <- ys]\n  where xs = primerosDivisores1 n\n        (z:zs) = reverse xs\n        ys | z^2 == n  = zs\n           | otherwise = z:zs\n\n-- (primerosDivisores n) es la lista de los divisores del n\u00famero n cuyo\n-- cuadrado es menor o gual que n. Por ejemplo,\n--    primerosDivisores 25  ==  [1,5]\n--    primerosDivisores 30  ==  [1,2,3,5]\nprimerosDivisores1 :: Integer -> [Integer]\nprimerosDivisores1 n =\n   [x | x <- [1..round (sqrt (fromIntegral n))],\n        x `esDivisorDe` n]\n\n-- 6\u00aa soluci\u00f3n\n-- ===========\n\ndivisores6 :: Integer -> [Integer]\ndivisores6 n = aux [1..n]\n  where aux [] = []\n        aux (x:xs) | x `esDivisorDe` n = x : aux xs\n                   | otherwise         = aux xs\n\n-- 7\u00aa soluci\u00f3n\n-- ===========\n\ndivisores7 :: Integer -> [Integer]\ndivisores7 n = xs ++ [n `div` y | y <- ys]\n  where xs = primerosDivisores2 n\n        (z:zs) = reverse xs\n        ys | z^2 == n  = zs\n           | otherwise = z:zs\n\nprimerosDivisores2 :: Integer -> [Integer]\nprimerosDivisores2 n = aux [1..round (sqrt (fromIntegral n))]\n  where aux [] = []\n        aux (x:xs) | x `esDivisorDe` n = x : aux xs\n                   | otherwise         = aux xs\n\n-- 8\u00aa soluci\u00f3n\n-- ===========\n\ndivisores8 :: Integer -> [Integer]\ndivisores8 =\n  nub . sort . map product . subsequences . primeFactors\n\n-- 9\u00aa soluci\u00f3n\n-- ===========\n\ndivisores9 :: Integer -> [Integer]\ndivisores9 = sort\n           . map (product . concat)\n           . productoCartesiano\n           . map inits\n           . group\n           . primeFactors\n\n-- (productoCartesiano xss) es el producto cartesiano de los conjuntos\n-- xss. Por ejemplo,\n--    \u03bb> productoCartesiano [[1,3],[2,5],[6,4]]\n--    [[1,2,6],[1,2,4],[1,5,6],[1,5,4],[3,2,6],[3,2,4],[3,5,6],[3,5,4]]\nproductoCartesiano :: [[a]] -> [[a]]\nproductoCartesiano []       = [[]]\nproductoCartesiano (xs:xss) =\n  [x:ys | x <- xs, ys <- productoCartesiano xss]\n\n-- 10\u00aa soluci\u00f3n\n-- ============\n\ndivisores10 :: Integer -> [Integer]\ndivisores10 = sort\n            . map (product . concat)\n            . mapM inits\n            . group\n            . primeFactors\n\n-- 11\u00aa soluci\u00f3n\n-- ============\n\ndivisores11 :: Integer -> [Integer]\ndivisores11 = toList . divisors\n\n-- Comprobaci\u00f3n de equivalencia\n-- ============================\n\n-- La propiedad es\nprop_divisores :: Positive Integer -> Bool\nprop_divisores (Positive n) =\n  all (== divisores1 n)\n      [ divisores2 n\n      , divisores3 n\n      , divisores4 n\n      , divisores5 n\n      , divisores6 n\n      , divisores7 n\n      , divisores8 n\n      , divisores9 n\n      , divisores10 n\n      , divisores11 n\n      ]\n\n-- La comprobaci\u00f3n es\n--    \u03bb> quickCheck prop_divisores\n--    +++ OK, passed 100 tests.\n\n-- Comparaci\u00f3n de la eficiencia\n-- ============================\n\n-- La comparaci\u00f3n es\n--    \u03bb> length (divisores1 (product [1..11]))\n--    540\n--    (18.55 secs, 7,983,950,592 bytes)\n--    \u03bb> length (divisores2 (product [1..11]))\n--    540\n--    (18.81 secs, 7,983,950,592 bytes)\n--    \u03bb> length (divisores3 (product [1..11]))\n--    540\n--    (12.79 secs, 6,067,935,544 bytes)\n--    \u03bb> length (divisores4 (product [1..11]))\n--    540\n--    (12.51 secs, 6,067,935,592 bytes)\n--    \u03bb> length (divisores5 (product [1..11]))\n--    540\n--    (0.03 secs, 1,890,296 bytes)\n--    \u03bb> length (divisores6 (product [1..11]))\n--    540\n--    (21.46 secs, 9,899,961,392 bytes)\n--    \u03bb> length (divisores7 (product [1..11]))\n--    540\n--    (0.02 secs, 2,195,800 bytes)\n--    \u03bb> length (divisores8 (product [1..11]))\n--    540\n--    (0.09 secs, 107,787,272 bytes)\n--    \u03bb> length (divisores9 (product [1..11]))\n--    540\n--    (0.02 secs, 2,150,472 bytes)\n--    \u03bb> length (divisores10 (product [1..11]))\n--    540\n--    (0.01 secs, 1,652,120 bytes)\n--    \u03bb> length (divisores11 (product [1..11]))\n--    540\n--    (0.01 secs, 796,056 bytes)\n--\n--    \u03bb> length (divisores5 (product [1..17]))\n--    10752\n--    (10.16 secs, 3,773,953,128 bytes)\n--    \u03bb> length (divisores7 (product [1..17]))\n--    10752\n--    (9.83 secs, 4,679,260,712 bytes)\n--    \u03bb> length (divisores9 (product [1..17]))\n--    10752\n--    (0.06 secs, 46,953,344 bytes)\n--    \u03bb> length (divisores10 (product [1..17]))\n--    10752\n--    (0.02 secs, 33,633,712 bytes)\n--    \u03bb> length (divisores11 (product [1..17]))\n--    10752\n--    (0.03 secs, 6,129,584 bytes)\n--\n--    \u03bb> length (divisores10 (product [1..27]))\n--    677376\n--    (2.14 secs, 3,291,277,736 bytes)\n--    \u03bb> length (divisores11 (product [1..27]))\n--    677376\n--    (0.56 secs, 396,042,280 bytes)\n<\/pre>\n<p>El c\u00f3digo se encuentra en <a href=\"https:\/\/github.com\/jaalonso\/Exercitium\/blob\/main\/src\/Divisores_de_un_numero.hs\">GitHub<\/a>.<\/p>\n<p><a name=\"python\"><\/a><br \/>\n<b>Soluciones en Python<\/b><\/p>\n<pre lang=\"python\">\nfrom math import factorial, sqrt\nfrom timeit import Timer, default_timer\nfrom sys import setrecursionlimit\nfrom sympy import divisors\nfrom hypothesis import given, strategies as st\n\nsetrecursionlimit(10**6)\n\n# 1\u00aa soluci\u00f3n\n# ===========\n\ndef divisores1(n: int) -> list[int]:\n    return [x for x in range(1, n + 1) if n % x == 0]\n\n# 2\u00aa soluci\u00f3n\n# ===========\n\n# esDivisorDe(x, n) se verifica si x es un divisor de n. Por ejemplo,\n#    esDivisorDe(2, 6)  ==  True\n#    esDivisorDe(4, 6)  ==  False\ndef esDivisorDe(x: int, n: int) -> bool:\n    return n % x == 0\n\ndef divisores2(n: int) -> list[int]:\n    return [x for x in range(1, n + 1) if esDivisorDe(x, n)]\n\n# 3\u00aa soluci\u00f3n\n# ===========\n\ndef divisores3(n: int) -> list[int]:\n    return list(filter(lambda x: esDivisorDe(x, n), range(1, n + 1)))\n\n# 4\u00aa soluci\u00f3n\n# ===========\n\n# primerosDivisores(n) es la lista de los divisores del n\u00famero n cuyo\n# cuadrado es menor o gual que n. Por ejemplo,\n#    primerosDivisores(25)  ==  [1,5]\n#    primerosDivisores(30)  ==  [1,2,3,5]\ndef primerosDivisores(n: int) -> list[int]:\n    return [x for x in range(1, 1 + round(sqrt(n))) if n % x == 0]\n\ndef divisores4(n: int) -> list[int]:\n    xs = primerosDivisores(n)\n    zs = list(reversed(xs))\n    if zs[0]**2 == n:\n        return xs + [n \/\/ a for a in zs[1:]]\n    return xs + [n \/\/ a for a in zs]\n\n# 5\u00aa soluci\u00f3n\n# ===========\n\ndef divisores5(n: int) -> list[int]:\n    def aux(xs: list[int]) -> list[int]:\n        if xs:\n            if esDivisorDe(xs[0], n):\n                return [xs[0]] + aux(xs[1:])\n            return aux(xs[1:])\n        return xs\n\n    return aux(list(range(1, n + 1)))\n\n# 6\u00aa soluci\u00f3n\n# ============\n\ndef divisores6(n: int) -> list[int]:\n    xs = []\n    for x in range(1, n+1):\n        if n % x == 0:\n            xs.append(x)\n    return xs\n\n# 7\u00aa soluci\u00f3n\n# ===========\n\ndef divisores7(n: int) -> list[int]:\n    x = 1\n    xs = []\n    ys = []\n    while x * x < n:\n        if n % x == 0:\n            xs.append(x)\n            ys.append(n \/\/ x)\n        x = x + 1\n    if x * x == n:\n        xs.append(x)\n    return xs + list(reversed(ys))\n\n# 8\u00aa soluci\u00f3n\n# ============\n\ndef divisores8(n: int) -> list[int]:\n    return divisors(n)\n\n# Comprobaci\u00f3n de equivalencia\n# ============================\n\n# La propiedad es\n@given(st.integers(min_value=2, max_value=1000))\ndef test_divisores(n):\n    assert divisores1(n) ==\\\n           divisores2(n) ==\\\n           divisores3(n) ==\\\n           divisores4(n) ==\\\n           divisores5(n) ==\\\n           divisores6(n) ==\\\n           divisores7(n) ==\\\n           divisores8(n)\n\n# La comprobaci\u00f3n es\n#    src> poetry run pytest -q divisores_de_un_numero.py\n#    1 passed in 0.84s\n\n# Comparaci\u00f3n de eficiencia\n# =========================\n\ndef tiempo(e):\n    \"\"\"Tiempo (en segundos) de evaluar la expresi\u00f3n e.\"\"\"\n    t = Timer(e, \"\", default_timer, globals()).timeit(1)\n    print(f\"{t:0.2f} segundos\")\n\n# La comparaci\u00f3n es\n#    >>> tiempo('divisores5(4*factorial(7))')\n#    1.40 segundos\n#\n#    >>> tiempo('divisores1(factorial(11))')\n#    1.79 segundos\n#    >>> tiempo('divisores2(factorial(11))')\n#    3.80 segundos\n#    >>> tiempo('divisores3(factorial(11))')\n#    5.22 segundos\n#    >>> tiempo('divisores4(factorial(11))')\n#    0.00 segundos\n#    >>> tiempo('divisores6(factorial(11))')\n#    3.51 segundos\n#    >>> tiempo('divisores7(factorial(11))')\n#    0.00 segundos\n#    >>> tiempo('divisores8(factorial(11))')\n#    0.00 segundos\n#\n#    >>> tiempo('divisores4(factorial(17))')\n#    2.23 segundos\n#    >>> tiempo('divisores7(factorial(17))')\n#    3.22 segundos\n#    >>> tiempo('divisores8(factorial(17))')\n#    0.00 segundos\n#\n#    >>> tiempo('divisores8(factorial(27))')\n#    0.28 segundos\n<\/pre>\n<p>El c\u00f3digo se encuentra en <a href=\"https:\/\/github.com\/jaalonso\/Exercitium-Python\/blob\/main\/src\/divisores_de_un_numero.py\">GitHub<\/a>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Definir la funci\u00f3n divisores :: Integer -> [Integer] tal que divisores n es la lista de los divisores de n. Por ejemplo, divisores 30 == [1,2,3,5,6,10,15,30] length (divisores (product [1..10])) == 270 length (divisores (product [1..25])) == 340032 Soluciones A continuaci\u00f3n se muestran las soluciones en Haskell y las soluciones en Python. Soluciones en Haskell&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"_kad_post_transparent":"","_kad_post_title":"","_kad_post_layout":"","_kad_post_sidebar_id":"","_kad_post_content_style":"","_kad_post_vertical_padding":"","_kad_post_feature":"","_kad_post_feature_position":"","_kad_post_header":false,"_kad_post_footer":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"footnotes":"","_jetpack_memberships_contains_paid_content":false},"categories":[581],"tags":[],"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/posts\/7409"}],"collection":[{"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/comments?post=7409"}],"version-history":[{"count":2,"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/posts\/7409\/revisions"}],"predecessor-version":[{"id":7686,"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/posts\/7409\/revisions\/7686"}],"wp:attachment":[{"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/media?parent=7409"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/categories?post=7409"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.glc.us.es\/~jalonso\/exercitium\/wp-json\/wp\/v2\/tags?post=7409"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}