Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: 25% faster Project Euler 73 #10503 #11553

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 49 additions & 3 deletions project_euler/problem_073/sol1.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,29 @@
from math import gcd


def slow_solution(max_d: int = 12_000) -> int:
"""
Returns number of fractions lie between 1/3 and 1/2 in the sorted set
of reduced proper fractions for d ≤ max_d

>>> slow_solution(4)
0

>>> slow_solution(5)
1

>>> slow_solution(8)
3
"""

fractions_number = 0
for d in range(max_d + 1):
for n in range(d // 3 + 1, (d + 1) // 2):
if gcd(n, d) == 1:
fractions_number += 1
return fractions_number


def solution(max_d: int = 12_000) -> int:
"""
Returns number of fractions lie between 1/3 and 1/2 in the sorted set
Expand All @@ -36,11 +59,34 @@ def solution(max_d: int = 12_000) -> int:

fractions_number = 0
for d in range(max_d + 1):
for n in range(d // 3 + 1, (d + 1) // 2):
if gcd(n, d) == 1:
fractions_number += 1
if d % 2 == 0:
n_start = d // 3 + 2 if (d // 3 + 1) % 2 == 0 else d // 3 + 1
for n in range(n_start, (d + 1) // 2, 2):
if gcd(n, d) == 1:
fractions_number += 1
else:
for n in range(d // 3 + 1, (d + 1) // 2):
if gcd(n, d) == 1:
fractions_number += 1
return fractions_number


def benchmark() -> None:
"""
Benchmarks
"""
# Running performance benchmarks...
# slow_solution : 21.02750190000006
# solution : 15.79036830000041

from timeit import timeit

print("Running performance benchmarks...")

print(f"slow_solution : {timeit('slow_solution()', globals=globals(), number=10)}")
print(f"solution : {timeit('solution()', globals=globals(), number=10)}")


if __name__ == "__main__":
print(f"{solution() = }")
benchmark()