Skip to content

Commit

Permalink
Add kattis prob goldbach2 in python3 + notes
Browse files Browse the repository at this point in the history
  • Loading branch information
iandioch committed Apr 16, 2018
1 parent a832a4b commit 2281d53
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
7 changes: 7 additions & 0 deletions kattis/goldbach2/notes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Use the sieve of Eratosthenes to get all of the primes. Then initialise one pointer to the first prime, and the second pointer to the highest prime below the target number. Then iterate, with the following logic:

- If the sum of these primes is too large, decrement the pointer to the higher prime.
- If the sum of these primes is too small, incremenet the pointer to the lower prime.
- If the sum is equal, add these primes to the answer set, and incrememnt the lower pointer.

This runs in 0.1s in python3.
30 changes: 30 additions & 0 deletions kattis/goldbach2/solution.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
def main():
is_prime = [True for _ in range(32005)]
primes = []
for i in range(2, 32005):
if is_prime[i]:
primes.append(i)
for j in range(i+i, 32005, i):
is_prime[j] = False
n = int(input())
for _ in range(n):
m = int(input())
ans = []
i, j = 0, 0
while j < len(primes) and primes[j] < m:
j += 1
while i <= j:
if primes[i] + primes[j] == m:
ans.append((primes[i], primes[j]))
i += 1
elif primes[i] + primes[j] > m:
j -= 1
else:
i += 1
print('{} has {} representation(s)'.format(m, len(ans)))
for a, b in ans:
print('{}+{}'.format(a,b))
print()

if __name__ == '__main__':
main()

0 comments on commit 2281d53

Please sign in to comment.