# Given these facts, we know that if n_k is the product of the k smallest # primes, then for all n < n_k, n/φ(n) < n_k/φ(n_k). # # Finally, then, the solution is simply the largest product of consecutive # primes starting from 2 that fits within the given maximum. def prime_product(): product = 1 for prime in primes: product *= prime yield product prime_products = MonatonicIncreasingSequence(prime_product()) # Based in part on the tail recipe in the Python itertools documentation. def last(iterable): '''Return the final element of an iterator''' return deque(iterable, maxlen=1)[0] if __name__ == '__main__': try: maximum = int(argv[1]) except IndexError: maximum = 1000000 print(last(prime_products.range(maximum)))
#!/usr/bin/env python3 ''' Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' from itertools import takewhile, count from sequence import MonatonicIncreasingSequence multiples = MonatonicIncreasingSequence(n for n in count() if n % 3 == 0 or n % 5 == 0) if __name__ == '__main__': print(sum(multiples.range(999)))
Triangle, pentagonal, and hexagonal numbers are generated by the following formulae: Triangle T(n) = n(n+1)/2 1, 3, 6, 10, 15, ... Pentagonal P(n) = n(3n−1)/2 1, 5, 12, 22, 35, ... Hexagonal H(n) = n(2n−1) 1, 6, 15, 28, 45, ... It can be verified that T(285) = P(165) = H(143) = 40755. Find the next triangle number that is also pentagonal and hexagonal. ''' from itertools import count from sequence import MonatonicIncreasingSequence triangles = MonatonicIncreasingSequence(n * (n + 1) // 2 for n in count(1)) pentagons = MonatonicIncreasingSequence(n * (3 * n - 1) // 2 for n in count(1)) hexagons = MonatonicIncreasingSequence(n * (2 * n - 1) for n in count(1)) if __name__ == '__main__': # Want the first number over 40755 that is in triangles, pentagons and # hexagons. It makes little difference which we iterate over, since we'll # need to generate numbers in each sequence up to the number under test in # any case, so let's just go with the wording in the question. for number in triangles.range(40756, None): if number in pentagons and number in hexagons: print(number) break
#!/usr/bin/env python3 ''' Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. ''' from itertools import count from sequence import MonatonicIncreasingSequence multiples = MonatonicIncreasingSequence(n for n in count() if n % 3 == 0 or n % 5 == 0) if __name__ == '__main__': print(sum(multiples.range(999)))