Fermat


SUBMITTED BY: Guest

DATE: May 19, 2013, 4:04 a.m.

FORMAT: Python

SIZE: 3.1 kB

HITS: 2038

  1. from math import sqrt
  2. from random import randint
  3. # returns the greatest divisor and
  4. # how many times it goes into num as a list
  5. def gd(num):
  6. if is_prime(num):
  7. return [1, num]
  8. else:
  9. i = round(num / 2) + 1
  10. while i >= 2:
  11. for n in range(2, i + 1):
  12. if i * n == num:
  13. return [i, n]
  14. i -= 1
  15. def list_check(f, nums):
  16. for i in nums:
  17. if not f(i):
  18. return False
  19. return True
  20. # fermat's primality test, runs ten times
  21. def is_prime(x):
  22. test_num = 0
  23. for i in range(0, 11):
  24. test_num = randint(1, x)
  25. if (test_num ** x % x) == (test_num % x):
  26. continue
  27. else:
  28. return False
  29. return True
  30. def simplify(problem):
  31. nums = {}
  32. for i in problem:
  33. nums[i] = 0
  34. for i in problem:
  35. if i != 1:
  36. nums[i] += 1
  37. return nums
  38. def divisor_count(num):
  39. nums = {}
  40. problem = []
  41. current_divisors = []
  42. current_divisors = gd(num)
  43. for i in current_divisors:
  44. problem.append(i)
  45. while(list_check(is_prime, problem) == False):
  46. for i in range(0, len(problem)):
  47. if not is_prime(problem[i]):
  48. current_divisors = gd(problem[i])
  49. problem[i] = current_divisors[0]
  50. problem.append(current_divisors[1])
  51. nums = simplify(problem)
  52. divisors = 1
  53. for k, v in nums.items():
  54. divisors *= v + 1
  55. return divisors
  56. def sum(lower, next, f, upper, total):
  57. if lower > upper:
  58. return total
  59. else:
  60. sum(next(lower), next, f, upper, total + f(lower))
  61. def pe_12(num, divisors):
  62. i = 0
  63. while(divisors < 500):
  64. if i % 10 == 0:
  65. print(divisors)
  66. i += 1
  67. num += 1
  68. divisors = divisor_count(triangle_num(num))
  69. print(num)
  70. def triangle_num(x):
  71. sum = 0
  72. while x > 0:
  73. sum += x
  74. x -= 1
  75. return sum

comments powered by Disqus