function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def next_point( point_x: float, point_y: float, incoming_gradient: float ) -> tuple[float, float, float]: # normal_gradient = gradient of line through which the beam is reflected # outgoing_gradient = gradient of reflected line normal_gradient = point_y / 4 / point_x s2 = 2 * normal_gradient / (1 + normal_gradient * normal_gradient) c2 = (1 - normal_gradient * normal_gradient) / ( 1 + normal_gradient * normal_gradient ) outgoing_gradient = (s2 - c2 * incoming_gradient) / (c2 + s2 * incoming_gradient) # to find the next point, solve the simultaeneous equations: # y^2 + 4x^2 = 100 # y - b = m * (x - a) # ==> A x^2 + B x + C = 0 quadratic_term = outgoing_gradient**2 + 4 linear_term = 2 * outgoing_gradient * (point_y - outgoing_gradient * point_x) constant_term = (point_y - outgoing_gradient * point_x) ** 2 - 100 x_minus = ( -linear_term - sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) x_plus = ( -linear_term + sqrt(linear_term**2 - 4 * quadratic_term * constant_term) ) / (2 * quadratic_term) # two solutions, one of which is our input point next_x = x_minus if isclose(x_plus, point_x) else x_plus next_y = point_y + outgoing_gradient * (next_x - point_x) return next_x, next_y, outgoing_gradient
project_euler
def solution(first_x_coord: float = 1.4, first_y_coord: float = -9.6) -> int: num_reflections: int = 0 point_x: float = first_x_coord point_y: float = first_y_coord gradient: float = (10.1 - point_y) / (0.0 - point_x) while not (-0.01 <= point_x <= 0.01 and point_y > 0): point_x, point_y, gradient = next_point(point_x, point_y, gradient) num_reflections += 1 return num_reflections
project_euler
def _modexpt(base: int, exponent: int, modulo_value: int) -> int: if exponent == 1: return base if exponent % 2 == 0: x = _modexpt(base, exponent // 2, modulo_value) % modulo_value return (x * x) % modulo_value else: return (base * _modexpt(base, exponent - 1, modulo_value)) % modulo_value
project_euler
def solution(base: int = 1777, height: int = 1855, digits: int = 8) -> int: # calculate base↑↑height by right-assiciative repeated modular # exponentiation result = base for _ in range(1, height): result = _modexpt(base, result, 10**digits) return result
project_euler
def solution(limit: int = 1000000) -> int: limit = limit + 1 frequency = [0] * limit for first_term in range(1, limit): for n in range(first_term, limit, first_term): common_difference = first_term + n / first_term if common_difference % 4: # d must be divisble by 4 continue else: common_difference /= 4 if ( first_term > common_difference and first_term < 4 * common_difference ): # since x,y,z are positive integers frequency[n] += 1 # so z>0 and a>d ,also 4d<a count = sum(1 for x in frequency[1:limit] if x == 10) return count
project_euler
def next_term(a_i, k, i, n): # ds_b - digitsum(b) ds_b = sum(a_i[j] for j in range(k, len(a_i))) c = sum(a_i[j] * base[j] for j in range(min(len(a_i), k))) diff, dn = 0, 0 max_dn = n - i sub_memo = memo.get(ds_b) if sub_memo is not None: jumps = sub_memo.get(c) if jumps is not None and len(jumps) > 0: # find and make the largest jump without going over max_jump = -1 for _k in range(len(jumps) - 1, -1, -1): if jumps[_k][2] <= k and jumps[_k][1] <= max_dn: max_jump = _k break if max_jump >= 0: diff, dn, _kk = jumps[max_jump] # since the difference between jumps is cached, add c new_c = diff + c for j in range(min(k, len(a_i))): new_c, a_i[j] = divmod(new_c, 10) if new_c > 0: add(a_i, k, new_c) else: sub_memo[c] = [] else: sub_memo = {c: []} memo[ds_b] = sub_memo if dn >= max_dn or c + diff >= base[k]: return diff, dn if k > ks[0]: while True: # keep doing smaller jumps _diff, terms_jumped = next_term(a_i, k - 1, i + dn, n) diff += _diff dn += terms_jumped if dn >= max_dn or c + diff >= base[k]: break else: # would be too small a jump, just compute sequential terms instead _diff, terms_jumped = compute(a_i, k, i + dn, n) diff += _diff dn += terms_jumped jumps = sub_memo[c] # keep jumps sorted by # of terms skipped j = 0 while j < len(jumps): if jumps[j][1] > dn: break j += 1 # cache the jump for this value digitsum(b) and c sub_memo[c].insert(j, (diff, dn, k)) return (diff, dn)
project_euler
def compute(a_i, k, i, n): if i >= n: return 0, i if k > len(a_i): a_i.extend([0 for _ in range(k - len(a_i))]) # note: a_i -> b * 10^k + c # ds_b -> digitsum(b) # ds_c -> digitsum(c) start_i = i ds_b, ds_c, diff = 0, 0, 0 for j in range(len(a_i)): if j >= k: ds_b += a_i[j] else: ds_c += a_i[j] while i < n: i += 1 addend = ds_c + ds_b diff += addend ds_c = 0 for j in range(k): s = a_i[j] + addend addend, a_i[j] = divmod(s, 10) ds_c += a_i[j] if addend > 0: break if addend > 0: add(a_i, k, addend) return diff, i - start_i
project_euler
def add(digits, k, addend): for j in range(k, len(digits)): s = digits[j] + addend if s >= 10: quotient, digits[j] = divmod(s, 10) addend = addend // 10 + quotient else: digits[j] = s addend = addend // 10 if addend == 0: break while addend > 0: addend, digit = divmod(addend, 10) digits.append(digit)
project_euler
def solution(n: int = 10**15) -> int: digits = [1] i = 1 dn = 0 while True: diff, terms_jumped = next_term(digits, 20, i + dn, n) dn += terms_jumped if dn == n - i: break a_n = 0 for j in range(len(digits)): a_n += digits[j] * 10**j return a_n
project_euler
def check(number: int) -> bool: check_last = [0] * 11 check_front = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False if not f: return f # mark first 9 numbers number = int(str(number)[:9]) for _ in range(9): check_front[int(number % 10)] = 1 number = number // 10 # check first 9 numbers for pandigitality for x in range(9): if not check_front[x + 1]: f = False return f
project_euler
def check1(number: int) -> bool: check_last = [0] * 11 # mark last 9 numbers for _ in range(9): check_last[int(number % 10)] = 1 number = number // 10 # flag f = True # check last 9 numbers for pandigitality for x in range(9): if not check_last[x + 1]: f = False return f
project_euler
def solution() -> int: a = 1 b = 1 c = 2 # temporary Fibonacci numbers a1 = 1 b1 = 1 c1 = 2 # temporary Fibonacci numbers mod 1e9 # mod m=1e9, done for fast optimisation tocheck = [0] * 1000000 m = 1000000000 for x in range(1000000): c1 = (a1 + b1) % m a1 = b1 % m b1 = c1 % m if check1(b1): tocheck[x + 3] = 1 for x in range(1000000): c = a + b a = b b = c # perform check only if in tocheck if tocheck[x + 3] and check(b): return x + 3 # first 2 already done return -1
project_euler
def vector_product(point1: tuple[int, int], point2: tuple[int, int]) -> int: return point1[0] * point2[1] - point1[1] * point2[0]
project_euler
def contains_origin(x1: int, y1: int, x2: int, y2: int, x3: int, y3: int) -> bool: point_a: tuple[int, int] = (x1, y1) point_a_to_b: tuple[int, int] = (x2 - x1, y2 - y1) point_a_to_c: tuple[int, int] = (x3 - x1, y3 - y1) a: float = -vector_product(point_a, point_a_to_b) / vector_product( point_a_to_c, point_a_to_b ) b: float = +vector_product(point_a, point_a_to_c) / vector_product( point_a_to_c, point_a_to_b ) return a > 0 and b > 0 and a + b < 1
project_euler
def solution(filename: str = "p102_triangles.txt") -> int: data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") triangles: list[list[int]] = [] for line in data.strip().split("\n"): triangles.append([int(number) for number in line.split(",")]) ret: int = 0 triangle: list[int] for triangle in triangles: ret += contains_origin(*triangle) return ret
project_euler
def solution(exponent: int = 30) -> int: # To find how many total games were lost for a given exponent x, # we need to find the Fibonacci number F(x+2). fibonacci_index = exponent + 2 phi = (1 + 5**0.5) / 2 fibonacci = (phi**fibonacci_index - (phi - 1) ** fibonacci_index) / 5**0.5 return int(fibonacci)
project_euler
def is_prime(number: int) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True
project_euler
def solution(n: int = 7) -> int: pandigital_str = "".join(str(i) for i in range(1, n + 1)) perm_list = [int("".join(i)) for i in permutations(pandigital_str, n)] pandigitals = [num for num in perm_list if is_prime(num)] return max(pandigitals) if pandigitals else 0
project_euler
def is_prime(number: int) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True
project_euler
def compute_nums(n: int) -> list[int]: if not isinstance(n, int): raise ValueError("n must be an integer") if n <= 0: raise ValueError("n must be >= 0") list_nums = [] for num in range(len(odd_composites)): i = 0 while 2 * i * i <= odd_composites[num]: rem = odd_composites[num] - 2 * i * i if is_prime(rem): break i += 1 else: list_nums.append(odd_composites[num]) if len(list_nums) == n: return list_nums return []
project_euler
def get_totients(max_one: int) -> list[int]: totients = [0] * max_one for i in range(0, max_one): totients[i] = i for i in range(2, max_one): if totients[i] == i: for j in range(i, max_one, i): totients[j] -= totients[j] // i return totients
project_euler
def has_same_digits(num1: int, num2: int) -> bool: return sorted(str(num1)) == sorted(str(num2))
project_euler
def solution(max_n: int = 10000000) -> int: min_numerator = 1 # i min_denominator = 0 # φ(i) totients = get_totients(max_n + 1) for i in range(2, max_n + 1): t = totients[i] if i * min_denominator < min_numerator * t and has_same_digits(i, t): min_numerator = i min_denominator = t return min_numerator
project_euler
def solution(): total = 0 for i in range(1, 1001): total += i**i return str(total)[-10:]
project_euler
def partition(number_to_partition: int) -> set[int]: if number_to_partition < 0: return set() elif number_to_partition == 0: return {1} ret: set[int] = set() prime: int sub: int for prime in primes: if prime > number_to_partition: continue for sub in partition(number_to_partition - prime): ret.add(sub * prime) return ret
project_euler
def solution(number_unique_partitions: int = 5000) -> int | None: for number_to_partition in range(1, NUM_PRIMES): if len(partition(number_to_partition)) > number_unique_partitions: return number_to_partition return None
project_euler
def solution(limit=28123): sum_divs = [1] * (limit + 1) for i in range(2, int(limit**0.5) + 1): sum_divs[i * i] += i for k in range(i + 1, limit // i + 1): sum_divs[k * i] += k + i abundants = set() res = 0 for n in range(1, limit + 1): if sum_divs[n] > n: abundants.add(n) if not any((n - a in abundants) for a in abundants): res += n return res
project_euler
def solution(): result = list(map("".join, permutations("0123456789"))) return result[999999]
project_euler
def log_difference(number: int) -> float: log_number = math.log(2, 10) * number difference = round((log_number - int(log_number)), 15) return difference
project_euler
def solution(number: int = 678910) -> int: power_iterator = 90 position = 0 lower_limit = math.log(1.23, 10) upper_limit = math.log(1.24, 10) previous_power = 0 while position < number: difference = log_difference(power_iterator) if difference >= upper_limit: power_iterator += 93 elif difference < lower_limit: power_iterator += 196 else: previous_power = power_iterator power_iterator += 196 position += 1 return previous_power
project_euler
def triangle_number_generator(): for n in range(1, 1000000): yield n * (n + 1) // 2
project_euler
def count_divisors(n): divisors_count = 1 i = 2 while i * i <= n: multiplicity = 0 while n % i == 0: n //= i multiplicity += 1 divisors_count *= multiplicity + 1 i += 1 if n > 1: divisors_count *= 2 return divisors_count
project_euler
def solution(): return next(i for i in triangle_number_generator() if count_divisors(i) > 500)
project_euler
def count_divisors(n): n_divisors = 1 i = 2 while i * i <= n: multiplicity = 0 while n % i == 0: n //= i multiplicity += 1 n_divisors *= multiplicity + 1 i += 1 if n > 1: n_divisors *= 2 return n_divisors
project_euler
def solution(): t_num = 1 i = 1 while True: i += 1 t_num += i if count_divisors(t_num) > 500: break return t_num
project_euler
def solution(n: int = 20) -> int: n = 2 * n # middle entry of odd rows starting at row 3 is the solution for n = 1, # 2, 3,... k = n // 2 return int(factorial(n) / (factorial(k) * factorial(n - k)))
project_euler
def is_prime(number: int) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True
project_euler
def search(target: int, prime_list: list) -> bool: left, right = 0, len(prime_list) - 1 while left <= right: middle = (left + right) // 2 if prime_list[middle] == target: return True elif prime_list[middle] < target: left = middle + 1 else: right = middle - 1 return False
project_euler
def solution(): prime_list = [n for n in range(1001, 10000, 2) if is_prime(n)] candidates = [] for number in prime_list: tmp_numbers = [] for prime_member in permutations(list(str(number))): prime = int("".join(prime_member)) if prime % 2 == 0: continue if search(prime, prime_list): tmp_numbers.append(prime) tmp_numbers.sort() if len(tmp_numbers) >= 3: candidates.append(tmp_numbers) passed = [] for candidate in candidates: length = len(candidate) found = False for i in range(length): for j in range(i + 1, length): for k in range(j + 1, length): if ( abs(candidate[i] - candidate[j]) == abs(candidate[j] - candidate[k]) and len({candidate[i], candidate[j], candidate[k]}) == 3 ): passed.append( sorted([candidate[i], candidate[j], candidate[k]]) ) found = True if found: break if found: break if found: break answer = set() for seq in passed: answer.add("".join([str(i) for i in seq])) return max(int(x) for x in answer)
project_euler
def solution(m: int = 100) -> int: memo = [[0 for _ in range(m)] for _ in range(m + 1)] for i in range(m + 1): memo[i][0] = 1 for n in range(m + 1): for k in range(1, m): memo[n][k] += memo[n][k - 1] if n > k: memo[n][k] += memo[n - k - 1][k] return memo[m][m - 1] - 1
project_euler
def solution(filename: str = "input.txt") -> int: with open(os.path.join(os.path.dirname(__file__), filename)) as input_file: matrix = [ [int(element) for element in line.split(",")] for line in input_file.readlines() ] rows = len(matrix) cols = len(matrix[0]) minimal_path_sums = [[-1 for _ in range(cols)] for _ in range(rows)] for i in range(rows): minimal_path_sums[i][0] = matrix[i][0] for j in range(1, cols): for i in range(rows): minimal_path_sums[i][j] = minimal_path_sums[i][j - 1] + matrix[i][j] for i in range(1, rows): minimal_path_sums[i][j] = min( minimal_path_sums[i][j], minimal_path_sums[i - 1][j] + matrix[i][j] ) for i in range(rows - 2, -1, -1): minimal_path_sums[i][j] = min( minimal_path_sums[i][j], minimal_path_sums[i + 1][j] + matrix[i][j] ) return min(minimal_path_sums_row[-1] for minimal_path_sums_row in minimal_path_sums)
project_euler
def solution(target: int = 2000000) -> int: triangle_numbers: list[int] = [0] idx: int for idx in range(1, ceil(sqrt(target * 2) * 1.1)): triangle_numbers.append(triangle_numbers[-1] + idx) # we want this to be as close as possible to target best_product: int = 0 # the area corresponding to the grid that gives the product closest to target area: int = 0 # an estimate of b, using the quadratic formula b_estimate: float # the largest integer less than b_estimate b_floor: int # the largest integer less than b_estimate b_ceil: int # the triangle number corresponding to b_floor triangle_b_first_guess: int # the triangle number corresponding to b_ceil triangle_b_second_guess: int for idx_a, triangle_a in enumerate(triangle_numbers[1:], 1): b_estimate = (-1 + sqrt(1 + 8 * target / triangle_a)) / 2 b_floor = floor(b_estimate) b_ceil = ceil(b_estimate) triangle_b_first_guess = triangle_numbers[b_floor] triangle_b_second_guess = triangle_numbers[b_ceil] if abs(target - triangle_b_first_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_first_guess * triangle_a area = idx_a * b_floor if abs(target - triangle_b_second_guess * triangle_a) < abs( target - best_product ): best_product = triangle_b_second_guess * triangle_a area = idx_a * b_ceil return area
project_euler
def solution(numerator: int = 3, denominator: int = 7, limit: int = 1000000) -> int: max_numerator = 0 max_denominator = 1 for current_denominator in range(1, limit + 1): current_numerator = current_denominator * numerator // denominator if current_denominator % denominator == 0: current_numerator -= 1 if current_numerator * max_denominator > current_denominator * max_numerator: max_numerator = current_numerator max_denominator = current_denominator return max_numerator
project_euler
def solution(number: int = 1000000) -> int: partitions = [1] for i in itertools.count(len(partitions)): item = 0 for j in itertools.count(1): sign = -1 if j % 2 == 0 else +1 index = (j * j * 3 - j) // 2 if index > i: break item += partitions[i - index] * sign item %= number index += j if index > i: break item += partitions[i - index] * sign item %= number if item == 0: return i partitions.append(item) return 0
project_euler
def unique_prime_factors(n: int) -> set: i = 2 factors = set() while i * i <= n: if n % i: i += 1 else: n //= i factors.add(i) if n > 1: factors.add(n) return factors
project_euler
def upf_len(num: int) -> int: return len(unique_prime_factors(num))
project_euler
def equality(iterable: list) -> bool: return len(set(iterable)) in (0, 1)
project_euler
def run(n: int) -> list: # Incrementor variable for our group list comprehension. # This serves as the first number in each list of values # to test. base = 2 while True: # Increment each value of a generated range group = [base + i for i in range(n)] # Run elements through out unique_prime_factors function # Append our target number to the end. checker = [upf_len(x) for x in group] checker.append(n) # If all numbers in the list are equal, return the group variable. if equality(checker): return group # Increment our base variable by 1 base += 1
project_euler
def solution(n: int = 4) -> int: results = run(n) return results[0] if len(results) else None
project_euler
def solution(): constant = [] i = 1 while len(constant) < 1e6: constant.append(str(i)) i += 1 constant = "".join(constant) return ( int(constant[0]) * int(constant[9]) * int(constant[99]) * int(constant[999]) * int(constant[9999]) * int(constant[99999]) * int(constant[999999]) )
project_euler
def solution(n: int = 1000000) -> int: largest_number = 1 pre_counter = 1 counters = {1: 1} for input1 in range(2, n): counter = 0 number = input1 while True: if number in counters: counter += counters[number] break if number % 2 == 0: number //= 2 counter += 1 else: number = (3 * number) + 1 counter += 1 if input1 not in counters: counters[input1] = counter if counter > pre_counter: largest_number = input1 pre_counter = counter return largest_number
project_euler
def solution(): file_path = os.path.join(os.path.dirname(__file__), "num.txt") with open(file_path) as file_hand: return str(sum(int(line) for line in file_hand))[:10]
project_euler
def solution(n: int = 1000) -> int: f1, f2 = 1, 1 index = 2 while True: i = 0 f = f1 + f2 f1, f2 = f2, f index += 1 for _ in str(f): i += 1 if i == n: break return index
project_euler
def fibonacci_generator() -> Generator[int, None, None]: a, b = 0, 1 while True: a, b = b, a + b yield b
project_euler
def solution(n: int = 1000) -> int: answer = 1 gen = fibonacci_generator() while len(str(next(gen))) < n: answer += 1 return answer + 1
project_euler
def fibonacci(n: int) -> int: if n == 1 or not isinstance(n, int): return 0 elif n == 2: return 1 else: sequence = [0, 1] for i in range(2, n + 1): sequence.append(sequence[i - 1] + sequence[i - 2]) return sequence[n]
project_euler
def fibonacci_digits_index(n: int) -> int: digits = 0 index = 2 while digits < n: index += 1 digits = len(str(fibonacci(index))) return index
project_euler
def solution(n: int = 1000) -> int: return fibonacci_digits_index(n)
project_euler
def solution(): total_sum = 0 temp_sum = 0 with open(os.path.dirname(__file__) + "/p022_names.txt") as file: name = str(file.readlines()[0]) name = name.replace('"', "").split(",") name.sort() for i in range(len(name)): for j in name[i]: temp_sum += ord(j) - ord("A") + 1 total_sum += (i + 1) * temp_sum temp_sum = 0 return total_sum
project_euler
def solution(): with open(os.path.dirname(__file__) + "/p022_names.txt") as file: names = str(file.readlines()[0]) names = names.replace('"', "").split(",") names.sort() name_score = 0 total_score = 0 for i, name in enumerate(names): for letter in name: name_score += ord(letter) - 64 total_score += (i + 1) * name_score name_score = 0 return total_score
project_euler
def next_number(number: int) -> int: sum_of_digits_squared = 0 while number: # Increased Speed Slightly by checking every 5 digits together. sum_of_digits_squared += DIGITS_SQUARED[number % 100000] number //= 100000 return sum_of_digits_squared
project_euler
def chain(number: int) -> bool: if CHAINS[number - 1] is not None: return CHAINS[number - 1] # type: ignore number_chain = chain(next_number(number)) CHAINS[number - 1] = number_chain while number < 10000000: CHAINS[number - 1] = number_chain number *= 10 return number_chain
project_euler
def solution(number: int = 10000000) -> int: for i in range(1, number): if CHAINS[i] is None: chain(i + 1) return CHAINS[:number].count(False)
project_euler
def try_key(ciphertext: list[int], key: tuple[int, ...]) -> str | None: decoded: str = "" keychar: int cipherchar: int decodedchar: int for keychar, cipherchar in zip(cycle(key), ciphertext): decodedchar = cipherchar ^ keychar if decodedchar not in VALID_INTS: return None decoded += chr(decodedchar) return decoded
project_euler
def filter_valid_chars(ciphertext: list[int]) -> list[str]: possibles: list[str] = [] for key in product(LOWERCASE_INTS, repeat=3): encoded = try_key(ciphertext, key) if encoded is not None: possibles.append(encoded) return possibles
project_euler
def filter_common_word(possibles: list[str], common_word: str) -> list[str]: return [possible for possible in possibles if common_word in possible.lower()]
project_euler
def solution(filename: str = "p059_cipher.txt") -> int: ciphertext: list[int] possibles: list[str] common_word: str decoded_text: str data: str = Path(__file__).parent.joinpath(filename).read_text(encoding="utf-8") ciphertext = [int(number) for number in data.strip().split(",")] possibles = filter_valid_chars(ciphertext) for common_word in COMMON_WORDS: possibles = filter_common_word(possibles, common_word) if len(possibles) == 1: break decoded_text = possibles[0] return sum(ord(char) for char in decoded_text)
project_euler
def solution(n: int = 1000) -> int: prev_numerator, prev_denominator = 1, 1 result = [] for i in range(1, n + 1): numerator = prev_numerator + 2 * prev_denominator denominator = prev_numerator + prev_denominator if len(str(numerator)) > len(str(denominator)): result.append(i) prev_numerator = numerator prev_denominator = denominator return len(result)
project_euler
def solution(gon_side: int = 5) -> int: if gon_side < 3 or gon_side > 5: raise ValueError("gon_side must be in the range [3, 5]") # Since it's 16, we know 10 is on the outer ring # Put the big numbers at the end so that they are never the first number small_numbers = list(range(gon_side + 1, 0, -1)) big_numbers = list(range(gon_side + 2, gon_side * 2 + 1)) for perm in permutations(small_numbers + big_numbers): numbers = generate_gon_ring(gon_side, list(perm)) if is_magic_gon(numbers): return int("".join(str(n) for n in numbers)) raise ValueError(f"Magic {gon_side}-gon ring is impossible")
project_euler
def generate_gon_ring(gon_side: int, perm: list[int]) -> list[int]: result = [0] * (gon_side * 3) result[0:3] = perm[0:3] perm.append(perm[1]) magic_number = 1 if gon_side < 5 else 2 for i in range(1, len(perm) // 3 + magic_number): result[3 * i] = perm[2 * i + 1] result[3 * i + 1] = result[3 * i - 1] result[3 * i + 2] = perm[2 * i + 2] return result
project_euler
def is_magic_gon(numbers: list[int]) -> bool: if len(numbers) % 3 != 0: raise ValueError("a gon ring should have a length that is a multiple of 3") if min(numbers[::3]) != numbers[0]: return False total = sum(numbers[:3]) return all(sum(numbers[i : i + 3]) == total for i in range(3, len(numbers), 3))
project_euler
def prime_sieve(limit: int) -> list[int]: is_prime = [True] * limit is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(limit**0.5 + 1), 2): index = i * 2 while index < limit: is_prime[index] = False index = index + i primes = [2] for i in range(3, limit, 2): if is_prime[i]: primes.append(i) return primes
project_euler
def solution(ceiling: int = 1_000_000) -> int: primes = prime_sieve(ceiling) length = 0 largest = 0 for i in range(len(primes)): for j in range(i + length, len(primes)): sol = sum(primes[i:j]) if sol >= ceiling: break if sol in primes: length = j - i largest = sol return largest
project_euler
def solution(n: int = 998001) -> int: answer = 0 for i in range(999, 99, -1): # 3 digit numbers range from 999 down to 100 for j in range(999, 99, -1): product_string = str(i * j) if product_string == product_string[::-1] and i * j < n: answer = max(answer, i * j) return answer
project_euler
def solution(n: int = 998001) -> int: # fetches the next number for number in range(n - 1, 9999, -1): str_number = str(number) # checks whether 'str_number' is a palindrome. if str_number == str_number[::-1]: divisor = 999 # if 'number' is a product of two 3-digit numbers # then number is the answer otherwise fetch next number. while divisor != 99: if (number % divisor == 0) and (len(str(number // divisor)) == 3.0): return number divisor -= 1 raise ValueError("That number is larger than our acceptable range.")
project_euler
def solution(n: int = 600851475143) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") i = 2 ans = 0 if n == 2: return 2 while n > 2: while n % i != 0: i += 1 ans = i while n % i == 0: n = n // i i += 1 return int(ans)
project_euler
def solution(n: int = 600851475143) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") prime = 1 i = 2 while i * i <= n: while n % i == 0: prime = i n //= i i += 1 if n > 1: prime = n return int(prime)
project_euler
def is_prime(number: int) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True
project_euler
def solution(n: int = 600851475143) -> int: try: n = int(n) except (TypeError, ValueError): raise TypeError("Parameter n must be int or castable to int.") if n <= 0: raise ValueError("Parameter n must be greater than or equal to one.") max_number = 0 if is_prime(n): return n while n % 2 == 0: n //= 2 if is_prime(n): return n for i in range(3, int(math.sqrt(n)) + 1, 2): if n % i == 0: if is_prime(n // i): max_number = n // i break elif is_prime(i): max_number = i return max_number
project_euler
def solution(num_picks: int = 20) -> str: total = math.comb(NUM_BALLS, num_picks) missing_colour = math.comb(NUM_BALLS - BALLS_PER_COLOUR, num_picks) result = NUM_COLOURS * (1 - missing_colour / total) return f"{result:.9f}"
project_euler
def is_prime(n: int) -> bool: return seive[n]
project_euler
def contains_an_even_digit(n: int) -> bool: return any(digit in "02468" for digit in str(n))
project_euler
def find_circular_primes(limit: int = 1000000) -> list[int]: result = [2] # result already includes the number 2. for num in range(3, limit + 1, 2): if is_prime(num) and not contains_an_even_digit(num): str_num = str(num) list_nums = [int(str_num[j:] + str_num[:j]) for j in range(len(str_num))] if all(is_prime(i) for i in list_nums): result.append(num) return result
project_euler
def solution() -> int: return len(find_circular_primes())
project_euler
def check_partition_perfect(positive_integer: int) -> bool: exponent = math.log2(math.sqrt(4 * positive_integer + 1) / 2 + 1 / 2) return exponent == int(exponent)
project_euler
def solution(max_proportion: float = 1 / 12345) -> int: total_partitions = 0 perfect_partitions = 0 integer = 3 while True: partition_candidate = (integer**2 - 1) / 4 # if candidate is an integer, then there is a partition for k if partition_candidate == int(partition_candidate): partition_candidate = int(partition_candidate) total_partitions += 1 if check_partition_perfect(partition_candidate): perfect_partitions += 1 if perfect_partitions > 0: if perfect_partitions / total_partitions < max_proportion: return int(partition_candidate) integer += 1
project_euler
def is_combination_valid(combination): return ( int("".join(combination[0:2])) * int("".join(combination[2:5])) == int("".join(combination[5:9])) ) or ( int("".join(combination[0])) * int("".join(combination[1:5])) == int("".join(combination[5:9])) )
project_euler
def solution(): return sum( { int("".join(pandigital[5:9])) for pandigital in itertools.permutations("123456789") if is_combination_valid(pandigital) } )
project_euler
def prime_sieve(n: int) -> list[int]: is_prime = [True] * n is_prime[0] = False is_prime[1] = False is_prime[2] = True for i in range(3, int(n**0.5 + 1), 2): index = i * 2 while index < n: is_prime[index] = False index = index + i primes = [2] for i in range(3, n, 2): if is_prime[i]: primes.append(i) return primes
project_euler
def digit_replacements(number: int) -> list[list[int]]: number_str = str(number) replacements = [] digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] for duplicate in Counter(number_str) - Counter(set(number_str)): family = [int(number_str.replace(duplicate, digit)) for digit in digits] replacements.append(family) return replacements
project_euler
def solution(family_length: int = 8) -> int: numbers_checked = set() # Filter primes with less than 3 replaceable digits primes = { x for x in set(prime_sieve(1_000_000)) if len(str(x)) - len(set(str(x))) >= 3 } for prime in primes: if prime in numbers_checked: continue replacements = digit_replacements(prime) for family in replacements: numbers_checked.update(family) primes_in_family = primes.intersection(family) if len(primes_in_family) != family_length: continue return min(primes_in_family) return -1
project_euler
def solution(a: int = 100, b: int = 100) -> int: # RETURN the MAXIMUM from the list of SUMs of the list of INT converted from STR of # BASE raised to the POWER return max( sum(int(x) for x in str(base**power)) for base in range(a) for power in range(b) )
project_euler
def solution(n: int = 10**6) -> int: if n <= 0: raise ValueError("Please enter an integer greater than 0") phi = list(range(n + 1)) for number in range(2, n + 1): if phi[number] == number: phi[number] -= 1 for multiple in range(number * 2, n + 1, number): phi[multiple] = (phi[multiple] // number) * (number - 1) answer = 1 for number in range(1, n + 1): if (answer / phi[answer]) < (number / phi[number]): answer = number return answer
project_euler
def solution() -> int: script_dir = os.path.dirname(os.path.realpath(__file__)) triangle_path = os.path.join(script_dir, "triangle.txt") with open(triangle_path) as in_file: triangle = [[int(i) for i in line.split()] for line in in_file] while len(triangle) != 1: last_row = triangle.pop() curr_row = triangle[-1] for j in range(len(last_row) - 1): curr_row[j] += max(last_row[j], last_row[j + 1]) return triangle[0][0]
project_euler
def solution(): script_dir = os.path.dirname(os.path.realpath(__file__)) triangle = os.path.join(script_dir, "triangle.txt") with open(triangle) as f: triangle = f.readlines() a = [] for line in triangle: numbers_from_line = [] for number in line.strip().split(" "): numbers_from_line.append(int(number)) a.append(numbers_from_line) for i in range(1, len(a)): for j in range(len(a[i])): number1 = a[i - 1][j] if j != len(a[i - 1]) else 0 number2 = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(number1, number2) return max(a[-1])
project_euler
def is_prime(number: int) -> bool: if 1 < number < 4: # 2 and 3 are primes return True elif number < 2 or number % 2 == 0 or number % 3 == 0: # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes return False # All primes number are in format of 6k +/- 1 for i in range(5, int(math.sqrt(number) + 1), 6): if number % i == 0 or number % (i + 2) == 0: return False return True
project_euler
def solution(ratio: float = 0.1) -> int: j = 3 primes = 3 while primes / (2 * j - 1) >= ratio: for i in range(j * j + j + 1, (j + 2) * (j + 2), j + 1): primes += is_prime(i) j += 2 return j
project_euler
def is_digit_cancelling(num: int, den: int) -> bool: return ( num != den and num % 10 == den // 10 and (num // 10) / (den % 10) == num / den )
project_euler
def fraction_list(digit_len: int) -> list[str]: solutions = [] den = 11 last_digit = int("1" + "0" * digit_len) for num in range(den, last_digit): while den <= 99: if (num != den) and (num % 10 == den // 10) and (den % 10 != 0): if is_digit_cancelling(num, den): solutions.append(f"{num}/{den}") den += 1 num += 1 den = 10 return solutions
project_euler
def solution(n: int = 2) -> int: result = 1.0 for fraction in fraction_list(n): frac = Fraction(fraction) result *= frac.denominator / frac.numerator return int(result)
project_euler