Advertisement
jtentor

Divisores Primos 3.0

Oct 24th, 2015
280
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.31 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. __author__ = 'Julio Tentor jtentor@gmail.com, Brian Mayo brianmay.dev@gmail.com'
  4.  
  5.  
  6. from math import sqrt
  7. from functools import reduce
  8. from time import clock
  9.  
  10.  
  11. def timeformat(ticks):
  12.     hours, rem = divmod(ticks, 3600)
  13.     minutes, seconds = divmod(rem, 60)
  14.     return "{:0>2}:{:0>2}:{:09.6f}".format(int(hours), int(minutes), seconds)
  15.  
  16.  
  17. def isprime(number):
  18.     if number < 1:
  19.         raise ValueError("Error de argumento en isprime")
  20.     if number == 1 or number == 2:
  21.         return True
  22.     if number % 2 == 0:
  23.         return False
  24.     for divider in range(3, int(sqrt(number)) + 1, 2):
  25.         if number % divider == 0:
  26.             return False
  27.     return True
  28.  
  29.  
  30. def show(number, dividers):
  31.     print("Divisores", dividers)
  32.     for divider in dividers:
  33.         print("%5d" % divider, "+", "%5d" % number, "/", "%5d" % divider, "=", "%5d" % (divider + number / divider))
  34.  
  35.  
  36. def checkprimes(number, dividers):
  37.     for divider in dividers:
  38.         if not isprime(divider + number / divider):
  39.             return False
  40.     return True
  41.  
  42.  
  43. def testproceduralprogramming(limit):
  44.     starttime = clock()
  45.     for number in range(limit, 1, -1):
  46.         dividers = [1]
  47.         for divider in range(2, number):
  48.             if number % divider == 0:
  49.                 dividers.append(divider)
  50.         dividers.append(number)
  51.         if checkprimes(number, dividers):
  52.             print("El numero que buscamos es", number)
  53.             #show(number, dividers)
  54.             break
  55.     stoptime = clock()
  56.     print("Tiempo de ejecución versión Procedural", timeformat(stoptime - starttime))
  57.  
  58.  
  59. def testfunctionalprogramming(limit):
  60.     starttime = clock()
  61.     for number in range(limit, 1, -1):
  62.         dividers = [1] + [divider for divider in range(2, number) if number % divider == 0] + [number]
  63.         if reduce(lambda a, b: a and b, map(lambda divider: isprime(divider + number / divider), dividers)):
  64.             print("El numero que buscamos es", number)
  65.             #show(number, dividers)
  66.             break
  67.     stoptime = clock()
  68.     print("Tiempo de ejecución versión Funcional ", timeformat(stoptime - starttime))
  69.  
  70.  
  71. def test(limit):
  72.     testproceduralprogramming(limit)
  73.     testfunctionalprogramming(limit)
  74.  
  75.  
  76. if __name__ == '__main__': test(10000)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement