Advertisement
acclivity

pyPerfectNumbers

Sep 27th, 2022
1,073
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | Software | 0 0
  1. # Find perfect Numbers based on the Euclid-Euler Theorem
  2. # Mike Kerry - Sept 2022
  3. #
  4. # Consider the sequence 1, 2, 4, 8, 16 ....
  5. # If the sum of this sequence is prime, then
  6. # the product of the sum and the last in the sequence is perfect
  7.  
  8.  
  9. def is_prime(num):
  10.     if num < 4:
  11.         return num > 1  # 2 and 3 => True, anything less than 2 is False
  12.     if not num % 2:
  13.         return False    # All even numbers above 2, are non-prime
  14.     for d in range(3, 1 + int(num ** 0.5), 2):
  15.         if not num % d:
  16.             return False
  17.     return True
  18.  
  19.  
  20. ctr, tot = 0, 1
  21. n = 1
  22. while ctr < 8:
  23.     n += n               # double-up n each iteration
  24.     tot += n             # sum of the sequence 1, 2, 4, 8, ...
  25.     if is_prime(tot):    # if this sum is prime ...
  26.         print(n * tot)   # ... then (sum * last) is 'perfect'
  27.         ctr += 1
  28.  
  29. # Output
  30. # 6
  31. # 28
  32. # 496
  33. # 8128
  34. # 33550336
  35. # 8589869056
  36. # 137438691328
  37. # 2305843008139952128
  38.  
  39.  
  40.  
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement