Ejemplo n.º 1
0
def compute():
	isprime = eulerlib.list_primality(10000)  # Cache for small numbers
	digits = list(range(1, 10))
	
	def count_prime_sets(startindex, prevnum):
		if startindex == len(digits):
			return 1
		else:
			result = 0
			for split in range(startindex + 1, len(digits) + 1):
				num = int("".join(map(str, digits[startindex : split])))
				if num > prevnum and is_prime(num):
					result += count_prime_sets(split, num)
			return result
	
	def is_prime(n):
		if n < len(isprime):
			return isprime[n]
		else:
			return eulerlib.is_prime(n)
	
	ans = 0
	while True:
		ans += count_prime_sets(0, 0)
		if not next_permutation(digits):
			break
	return str(ans)
Ejemplo n.º 2
0
def compute():
    LIMIT = 10**8

    ans = 0
    isprime = eulerlib.list_primality(LIMIT - 1)

    # Search all possible x's. Note that a + 1 = x * y * y >= x. Furthermore, a < b, so a + 1 <= b.
    # Thus if x >= LIMIT, then LIMIT <= a + 1 <= b. With b >= LIMIT, no candidates are possible.
    for x in range(1, LIMIT):

        # Search all possible y's. Notice that when y increases, 'a' strictly increases.
        # So when some y generates an 'a' such that a >= LIMIT, no candidates are possible with higher values of y.
        for y in itertools.count(1):
            a = x * y * y - 1
            if a >= LIMIT:
                break
            if not isprime[a]:
                continue

            # Search all valid z's. We require z > y and gcd(y, z) = 1. Notice that when z increases, c strictly increases.
            # So when some z generates a c such that c >= LIMIT, no candidates are possible with higher values of z.
            for z in itertools.count(y + 1):
                if fractions.gcd(y, z) != 1:
                    continue
                c = x * z * z - 1
                if c >= LIMIT:
                    break

                # Check whether (a, b, c) is a solution
                b = x * y * z - 1
                if isprime[b] and isprime[c]:
                    ans += a + b + c

    return str(ans)
Ejemplo n.º 3
0
def compute():
    LIMIT = 10**8

    ans = 0
    isprime = eulerlib.list_primality(LIMIT - 1)

    # Search all possible x's. We know that c = x * z * z - 1. With the requirement c < LIMIT, we have x * z * z <= LIMIT.
    # Because z > y > 0, we know z >= 2. So at the very least we require x * 4 <= LIMIT. This implies x <= floor(LIMIT/4).
    for x in range(1, LIMIT // 4 + 1):

        # Search all possible y's. Notice that when y increases, 'a' strictly increases.
        # So when some y generates an 'a' such that a >= LIMIT, no candidates are possible with higher values of y.
        for y in itertools.count(1):
            a = x * y * y - 1
            if a >= LIMIT:
                break
            if not isprime[a]:
                continue

            # Search all valid z's. We require z > y and gcd(y, z) = 1. Notice that when z increases, c strictly increases.
            # So when some z generates a c such that c >= LIMIT, no candidates are possible with higher values of z.
            for z in itertools.count(y + 1):
                if fractions.gcd(y, z) != 1:
                    continue
                c = x * z * z - 1
                if c >= LIMIT:
                    break

                # Check whether (a, b, c) is a solution
                if isprime[c]:
                    b = x * y * z - 1
                    if isprime[b]:
                        ans += a + b + c

    return str(ans)
Ejemplo n.º 4
0
def compute():
    isprime = eulerlib.list_primality(10000)  # Cache for small numbers
    digits = list(range(1, 10))

    def count_prime_sets(startindex, prevnum):
        if startindex == len(digits):
            return 1
        else:
            result = 0
            for split in range(startindex + 1, len(digits) + 1):
                num = int("".join(map(str, digits[startindex:split])))
                if num > prevnum and is_prime(num):
                    result += count_prime_sets(split, num)
            return result

    def is_prime(n):
        if n < len(isprime):
            return isprime[n]
        else:
            return eulerlib.is_prime(n)

    ans = 0
    while True:
        ans += count_prime_sets(0, 0)
        if not eulerlib.next_permutation(digits):
            break
    return str(ans)
Ejemplo n.º 5
0
def compute():
	LIMIT = 10**8
	
	ans = 0
	isprime = eulerlib.list_primality(LIMIT - 1)
	
	# Search all possible x's. We know that c = x * z * z - 1. With the requirement c < LIMIT, we have x * z * z <= LIMIT.
	# Because z > y > 0, we know z >= 2. So at the very least we require x * 4 <= LIMIT. This implies x <= floor(LIMIT/4).
	for x in range(1, LIMIT // 4 + 1):
		
		# Search all possible y's. Notice that when y increases, 'a' strictly increases.
		# So when some y generates an 'a' such that a >= LIMIT, no candidates are possible with higher values of y.
		for y in itertools.count(1):
			a = x * y * y - 1
			if a >= LIMIT:
				break
			if not isprime[a]:
				continue
			
			# Search all valid z's. We require z > y and gcd(y, z) = 1. Notice that when z increases, c strictly increases.
			# So when some z generates a c such that c >= LIMIT, no candidates are possible with higher values of z.
			for z in itertools.count(y + 1):
				if fractions.gcd(y, z) != 1:
					continue
				c = x * z * z - 1
				if c >= LIMIT:
					break
				
				# Check whether (a, b, c) is a solution
				if isprime[c]:
					b = x * y * z - 1
					if isprime[b]:
						ans += a + b + c
	
	return str(ans)
Ejemplo n.º 6
0
def compute():
	START_NUM = 1
	END_NUM = 500
	CROAK_SEQ = "PPPPNNPPPNPPNPN"
	
	NUM_JUMPS = len(CROAK_SEQ) - 1
	NUM_TRIALS = 2**NUM_JUMPS
	
	globalnumerator = 0
	isprime = eulerlib.list_primality(END_NUM)
	for i in range(START_NUM, END_NUM + 1):
		for j in range(NUM_TRIALS):
			pos = i
			trialnumerator = 1
			if isprime[pos] == (CROAK_SEQ[0] == 'P'):
				trialnumerator *= 2
			for k in range(NUM_JUMPS):
				if pos <= START_NUM:
					pos += 1
				elif pos >= END_NUM:
					pos -= 1
				elif (j >> k) & 1 == 0:
					pos += 1
				else:
					pos -= 1
				if isprime[pos] == (CROAK_SEQ[k + 1] == 'P'):
					trialnumerator *= 2
			globalnumerator += trialnumerator
	
	globaldenominator = (END_NUM + 1 - START_NUM) * 2**NUM_JUMPS * 3**len(CROAK_SEQ)
	ans = fractions.Fraction(globalnumerator, globaldenominator)
	return str(ans)
Ejemplo n.º 7
0
def compute():
    primes = eulerlib.list_primality(999999)

    def is_circular_prime(n):
        s = str(n)
        return all(primes[int(s[i:] + s[:i])] for i in range(len(s)))

    return sum(1 for i in range(1000000) if is_circular_prime(i))
Ejemplo n.º 8
0
def compute():
    primes = eulerlib.list_primality(999999)

    def is_truncatable(num):
        return all(primes[int(str(num)[:i])]
                   for i in range(1, len(str(num)))) and all(
                       primes[int(str(num)[i:])] for i in range(len(str(num))))

    return sum(i for i in range(10, 999999) if is_truncatable(i))
Ejemplo n.º 9
0
def compute():
    isprime = eulerlib.list_primality(999999)

    def is_circular_prime(n):
        s = str(n)
        return all(isprime[int(s[i:] + s[:i])] for i in range(len(s)))

    ans = sum(1 for i in range(len(isprime)) if is_circular_prime(i))
    return str(ans)
Ejemplo n.º 10
0
def compute():
	isprime = eulerlib.list_primality(999999)
	def is_circular_prime(n):
		s = str(n)
		return all(isprime[int(s[i : ] + s[ : i])] for i in range(len(s)))
	
	ans = sum(1
		for i in range(len(isprime))
		if is_circular_prime(i))
	return str(ans)
Ejemplo n.º 11
0
def calc():
    isprime = eulerlib.list_primality(999999)

    def s(n):
        k = str(n)
        return all(isprime[int(k[i:] + k[:i])] for i in range(len(k)))

    a = sum(1 for i in range(len(isprime)) if s(i))
    return str(a)

    print(calc())
Ejemplo n.º 12
0
def compute():
	LIMIT = 10**8
	
	isprime = eulerlib.list_primality(LIMIT + 1)
	
	def is_prime_generating(n):
		return all(
			n % d != 0 or isprime[d + n // d]
			for d in range(2, eulerlib.sqrt(n) + 1))
	
	ans = sum(n for n in range(LIMIT + 1) if isprime[n + 1] and is_prime_generating(n))
	return str(ans)
Ejemplo n.º 13
0
def compute():
    primes = eulerlib.list_primality(1000000)
    for i in range(33, 1000000, 2):
        if primes[i]:
            continue
        isOk = True
        for j in range(1, int(pow(i / 2, 1 / 2)) + 1):
            if primes[i - j * j * 2]:
                isOk = False
                break
        if isOk:
            print(i)
            break
Ejemplo n.º 14
0
def compute():
	LIMIT = 10000
	isprime = eulerlib.list_primality(LIMIT - 1)
	for base in range(1000, LIMIT):
		if isprime[base]:
			for step in range(1, LIMIT):
				a = base + step
				b = a + step
				if     a < LIMIT and isprime[a] and has_same_digits(a, base) \
				   and b < LIMIT and isprime[b] and has_same_digits(b, base) \
				   and (base != 1487 or a != 4817):
					return str(base) + str(a) + str(b)
	raise RuntimeError("Not found")
Ejemplo n.º 15
0
def compute():
    isprime = eulerlib.list_primality(
        999999)  # List of True, False,.... for whether each number is prime.

    def is_circular_prime(n):
        s = str(n)
        # Returns true if all elements pass a test:
        return all(isprime[int(s[i:] + s[:i])]
                   for i in range(len(s)))  # Cycling

    ans = sum(
        1  # Ahhh instead of i for i in .... we're just adding 1 each time
        for i in range(len(isprime)) if is_circular_prime(i))
    return str(ans)
Ejemplo n.º 16
0
def compute():
    primes = eulerlib.list_primality(10000)
    for i in range(1000, 10000):
        if not primes[i]:
            continue
        changeList = createList(str(i))
        for j in changeList:
            if j <= i:
                continue
            if list.__contains__(
                    changeList, i +
                (j - i) * 2) and primes[j] and primes[i + (j - i) * 2]:
                print(str(i) + str(j) + str(i + (j - i) * 2))
                break
Ejemplo 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)
Ejemplo n.º 18
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)
Ejemplo n.º 19
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)
Ejemplo 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)
Ejemplo n.º 21
0
def compute():
    START_NUM = 1
    END_NUM = 500
    CROAK_SEQ = "PPPPNNPPPNPPNPN"
    assert 0 <= START_NUM < END_NUM
    assert 1 <= len(CROAK_SEQ)

    NUM_JUMPS = len(CROAK_SEQ) - 1
    NUM_TRIALS = 2**NUM_JUMPS

    globalnumerator = 0
    isprime = eulerlib.list_primality(END_NUM)

    # For each starting square
    for i in range(START_NUM, END_NUM + 1):
        # For each sequence of jumps
        for j in range(NUM_TRIALS):

            # Set initial position and croak
            pos = i
            trialnumerator = 1
            if isprime[pos] == (CROAK_SEQ[0] == 'P'):
                trialnumerator *= 2

            # Simulate each jump and croak
            for k in range(NUM_JUMPS):
                if pos <= START_NUM:
                    pos += 1  # Forced move
                elif pos >= END_NUM:
                    pos -= 1  # Forced move
                elif (j >> k) & 1 == 0:
                    pos += 1  # Chosen move
                else:
                    pos -= 1  # Chosen move

                # Multiply the running probability by 2/3 if primeness of current position
                # matches croak sequence at current index, otherwise multiply by 1/3
                if isprime[pos] == (CROAK_SEQ[k + 1] == 'P'):
                    trialnumerator *= 2
            globalnumerator += trialnumerator

    # Calculate final probability fraction
    globaldenominator = (END_NUM + 1 -
                         START_NUM) * 2**NUM_JUMPS * 3**len(CROAK_SEQ)
    ans = fractions.Fraction(globalnumerator, globaldenominator)
    return str(ans)
Ejemplo 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)
Ejemplo n.º 23
0
def compute():
    primes = eulerlib.list_primality(7071)
    helo = [False] * (5 * 10**7)
    for i in range(7071):
        if primes[i]:
            for j in range(368):
                if i**2 + j**3 > len(helo) - 1:
                    break
                if primes[j]:
                    for k in range(84):
                        if i**2 + j**3 + k**4 > len(helo) - 1:
                            break
                        if primes[k]:
                            helo[i**2 + j**3 + k**4] = True
    ans = 0
    for i in range(len(helo)):
        if helo[i]:
            ans += 1
    return ans
Ejemplo n.º 24
0
def compute():
	isprime = eulerlib.list_primality(1000000)
	for i in range(len(isprime)):
		if not isprime[i]:
			continue
		
		n = [int(c) for c in str(i)]
		for mask in range(1 << len(n)):
			digits = do_mask(n, mask)
			count = 0
			for j in range(10):
				if digits[0] != 0 and isprime[to_number(digits)]:
					count += 1
				digits = add_mask(digits, mask)
			
			if count == 8:
				digits = do_mask(n, mask)
				for j in range(10):
					if digits[0] != 0 and isprime[to_number(digits)]:
						return str(to_number(digits))
					digits = add_mask(digits, mask)
	raise AssertionError("Not found")
Ejemplo n.º 25
0
def compute():
    LIMIT = 10**7

    isprime = eulerlib.list_primality(LIMIT)

    # pathmax[i] = None if i is not prime or i is not connected to 2.
    # Otherwise, considering all connection paths from 2 to i and for each path computing
    # the maximum number, pathmax[i] is the minimum number among all these maxima.
    pathmax = [None] * len(isprime)

    # Process paths in increasing order of maximum number
    queue = [(2, 2)]
    while len(queue) > 0:
        pmax, n = heapq.heappop(queue)
        if pathmax[n] is not None and pmax >= pathmax[n]:
            # This happens if at the time this update was queued, a better
            # or equally good update was queued ahead but not processed yet
            continue

        # Update the target node and explore neighbors
        pathmax[n] = pmax

        # Try all replacements of a single digit, including the leading zero.
        # This generates exactly all (no more, no less) the ways that a number m is connected to n.
        digits = to_digits(n)
        tempdigits = list(digits)
        for i in range(len(tempdigits)):  # For each digit position
            for j in range(10):  # For each digit value
                tempdigits[i] = j
                m = to_number(tempdigits)
                nextpmax = max(m, pmax)
                if m < len(isprime) and isprime[m] and (pathmax[m] is None or
                                                        nextpmax < pathmax[m]):
                    heapq.heappush(queue, (nextpmax, m))
            tempdigits[i] = digits[i]  # Restore the digit

    ans = sum(i for i in range(len(isprime))
              if (isprime[i] and (pathmax[i] is None or pathmax[i] > i)))
    return str(ans)
Ejemplo n.º 26
0
def compute():
	LIMIT = 10**7
	
	isprime = eulerlib.list_primality(LIMIT)
	
	# pathmax[i] = None if i is not prime or i is not connected to 2.
	# Otherwise, considering all connection paths from 2 to i and for each path computing
	# the maximum number, pathmax[i] is the minimum number among all these maxima.
	pathmax = [None] * len(isprime)
	
	# Process paths in increasing order of maximum number
	queue = [(2, 2)]
	while len(queue) > 0:
		pmax, n = heapq.heappop(queue)
		if pathmax[n] is not None and pmax >= pathmax[n]:
			# This happens if at the time this update was queued, a better
			# or equally good update was queued ahead but not processed yet
			continue
		
		# Update the target node and explore neighbors
		pathmax[n] = pmax
		
		# Try all replacements of a single digit, including the leading zero.
		# This generates exactly all (no more, no less) the ways that a number m is connected to n.
		digits = to_digits(n)
		tempdigits = list(digits)
		for i in range(len(tempdigits)):  # For each digit position
			for j in range(10):  # For each digit value
				tempdigits[i] = j
				m = to_number(tempdigits)
				nextpmax = max(m, pmax)
				if m < len(isprime) and isprime[m] and (pathmax[m] is None or nextpmax < pathmax[m]):
					heapq.heappush(queue, (nextpmax, m))
			tempdigits[i] = digits[i]  # Restore the digit
	
	ans = sum(i for i in range(len(isprime))
		if isprime[i] and (pathmax[i] is None or pathmax[i] > i))
	return str(ans)
Ejemplo n.º 27
0
def compute():
	TARGET = 500500
	MODULUS = 500500507
	isprime = eulerlib.list_primality(7376507)  # 500500th (1-based) prime number
	
	queue = []
	nextprime = 2
	heapq.heappush(queue, nextprime)
	
	ans = 1
	for _ in range(TARGET):
		item = heapq.heappop(queue)
		ans *= item
		ans %= MODULUS
		heapq.heappush(queue, item**2)
		
		if item == nextprime:
			nextprime += 1
			while not isprime[nextprime]:
				nextprime += 1
			heapq.heappush(queue, nextprime)
	
	return str(ans)
Ejemplo n.º 28
0
import eulerlib, itertools


def compute():
	ans = max(((a, b) for a in range(-999, 1000) for b in range(2, 1000)),
		key=count_consecutive_primes)
	return str(ans[0] * ans[1])


def count_consecutive_primes(ab):
	a, b = ab
	for i in itertools.count():
		n = i * i + i * a + b
		if not is_prime(n):
			return i


isprimecache = eulerlib.list_primality(1000)

def is_prime(n):
	if n < 0:
		return False
	elif n < len(isprimecache):
		return isprimecache[n]
	else:
		return eulerlib.is_prime(n)


if __name__ == "__main__":
	print(compute())
Ejemplo n.º 29
0
import eulerlib, itertools


def calc():
    ans = max(((a, b) for a in range(-999, 1000) for b in range(2, 1000)),
              key=ppc)
    return str(ans[0] * ans[1])


def ppc(ab):  #счет простых чисел
    a, b = ab
    for i in itertools.count():
        n = i * i + i * a + b
        if not is_prime(n):
            return i


main_c = eulerlib.list_primality(1000)  #основной кеш


def is_prime(n):
    if n < 0:
        return False
    elif n < len(main_c):
        return main_c[n]
    else:
        return eulerlib.is_prime(n)

    print(calc())
Ejemplo n.º 30
0
import eulerlib, sys
if sys.version_info.major == 2:
    range = xrange

isprime = eulerlib.list_primality(999999)


def compute():
    ans = sum(1 for i in range(len(isprime)) if is_circular_prime(i))
    return str(ans)


def is_circular_prime(n):
    s = str(n)
    return all(isprime[int(s[i:] + s[:i])] for i in range(len(s)))


if __name__ == "__main__":
    print(compute())
Ejemplo n.º 31
0
# 
# Solution to Project Euler problem 35
# by Project Nayuki
# 
# http://www.nayuki.io/page/project-euler-solutions
# https://github.com/nayuki/Project-Euler-solutions
# 

import eulerlib, sys
if sys.version_info.major == 2:
	range = xrange


isprime = eulerlib.list_primality(999999)

def compute():
	ans = 0
	for i in range(len(isprime)):
		if is_circular_prime(i):
			ans += 1
	return str(ans)


def is_circular_prime(n):
	s = str(n)
	for i in range(len(s)):
		if not isprime[int(s[i : ] + s[ : i])]:
			return False
	return True

Ejemplo n.º 32
0
def compute():
    isprime = eulerlib.list_primality(20000000)
    ans = sum(sam_transitions_minus_max_transitions(i) for (i, p) in enumerate(isprime) if i >= 10000000 and p)
    return str(ans)
Ejemplo n.º 33
0
def compute():
    isprime = eulerlib.list_primality(20000000)
    ans = sum(
        sam_transitions_minus_max_transitions(i)
        for (i, p) in enumerate(isprime) if i >= 10000000 and p)
    return str(ans)
Ejemplo n.º 34
0

def compute():
    ans = max(((a, b) for a in range(-999, 1000) for b in range(2, 1000)),
              key=count_consecutive_primes)
    return str(ans[0] * ans[1])


def count_consecutive_primes(ab):
    a, b = ab
    for i in itertools.count():
        n = i * i + i * a + b
        if not is_prime(n):
            return i


isprimecache = eulerlib.list_primality(1000)


def is_prime(n):
    if n < 0:
        return False
    elif n < len(isprimecache):
        return isprimecache[n]
    else:
        return eulerlib.is_prime(n)


if __name__ == "__main__":
    print(compute())