Computes the solution to the problem up to the specified limit >>> solution(1000) 34825 >>> solution(10_000) 1134942 >>> solution(100_000) 36393008
(limit: int = 999_966_663_333)
| 51 | |
| 52 | |
| 53 | def solution(limit: int = 999_966_663_333) -> int: |
| 54 | """ |
| 55 | Computes the solution to the problem up to the specified limit |
| 56 | >>> solution(1000) |
| 57 | 34825 |
| 58 | |
| 59 | >>> solution(10_000) |
| 60 | 1134942 |
| 61 | |
| 62 | >>> solution(100_000) |
| 63 | 36393008 |
| 64 | """ |
| 65 | primes_upper_bound = math.floor(math.sqrt(limit)) + 100 |
| 66 | primes = prime_sieve(primes_upper_bound) |
| 67 | |
| 68 | matches_sum = 0 |
| 69 | prime_index = 0 |
| 70 | last_prime = primes[prime_index] |
| 71 | |
| 72 | while (last_prime**2) <= limit: |
| 73 | next_prime = primes[prime_index + 1] |
| 74 | |
| 75 | lower_bound = last_prime**2 |
| 76 | upper_bound = next_prime**2 |
| 77 | |
| 78 | # Get numbers divisible by lps(current) |
| 79 | current = lower_bound + last_prime |
| 80 | while upper_bound > current <= limit: |
| 81 | matches_sum += current |
| 82 | current += last_prime |
| 83 | |
| 84 | # Reset the upper_bound |
| 85 | while (upper_bound - next_prime) > limit: |
| 86 | upper_bound -= next_prime |
| 87 | |
| 88 | # Add the numbers divisible by ups(current) |
| 89 | current = upper_bound - next_prime |
| 90 | while current > lower_bound: |
| 91 | matches_sum += current |
| 92 | current -= next_prime |
| 93 | |
| 94 | # Remove the numbers divisible by both ups and lps |
| 95 | current = 0 |
| 96 | while upper_bound > current <= limit: |
| 97 | if current <= lower_bound: |
| 98 | # Increment the current number |
| 99 | current += last_prime * next_prime |
| 100 | continue |
| 101 | |
| 102 | if current > limit: |
| 103 | break |
| 104 | |
| 105 | # Remove twice since it was added by both ups and lps |
| 106 | matches_sum -= current * 2 |
| 107 | |
| 108 | # Increment the current number |
| 109 | current += last_prime * next_prime |
| 110 |
no test coverage detected