Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # n => isprime => bool ( true se è primo, false altrimenti )
- def isPrime(n):
- numberOfDividents = 0
- import math
- if(n == 2):
- return True
- if(n % 2 == 0):
- return False
- square = int(math.sqrt(n)) + 1
- for div in range(2, square):
- if(n % div == 0):
- return False
- return True
- # list every prime from 'from' to 'to'
- # ex, getPrimes (1, 9) => [1,2,3,5,7]
- def getPrimes(begin, end):
- foundPrimes = []
- for k in range(begin, end + 1):
- if(isPrime(k)):
- foundPrimes.append(k)
- return foundPrimes
- def binary_search(arr, low, high, x):
- # Check base case
- if high >= low:
- mid = (high + low) // 2
- # If element is present at the middle itself
- if arr[mid] == x:
- return mid
- # If element is smaller than mid, then it can only
- # be present in left subarray
- elif arr[mid] > x:
- return binary_search(arr, low, mid - 1, x)
- # Else the element can only be present in right subarray
- else:
- return binary_search(arr, mid + 1, high, x)
- else:
- # Element is not present in the array
- return -1
- def sortByFirstElement(element):
- return int(element.split('+')[0])
- def goldbach_partitions(n):
- primes_to_try = getPrimes(2, n - 1)
- if(n % 2 != 0):
- return []
- adding_to_n = []
- for i in primes_to_try:
- if(binary_search(primes_to_try, 0, len(primes_to_try) - 1, n - i) != -1):
- if not ((str(i) + '+' + str(n - i) in adding_to_n) or (str(n - i) + '+' + str(i) in adding_to_n)):
- adding_to_n.append(
- str(i) + '+' + str(n - i)
- )
- return sorted(adding_to_n, key=sortByFirstElement)
- print(goldbach_partitions(26))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement