Exemplo n.º 1
0
def compute():
    LIMIT = 150000000

    INCREMENTS = [1, 3, 7, 9, 13, 27]  # Must be in non-decreasing order
    NON_INCREMENTS = set(range(INCREMENTS[-1])) - set(INCREMENTS)

    maxnumber = LIMIT**2 + INCREMENTS[-1]
    primes = eulerlib.list_primes(eulerlib.sqrt(maxnumber))

    def has_consecutive_primes(n):
        # Generate the set of numbers to test for primality
        n2 = n**2
        temp = [(n2 + k) for k in INCREMENTS]

        # Test that each number is prime.
        # Note: The nesting of the loops can be reversed, but this way is much faster.
        if any((x != p and x % p == 0) for p in primes for x in temp):
            return False

        # Test that each number that is not an increment is composite.
        # This checks that the prime numbers we found are in fact consecutive.
        return all((not is_prime(n2 + k)) for k in NON_INCREMENTS)

    def is_prime(n):
        end = eulerlib.sqrt(n)
        for p in primes:
            if p > end:
                break
            if n % p == 0:
                return False
        return True

    ans = sum(n for n in range(0, LIMIT, 10) if has_consecutive_primes(n))
    return str(ans)
Exemplo n.º 2
0
def p010():

    max_num = 1999999

    res = sum(eulerlib.list_primes(max_num))

    return res
Exemplo n.º 3
0
def compute():
	BASE = 10**14
	SEARCH_RANGE = 10000000  # Number of candidates starting from BASE to search for primes. Hopefully there are 100 000 primes among here.
	MODULUS = 1234567891011
	
	
	# iscomposite[i] pertains to the number BASE + i
	# Sieve of Eratosthenes, but starting at BASE
	iscomposite = [False] * SEARCH_RANGE
	primes = eulerlib.list_primes(eulerlib.sqrt(BASE + SEARCH_RANGE))
	for p in primes:
		for i in range((BASE + p - 1) // p * p - BASE, len(iscomposite), p):
			iscomposite[i] = True
	
	# Returns p - BASE, where p is the next prime after n + BASE
	def next_prime(n):
		while True:
			n += 1
			if n >= len(iscomposite):
				raise AssertionError("Search range exhausted")
			if not iscomposite[n]:
				return n
	
	
	ans = 0
	p = 0
	for i in range(100000):
		p = next_prime(p)
		ans = (ans + fibonacci_mod(BASE + p, MODULUS)) % MODULUS
	return str(ans)
Exemplo n.º 4
0
def compute():
    BASE = 10**14
    SEARCH_RANGE = 10000000  # Number of candidates starting from BASE to search for primes. Hopefully there are 100 000 primes among here.
    MODULUS = 1234567891011

    # iscomposite[i] pertains to the number BASE + i
    # Sieve of Eratosthenes, but starting at BASE
    iscomposite = [False] * SEARCH_RANGE
    primes = eulerlib.list_primes(eulerlib.sqrt(BASE + SEARCH_RANGE))
    for p in primes:
        for i in range((BASE + p - 1) // p * p - BASE, len(iscomposite), p):
            iscomposite[i] = True

    # Returns p - BASE, where p is the next prime after n + BASE
    def next_prime(n):
        while True:
            n += 1
            if n >= len(iscomposite):
                raise AssertionError("Search range exhausted")
            if not iscomposite[n]:
                return n

    ans = 0
    p = 0
    for i in range(100000):
        p = next_prime(p)
        ans = (ans + fibonacci_mod(BASE + p, MODULUS)) % MODULUS
    return str(ans)
Exemplo n.º 5
0
def compute():
    LIMIT = 10000000

    possible = set()
    primes = eulerlib.list_primes(LIMIT // 2)
    end = eulerlib.sqrt(LIMIT)
    for i in range(len(primes)):
        p = primes[i]
        if p > end:
            break
        for j in range(i + 1, len(primes)):
            q = primes[j]
            lcm = p * q
            if lcm > LIMIT:
                break
            multlimit = LIMIT // lcm

            multiplier = 1
            while multiplier * p <= multlimit:
                multiplier *= p
            maxmult = multiplier
            while multiplier % p == 0:
                multiplier //= p
                while multiplier * q <= multlimit:
                    multiplier *= q
                maxmult = max(multiplier, maxmult)
            possible.add(maxmult * lcm)

    ans = sum(possible)
    return str(ans)
Exemplo n.º 6
0
def compute():
	LIMIT = 10000000
	
	possible = set()
	primes = eulerlib.list_primes(LIMIT // 2)
	end = eulerlib.sqrt(LIMIT)
	for i in range(len(primes)):
		p = primes[i]
		if p > end:
			break
		for j in range(i + 1, len(primes)):
			q = primes[j]
			lcm = p * q
			if lcm > LIMIT:
				break
			multlimit = LIMIT // lcm
			
			multiplier = 1
			while multiplier * p <= multlimit:
				multiplier *= p
			maxmult = multiplier
			while multiplier % p == 0:
				multiplier //= p
				while multiplier * q <= multlimit:
					multiplier *= q
				maxmult = max(multiplier, maxmult)
			possible.add(maxmult * lcm)
	
	ans = sum(possible)
	return str(ans)
Exemplo n.º 7
0
def compute():
    DIGITS = 10

    primes = eulerlib.list_primes(eulerlib.sqrt(10**DIGITS))

    # Only valid if 1 < n <= 10^DIGITS.
    def is_prime(n):
        end = eulerlib.sqrt(n)
        for p in primes:
            if p > end:
                break
            if n % p == 0:
                return False
        return True

    ans = 0
    # For each repeating digit
    for digit in range(10):

        # Search by the number of repetitions in decreasing order
        for rep in range(DIGITS, -1, -1):
            sum = 0
            digits = [0] * DIGITS

            # Try all possibilities for filling the non-repeating digits
            for i in range(9**(DIGITS - rep)):

                # Build initial array. For example, if DIGITS=7, digit=5, rep=4, i=123, then the array will be filled with 5,5,5,5,1,4,7.
                for j in range(rep):
                    digits[j] = digit
                temp = i
                for j in range(DIGITS - rep):
                    d = temp % 9
                    if d >= digit:  # Skip the repeating digit
                        d += 1
                    if j > 0 and d > digits[
                            DIGITS -
                            j]:  # If this is true, then after sorting, the array will be in an already-tried configuration
                        break
                    digits[-1 - j] = d
                    temp //= 9

                else:
                    digits.sort()  # Start at lowest permutation

                    while True:  # Go through all permutations
                        if digits[
                                0] > 0:  # Skip if the number has a leading zero, which means it has less than DIGIT digits
                            num = int("".join(map(str, digits)))
                            if is_prime(num):
                                sum += num
                        if not eulerlib.next_permutation(digits):
                            break

            if sum > 0:  # Primes found; skip all lesser repetitions
                ans += sum
                break

    return str(ans)
Exemplo n.º 8
0
def compute():
	DIGITS = 10
	
	primes = eulerlib.list_primes(eulerlib.sqrt(10**DIGITS))
	
	# Only valid if 1 < n <= 10^DIGITS.
	def is_prime(n):
		end = eulerlib.sqrt(n)
		for p in primes:
			if p > end:
				break
			if n % p == 0:
				return False
		return True
	
	
	ans = 0
	# For each repeating digit
	for digit in range(10):
		
		# Search by the number of repetitions in decreasing order
		for rep in range(DIGITS, -1, -1):
			sum = 0
			digits = [0] * DIGITS
			
			# Try all possibilities for filling the non-repeating digits
			for i in range(9**(DIGITS - rep)):
				
				# Build initial array. For example, if DIGITS=7, digit=5, rep=4, i=123, then the array will be filled with 5,5,5,5,1,4,7.
				for j in range(rep):
					digits[j] = digit
				temp = i
				for j in range(DIGITS - rep):
					d = temp % 9
					if d >= digit:  # Skip the repeating digit
						d += 1
					if j > 0 and d > digits[DIGITS - j]:  # If this is true, then after sorting, the array will be in an already-tried configuration
						break
					digits[-1 - j] = d
					temp //= 9
				
				else:
					digits.sort()  # Start at lowest permutation
				
					while True:  # Go through all permutations
						if digits[0] > 0:  # Skip if the number has a leading zero, which means it has less than DIGIT digits
							num = int("".join(map(str, digits)))
							if is_prime(num):
								sum += num
						if not eulerlib.next_permutation(digits):
							break
			
			if sum > 0:  # Primes found; skip all lesser repetitions
				ans += sum
				break
	
	return str(ans)
Exemplo n.º 9
0
def compute():
    primes = eulerlib.list_primes(1000000)
    num = 0
    for i in range(4, 1000000):
        if isFourPrimes(i, primes):
            num += 1
        else:
            num = 0
        if num == 4:
            print(i - 3)
            break
Exemplo n.º 10
0
def compute():
	LIMIT = 10**8 - 1
	ans = 0
	primes = eulerlib.list_primes(LIMIT // 2)
	sqrt = eulerlib.sqrt(LIMIT)
	for (i, p) in enumerate(primes):
		if p > sqrt:
			break
		end = binary_search(primes, LIMIT // p)
		ans += (end + 1 if end >= 0 else -end - 1) - i
	return str(ans)
Exemplo n.º 11
0
def compute():
    ans = 0
    primes = eulerlib.list_primes(2000000)
    for i in itertools.count(2):
        p = primes[i]
        q = primes[i + 1]
        if p > 1000000:
            break
        k = 1
        while k < p:
            k *= 10
        m = (q - p) * reciprocal_mod(k % q, q) % q
        ans += m * k + p
    return str(ans)
Exemplo n.º 12
0
def compute():
	ans = 0
	primes = eulerlib.list_primes(2000000)
	for i in itertools.count(2):
		p = primes[i]
		q = primes[i + 1]
		if p > 1000000:
			break
		k = 1
		while k < p:
			k *= 10
		m = (q - p) * eulerlib.reciprocal_mod(k % q, q) % q
		ans += m * k + p
	return str(ans)
Exemplo n.º 13
0
def prime_factors(n):
    a = []
    t = n
    if eulerlib.is_prime(t):
        return [t]
    for p in eulerlib.list_primes(t):
        while t % p == 0:
            t /= p
            a.append(p)
        if eulerlib.is_prime(t):
            a.append(t)
            break

    return a
Exemplo n.º 14
0
def compute():
	LIMIT = 10**9
	primes = eulerlib.list_primes(100)
	
	def count(primeindex, product):
		if primeindex == len(primes):
			return 1 if product <= LIMIT else 0
		else:
			result = 0
			while product <= LIMIT:
				result += count(primeindex + 1, product)
				product *= primes[primeindex]
			return result
	
	return str(count(0, 1))
Exemplo n.º 15
0
def compute():
	LIMIT = 10**9
	primes = eulerlib.list_primes(100)
	
	def count(primeindex, product):
		if primeindex == len(primes):
			return 1 if product <= LIMIT else 0
		else:
			result = 0
			while product <= LIMIT:
				result += count(primeindex + 1, product)
				product *= primes[primeindex]
			return result
	
	return str(count(0, 1))
Exemplo n.º 16
0
def compute():
    LIMIT = 5000
    MODULUS = 10**16

    # Use dynamic programming. count[i] is the number of subsets of primes with the sum of i, modulo MODULUS.
    count = [0] * (LIMIT**2 // 2)
    count[0] = 1
    s = 0  # Sum of all primes seen so far, and thus the highest index among nonzero entries in 'count'
    for p in eulerlib.list_primes(LIMIT):
        for i in range(s, -1, -1):
            count[i + p] = (count[i + p] + count[i]) % MODULUS
        s += p

    isprime = eulerlib.list_primality(len(count))
    ans = sum(count[i] for i in range(len(count)) if isprime[i]) % MODULUS
    return str(ans)
Exemplo n.º 17
0
def compute():
	LIMIT = 5000
	MODULUS = 10**16
	
	# Use dynamic programming. count[i] is the number of subsets of primes with the sum of i, modulo MODULUS.
	count = [0] * (LIMIT**2 // 2)
	count[0] = 1
	s = 0  # Sum of all primes seen so far, and thus the highest index among nonzero entries in 'count'
	for p in eulerlib.list_primes(LIMIT):
		for i in range(s, -1, -1):
			count[i + p] = (count[i + p] + count[i]) % MODULUS
		s += p
	
	isprime = eulerlib.list_primality(len(count))
	ans = sum(count[i] for i in range(len(count)) if isprime[i]) % MODULUS
	return str(ans)
def answer():
    primes = eulerlib.list_primes(1000000)
    length = 0
    max = 0
    lastj = len(primes)
    for i in range(len(primes)):
        for j in range(i + length, lastj):
            result = sum(primes[i:j])
            if (result < 1000000):
                if (result in primes):
                    length = j - i
                    max = result
            else:
                lastj = j + 1
                break
    return max
Exemplo n.º 19
0
def compute():
	LIMIT = 50000000
	primes = eulerlib.list_primes(eulerlib.sqrt(LIMIT))
	
	sums = set([0])
	for i in range(2, 5):
		newsums = set()
		for p in primes:
			q = p**i
			if q > LIMIT:
				break
			for x in sums:
				if x + q <= LIMIT:
					newsums.add(x + q)
		sums = newsums
	return str(len(sums))
Exemplo n.º 20
0
def compute():
	ans = 0
	isprime = eulerlib.list_primality(999999)
	primes = eulerlib.list_primes(999999)
	consecutive = 0
	for i in range(len(primes)):
		sum = primes[i]
		consec = 1
		for j in range(i + 1, len(primes)):
			sum += primes[j]
			consec += 1
			if sum >= len(isprime):
				break
			if isprime[sum] and consec > consecutive:
				ans = sum
				consecutive = consec
	return str(ans)
Exemplo n.º 21
0
def compute():
    ans = 0
    isprime = eulerlib.list_primality(999999)
    primes = eulerlib.list_primes(999999)
    consecutive = 0
    for i in range(len(primes)):
        sum = primes[i]
        consec = 1
        for j in range(i + 1, len(primes)):
            sum += primes[j]
            consec += 1
            if sum >= len(isprime):
                break
            if isprime[sum] and consec > consecutive:
                ans = sum
                consecutive = consec
    return str(ans)
Exemplo n.º 22
0
def compute():
    primes = eulerlib.list_primes(1000000)
    isPrimes = eulerlib.list_primality(1000000)
    max = 0
    maxConsecutive = 0
    for i in range(len(primes)):
        sum = 0
        length = 0
        for j in range(i, len(primes)):
            sum += primes[j]
            length += 1
            if sum > 1000000:
                break
            if isPrimes[sum]:
                if length > maxConsecutive:
                    max = sum
                    maxConsecutive = length
    print(max)
Exemplo n.º 23
0
def compute():
	# Collect unique numbers in Pascal's triangle
	numbers = set(eulerlib.binomial(n, k) for n in range(51) for k in range(n + 1))
	maximum = max(numbers)
	
	# Prepare list of squared primes
	primes = eulerlib.list_primes(eulerlib.sqrt(maximum))
	primessquared = [p * p for p in primes]
	
	def is_squarefree(n):
		for p2 in primessquared:
			if p2 > n:
				break
			if n % p2 == 0:
				return False
		return True
	
	# Sum up the squarefree numbers
	ans = sum(n for n in numbers if is_squarefree(n))
	return str(ans)
Exemplo n.º 24
0
def compute():
	# Collect unique numbers in Pascal's triangle
	numbers = set(eulerlib.binomial(n, k) for n in range(51) for k in range(n + 1))
	maximum = max(numbers)
	
	# Prepare list of squared primes
	primes = eulerlib.list_primes(eulerlib.sqrt(maximum))
	primessquared = [p * p for p in primes]
	
	def is_squarefree(n):
		for p2 in primessquared:
			if p2 > n:
				break
			if n % p2 == 0:
				return False
		return True
	
	# Sum up the squarefree numbers
	ans = sum(n for n in numbers if is_squarefree(n))
	return str(ans)
Exemplo n.º 25
0
def compute():
	LIMIT = 150000000
	
	INCREMENTS = [1, 3, 7, 9, 13, 27]  # Must be in non-decreasing order
	NON_INCREMENTS = set(range(INCREMENTS[-1])) - set(INCREMENTS)
	
	maxnumber = LIMIT**2 + INCREMENTS[-1]
	primes = eulerlib.list_primes(eulerlib.sqrt(maxnumber))
	
	def has_consecutive_primes(n):
		# Generate the set of numbers to test for primality
		n2 = n**2
		temp = [(n2 + k) for k in INCREMENTS]
		
		# Test that each number is prime.
		# Note: The nesting of the loops can be reversed, but this way is much faster.
		if any((x != p and x % p == 0)
				for p in primes
				for x in temp):
			return False
		
		# Test that each number that is not an increment is composite.
		# This checks that the prime numbers we found are in fact consecutive.
		return all((not is_prime(n2 + k)) for k in NON_INCREMENTS)
	
	
	def is_prime(n):
		end = eulerlib.sqrt(n)
		for p in primes:
			if p > end:
				break
			if n % p == 0:
				return False
		return True
	
	
	ans = sum(n for n in range(0, LIMIT, 10) if has_consecutive_primes(n))
	return str(ans)
Exemplo n.º 26
0
def compute():
	primes = eulerlib.list_primes(100000)
	ans = sum(p for p in primes if p == 2 or p == 5 or not has_divisible_repunit(p))
	return str(ans)
Exemplo n.º 27
0
import eulerlib

ans = sum(eulerlib.list_primes(20))
print(ans)
Exemplo n.º 28
0
def compute():
	PRIME_LIMIT = 100000  # Arbitrary initial cutoff
	primes = eulerlib.list_primes(PRIME_LIMIT)
	
	
	# Tries to find any suitable set and return its sum, or None if none is found.
	# A set is suitable if it contains only primes, its size is targetsize,
	# its sum is less than or equal to sumlimit, and each pair concatenates to a prime.
	# 'prefix' is an array of ascending indices into the 'primes' array,
	# which describes the set found so far.
	# The function blindly assumes that each pair of primes in 'prefix' concatenates to a prime.
	# 
	# For example, find_set_sum([1, 3, 28], 5, 10000) means "find the sum of any set
	# where the set has size 5, consists of primes with the lowest elements being [3, 7, 109],
	# has sum 10000 or less, and has each pair concatenating to form a prime".
	def find_set_sum(prefix, targetsize, sumlimit):
		if len(prefix) == targetsize:
			return sum(primes[i] for i in prefix)
		else:
			istart = 0 if (len(prefix) == 0) else (prefix[-1] + 1)
			for i in range(istart, len(primes)):
				if primes[i] > sumlimit:
					break
				if all((is_concat_prime(i, j) and is_concat_prime(j, i)) for j in prefix):
					prefix.append(i)
					result = find_set_sum(prefix, targetsize, sumlimit - primes[i])
					prefix.pop()
					if result is not None:
						return result
			return None
	
	
	# Tests whether concat(primes[x], primes[y]) is a prime number, with memoization.
	@eulerlib.memoize
	def is_concat_prime(x, y):
		return is_prime(int(str(primes[x]) + str(primes[y])))
	
	
	# Tests whether the given integer is prime. The implementation performs trial division,
	# first using the list of primes named 'primes', then switching to simple incrementation.
	# This requires the last number in 'primes' (if any) to be an odd number.
	def is_prime(x):
		if x < 0:
			raise ValueError()
		elif x in (0, 1):
			return False
		else:
			end = eulerlib.sqrt(x)
			for p in primes:
				if p > end:
					break
				if x % p == 0:
					return False
			for i in range(primes[-1] + 2, end + 1, 2):
				if x % i == 0:
					return False
			return True
	
	
	sumlimit = PRIME_LIMIT
	while True:
		setsum = find_set_sum([], 5, sumlimit - 1)
		if setsum is None:  # No smaller sum found
			return str(sumlimit)
		sumlimit = setsum
def compute():
	ans = sum(eulerlib.list_primes(1999999))
	return str(ans)
Exemplo n.º 30
0
def compute():
    primes = eulerlib.list_primes(100000)
    ans = sum(p for p in primes
              if p == 2 or p == 5 or not has_divisible_repunit(p))
    return str(ans)
Exemplo n.º 31
0
import eulerlib
LIMIT = 50000000
primes = eulerlib.list_primes(eulerlib.sqrt(LIMIT))

sums = {0}
for i in range(2, 5):
    newsums = set()
    for p in primes:
        q = p**i
        if q > LIMIT:
            break
        for x in sums:
            if x + q <= LIMIT:
                newsums.add(x + q)
    sums = newsums
print(str(len(sums)))
Exemplo n.º 32
0
def compute():
    ans = sum(eulerlib.list_primes(1999999))
    return str(ans)
Exemplo n.º 33
0
def compute():
    PRIME_LIMIT = 100000  # Arbitrary initial cutoff
    primes = eulerlib.list_primes(PRIME_LIMIT)

    # Tries to find any suitable set and return its sum, or None if none is found.
    # A set is suitable if it contains only primes, its size is targetsize,
    # its sum is less than or equal to sumlimit, and each pair concatenates to a prime.
    # 'prefix' is an array of ascending indices into the 'primes' array,
    # which describes the set found so far.
    # The function blindly assumes that each pair of primes in 'prefix' concatenates to a prime.
    #
    # For example, find_set_sum([1, 3, 28], 5, 10000) means "find the sum of any set
    # where the set has size 5, consists of primes with the lowest elements being [3, 7, 109],
    # has sum 10000 or less, and has each pair concatenating to form a prime".
    def find_set_sum(prefix, targetsize, sumlimit):
        if len(prefix) == targetsize:
            return sum(primes[i] for i in prefix)
        else:
            istart = 0 if (len(prefix) == 0) else (prefix[-1] + 1)
            for i in range(istart, len(primes)):
                if primes[i] > sumlimit:
                    break
                if all((is_concat_prime(i, j) and is_concat_prime(j, i))
                       for j in prefix):
                    prefix.append(i)
                    result = find_set_sum(prefix, targetsize,
                                          sumlimit - primes[i])
                    prefix.pop()
                    if result is not None:
                        return result
            return None

    # Tests whether concat(primes[x], primes[y]) is a prime number, with memoization.
    @eulerlib.memoize
    def is_concat_prime(x, y):
        return is_prime(int(str(primes[x]) + str(primes[y])))

    # Tests whether the given integer is prime. The implementation performs trial division,
    # first using the list of primes named 'primes', then switching to simple incrementation.
    # This requires the last number in 'primes' (if any) to be an odd number.
    def is_prime(x):
        if x < 0:
            raise ValueError()
        elif x in (0, 1):
            return False
        else:
            end = eulerlib.sqrt(x)
            for p in primes:
                if p > end:
                    break
                if x % p == 0:
                    return False
            for i in range(primes[-1] + 2, end + 1, 2):
                if x % i == 0:
                    return False
            return True

    sumlimit = PRIME_LIMIT
    while True:
        setsum = find_set_sum([], 5, sumlimit - 1)
        if setsum is None:  # No smaller sum found
            return str(sumlimit)
        sumlimit = setsum
Exemplo n.º 34
0
def compute():
    primes = eulerlib.list_primes(1000000)
    for n in range(5, len(primes), 2):
        rem = n * primes[n - 1] * 2
        if rem > 10000000000:
            return str(n)
Exemplo n.º 35
0
def compute():
    primes = eulerlib.list_primes(1000000)
    for n in range(5, len(primes), 2):
        rem = n * primes[n - 1] * 2
        if rem > 10000000000:
            return str(n)