Example #1
0
def checkDSparams(q, p, g):
    warnings.simplefilter('ignore')
    check = pyprimes.isprime(q)
    warnings.simplefilter('default')
    if check == False:
        return -1

    warnings.simplefilter('ignore')
    check = pyprimes.isprime(p)
    warnings.simplefilter('default')
    if check == False:
        return -2

    r = (p - 1) % q
    if (r != 0):
        return -3

    k = (p - 1) // q

    x = pow(g, k, p)
    if (x == 1):
        return -4
    y = pow(g, q, p)
    if (y != 1):
        return -4

    return 0
Example #2
0
def main():
    for number in count(start=101, step=2):
        number = '0' + str(number)
        zero_digit_cnt = str(number).count('0')
        if zero_digit_cnt > 0:
            zero_digit_list = []
            for idx, c in enumerate(str(number)):
                if c == str('0'):
                    zero_digit_list.append(idx)
            for replace_cnt in range(1, zero_digit_cnt + 1):
                for zero_idx_comb in combinations(zero_digit_list,
                                                  replace_cnt):
                    non_family_cnt = 0
                    translated_num = number
                    for digit in range(0, 10):
                        for idx in zero_idx_comb:
                            translated_num = str(translated_num)[0:idx] + str(
                                digit) + str(translated_num)[idx + 1:]
                        # print('--- before {} after translated {}'.format(number,translated_num))
                        if not isprime(int(translated_num)):
                            non_family_cnt += 1
                            if non_family_cnt > 10 - FAMILY_CNT:
                                break
                    if non_family_cnt == 10 - FAMILY_CNT:
                        print('we found eight prime family {}'.format(number))
                        translated_num = number
                        for digit in range(0, 10):
                            for idx in zero_idx_comb:
                                translated_num = str(
                                    translated_num)[0:idx] + str(digit) + str(
                                        translated_num)[idx + 1:]
                            if isprime(int(translated_num)):
                                print('the smallest prime of it is {}'.format(
                                    translated_num))
                                return
Example #3
0
def fitsAssumption(num):
	if num-2 == 1 or pyprimes.isprime(num-2):
		return True
	for squareNum in squares(num):
		# print squareNum*2
		if pyprimes.isprime(num-2*squareNum):
			return True
	return False
def main():
    n = 1489
    while True:
        b, c = n + 3330, n + 3330 * 2
        if isprime(n) and isprime(b) and isprime(c) \
            and is_perm(n, b) and is_perm(b, c):
            break
        n += 2
    print str(n) + str(b) + str(c)
def prime_group_good(prime_set: FrozenSet[EnumeratedPrime]) -> bool:
    global BADPAIRS
    ret = True
    for prime1, prime2 in itertools.combinations(prime_set, 2):
        if not (isprime(int(str(prime1.prime) + str(prime2.prime)))
                and isprime(int(str(prime2.prime) + str(prime1.prime)))):
            BADPAIRS.add(frozenset((prime1.index, prime2.index)))
            ret = False
    print(BADPAIRS)
    return ret
def main():
    n_prime, d, prime_ratio, n = 0, 1, 1, 2

    while prime_ratio >= 0.10:
        n_prime += isprime(d + n) + isprime(d + n*2) + isprime(d + n*3)
        d += n * 4
        n += 2
        prime_ratio = float(n_prime) / (2 * n)

    print n-1
def main():
    for i in count(3, 2):
        if not isprime(i):
            for j in count(1):
                twice_square = 2 * j * j
                if twice_square >= i:
                    print('we found a special number {}'.format(i))
                    return True
                else:
                    if isprime(i - twice_square):
                        break
def checkRight(number):
    
    number = str(number)
    while len(number) > 1:
        if pyprimes.isprime(int(number)) != True:   # check to make sure number is still prime
            return False                            # return False because number is not still prime, therefore not a truncatable prime
        else:
            number = number[:-1]                    # remove far right digit
    if pyprimes.isprime(int(number)) == True:
        return True
    else:
        return False
Example #9
0
def get_prime_repl_count(p, index_subset):
	if index_subset == []:
		if pyprimes.isprime(int(p)):
			return 1
		else:
			return 0

	count = 0
	for replacement_digit in ['0','1','2','3','4','5','6','7','8','9']:
		p_replaced = int(replace_digits(str(p), index_subset, replacement_digit))
		if pyprimes.isprime(p_replaced) and (len(str(p_replaced)) == len(str(p))):
			count += 1
	return count
Example #10
0
def prime_perms():
    for i in range(N):
        for j in range(i+1, N):
            a, b = four_primes[i], four_primes[j]
            c = 2*b - a
            if set(str(a)) == set(str(b)) == set(str(c)) and pp.isprime(c):
                print a, b, c
Example #11
0
def findEulerTotient(n):
    if (pyprimes.isprime(n)):
        return n - 1
    et = n
    for (prime, power) in pyprimes.factorise(n):
        et *= (1 - 1.0 / prime)
    return et
Example #12
0
def main():
    prime_list = list(primes_below(UPPER_LIMIT))
    prime_list_len = len(prime_list)
    consecutive_len = 0

    # find the longest possible len, which sum is below 1 million
    for consecutive_len in count(1):
        if sum(prime_list[:consecutive_len - 1]) > UPPER_LIMIT:
            break

    while consecutive_len > 0:
        i = 0
        sum_now = sum(prime_list[i:i + consecutive_len])

        while i + consecutive_len < prime_list_len:
            if sum_now > UPPER_LIMIT:
                break
            else:
                if isprime(sum_now):
                    print('found max consecutive primes sum {}'.format( \
                        sum_now \
                        ))
                    return
            sum_now = sum_now - prime_list[i] + prime_list[i + consecutive_len]
            i += 1
        consecutive_len -= 1
Example #13
0
def DL_Param_Generator(small_bound, large_bound):
    s = small_bound.bit_length()
    l = large_bound.bit_length()
    q = generateLargePrime(s)
    while q == -1:
        q = generateLargePrime(s)

    p = 1

    while not (pyprimes.isprime(p) and p.bit_length() == l):
        r = random.getrandbits(l - s)
        p = q * r + 1
        if p.bit_length() == l - 1:
            p = q * (r << 1) + 1
        elif p.bit_length() == l + 1:
            p = q * (r >> 1) + 1

    h = 2
    g = 1
    while g == 1:
        g = pow(h, (p - 1) / q, p)
        h += 1

    #F=open("DSA_params.txt", 'w')
    #F.write(str(q)+'\n'+str(p)+'\n'+str(g)+'\n')
    #F.close()

    return (q, p, g)
Example #14
0
def random_prime(bitsize):
    warnings.simplefilter('ignore')
    chck = False
    while chck == False:
        p = random.randrange(2**(bitsize - 1), 2**bitsize - 1)
        chck = pyprimes.isprime(p)
    warnings.simplefilter('default')
    return p
def main():
    primes = [] # circular primes
    for i in xrange(1, 1000000):
        if False not in [isprime(x) for x in circular(i)]:
            primes.append(i)

    #print primes
    print len(primes)
Example #16
0
def getSumOfSquares(n):
    sumOfDivisorSquares = 1
    if (pyprimes.isprime(n)):
        sumOfDivisorSquares = 1 + n * n
        return sumOfDivisorSquares
    for (prime, power) in pyprimes.factorise(n):
        sumOfDivisorSquares *= (prime**(2 * power + 2) - 1) / (prime**2 - 1)
    return sumOfDivisorSquares
Example #17
0
def circular_primes(candidate: int):
    """Return the set of circular primes of i."""
    candidates = circular_shifts(candidate)
    for shift in candidates:
        if (not isprime(shift)):
            return empty_set

    return candidates
Example #18
0
def Param_Generator():
    n_p = 3072
    n_q = 256

    while True:
        q = random.randint(0, 2**n_q)
        q = q | 1
        if pyprimes.isprime(q) == True:
            break
    print('q: ', q)
    while True:
        k = random.randint(0, 2**(n_p-n_q))
        p = q * k + 1
        if pyprimes.isprime(p):
            break
    print('p: ', p)
    return (p, q)
Example #19
0
def main():
	#primes = [x for x in range(3, 501) if isprime(x)]
	firstGroup = sum([x for x in range(3, 101) if isprime(x)])
	secondGroup = 0

	for i in range(100, 201):
		digits = [int(x) for x in str(i) if isprime(i)]
		if digits: secondGroup += reduce(mul, digits)

	thirdGroup = sum([((x * secondGroup) - firstGroup) for x in range(200, 301) if isprime(x)])
	fourthGroup = sum([thirdGroup - (x ** 2) for x in range(300, 401) if isprime(x)])
	fifthGroup = sum([sum([int(x) for x in str(x)]) for x in range(400, 501) if isprime(x)])
	print firstGroup,
	print secondGroup,
	print thirdGroup,
	print fourthGroup,
	print fifthGroup,
Example #20
0
def main():
    n, primes, total = 12, 8, 13
    while primes * 100 / total >= 10 or n % 4 > 0:
        n += 1
        if pyprimes.isprime(1 + sum([8 * (k + 1) for k in xrange(n / 4)]) + n % 4 * 2 *(n / 4 + 1)):
            primes += 1
        total += 1
    print 1 + 2 * ((n - 1) / 4 + 1)
Example #21
0
def generate_primes(bits=100):
    generator = secrets.SystemRandom()
    primes = []

    while len(primes) < 2:
        number = generator.randint(2**bits, 2**(bits + 1) - 1)
        if isprime(number) and number not in primes:
            primes.append(number)
    return primes
Example #22
0
def random_prime(bound):
    warnings.simplefilter('ignore')
    chck = False
    while chck == False:
        p = random.randrange(1, bound)
        if check_small_primes(p) == 1:
            chck = pyprimes.isprime(p)
    warnings.simplefilter('default')
    return p
Example #23
0
def large_DL_Prime(q, bitsize):
    warnings.simplefilter('ignore')
    chck = False
    while chck == False:
        k = random.randrange(2**(bitsize - 1), 2**bitsize - 1)
        p = k * q + 1
        chck = pyprimes.isprime(p)
    warnings.simplefilter('default')
    return p
def quickAnswer(numPrime):
    start = time.time()
    counter = 1
    numToCheck = 3
    while counter != numPrime:
        if pyprimes.isprime(numToCheck):
            counter += 1
        numToCheck += 1
    return '{} is the 10001st prime, found in {} seconds.'.format(numToCheck - 1, time.time() - start)
def main():
    pans = pandigital(7)
    #print pans
    max_prime = 0
    for pan in pans:
        #print pan
        if isprime(pan) and max_prime < pan:
            max_prime = pan
    print max_prime
Example #26
0
def barck_zhishu():
    r = random.randint(100, 200)
    while True:
        s = int(str(r)[-1])
        if s % 2 == 0:
            r = r + 1
        if pyprimes.isprime(r):
            return r
        else:
            r = r + 1
def main():
    primes = [] # Truncatable primes
    cnt = 1
    while True:
        if cnt < 800000:
            left = left_truncatable(cnt)
            right = right_truncatable(cnt)
            #zero = not_zero(cnt)
            if False not in [isprime(x) for x in left] \
                and False not in [isprime(x) for x in right] \
                and len(str(cnt)) > 0:
                primes.append(cnt)
            cnt += 1
        else:
            break
    primes = primes[4:]
    primes = [x for x in primes if not_zero(x) == True]
    #print primes
    #print len(primes)
    print sum(primes)
Example #28
0
def main():
    prime_cnt = 0
    diagonal_cnt = 1
    for level in count(1):
        diagonal_cnt += 4
        for number in prime_diagonal_cnt(level):
            if isprime(number):
                prime_cnt += 1
        if diagonal_cnt > 10*prime_cnt:
            print(level*2+1)
            exit(0)
Example #29
0
def findCoPrimeNos(n):
    if (pyprimes.isprime(n)):
        coPrimeNos = [num for num in xrange(1, n)]
        return coPrimeNos

    primeFactors = pyprimes.factors(n)
    coPrimeNos = [
        num for num in xrange(1, n)
        if (not checkDivisibleAny(num, primeFactors))
    ]
    return coPrimeNos
Example #30
0
 def is_valid(self):
     self.d = odict()
     res = True
     for base in range(2, 11):
         kb = self.inbase(base)
         if pyprimes.isprime(kb):
             res = False
             break
         else:
             self.d[base] = pyprimes.factorise(kb).next()[0]
     return res
Example #31
0
 def __get_prime(self, rank):
     m = 1
     this_rank = -1
     while True:
         L = 4 * m + 1
         if pyprimes.isprime(L):
             this_rank += 1
         if this_rank == rank:
             break
         m += 1
     return L
Example #32
0
def Param_Generator(qbound, pbound):

    while True:
        q = random.randint(0, qbound)
        q = q | 1
        if pyprimes.isprime(q) == True:
            break
    while True:
        k = random.randint(0, pbound-qbound)
        p = q * k + 1
        if pyprimes.isprime(p):
            break

    alpha = random.randint(0, p)
    while True:
        g = pow(alpha, (p-1)//q, p)
        if g != 1:
            break
    print('g: ', g)
    return q, p, g
Example #33
0
def check_has_pair(prime):
    result = []

    digits = str(prime)

    if len(digits) < 2:
        return None

    for d in range(len(digits) - 1):
        p1 = digits[:d + 1]
        p2 = digits[d + 1:]

        if p1[0] == '0' or p2[0] == '0':
            continue

        if pyprimes.isprime(int(p1)) and pyprimes.isprime(
                int(p2)) and pyprimes.isprime(int(str(p2) + str(p1))):
            result.append([int(p1), int(p2)])

    return result
def create_sociable_numbers(num):
    """There are some bags in this function.
    >>>create_sociable_numbers(5)
    >>>[]"""
    if isprime(num):
        return list()
    chain = list()
    chain.append(num)
    while True:
        if isprime(num):
            return list()
        sum_prodiv = sum_proper_divisors(num) # sum of proper divisors
        if sum_prodiv not in chain:
            chain.append(sum_prodiv)
            #num = sum_prodiv
        else:
            break
        num = sum_prodiv
        if is_perfect(num):
            return list()
    return chain
Example #35
0
def generate_number_list(lowerbound=2, upperbound=10):
    '''
    Generate a list of Number objects
    '''

    number_list = []
    for value in range(lowerbound, upperbound + 1):
        if pp.isprime(value) and not include_primes:
            continue
        number = Number(value=value)
        number_list.append(number)
    return number_list
Example #36
0
def main():
    prime_pair = dict()
    existing_set = dict()
    PAIR_COUNT = 5
    for single_prime in primes():
        # split prime into char combinations
        str_prime = str(single_prime)
        for break_pos in range(1, len(str_prime)):
            left = int(str_prime[:break_pos])
            right = int(str_prime[break_pos:])
            if left != 0 and right != 0 and isprime(left) and isprime(
                    right) and left != right:
                if int(str(right) + str(left)) < single_prime:
                    continue
                if isprime(int(str(right) + str(left))):
                    # put this two prime pair into cache
                    # and left is definitely smaller than right
                    if left not in existing_set:
                        existing_set[left] = list()
                        existing_set[left].append(list({right}))
                    else:
                        for idx, single_set in enumerate(existing_set[left]):
                            for prime in single_set:
                                if not isprime(
                                        int(str(right) +
                                            str(prime))) or not isprime(
                                                int(str(prime) + str(right))):
                                    break
                            else:
                                existing_set[left][idx].append(right)
                                if len(existing_set[left]
                                       [idx]) == PAIR_COUNT - 1:
                                    existing_set[left][idx].append(left)
                                    return existing_set[left][idx]
                        existing_set[left].append(list({right}))

                    if right not in existing_set:
                        existing_set[right] = list()
                        existing_set[right].append(list({left}))
                    else:
                        for idx, single_set in enumerate(existing_set[right]):
                            for prime in single_set:
                                if not isprime(
                                        int(str(left) +
                                            str(prime))) or not isprime(
                                                int(str(prime) + str(left))):
                                    break
                            else:
                                existing_set[right][idx].append(left)
                                if len(existing_set[right]
                                       [idx]) == PAIR_COUNT - 1:
                                    existing_set[right][idx].append(right)
                                    return existing_set[right][idx]
                        existing_set[right].append(list({left}))
def main():
    greatest_prime = 0
    for n in range(9, 1, -1):
        digit_array = [str(i) for i in range(1, n + 1)]
        for number in permutations(digit_array, n):
            number = int(''.join(number))
            if isprime(number):
                if greatest_prime < number:
                    greatest_prime = number

        if greatest_prime > 0:
            print 'the largest n-digit prime is {}'.format(greatest_prime)
            break
Example #38
0
def DL_Param_Generator(small_bound, large_bound):  #Parameter Generation
    q = 0
    p = 0
    while (True):
        q = bitGenerator(small_bound)

        warnings.simplefilter('ignore')
        check = pyprimes.isprime(q)
        warnings.simplefilter('default')
        if check == True:
            break
    while (True):
        k = randrange(1, large_bound / small_bound)
        p = q * k + 1
        warnings.simplefilter('ignore')
        check = pyprimes.isprime(p)
        warnings.simplefilter('default')
        if check == True:
            break

    g = generateG(p, q)
    return (q, p, g)  #Returns q, p and g.
Example #39
0
 def __get_prime(self, rank):
     """
     Determine prime of specified rank
     """
     m = 1
     this_rank = -1
     while True:
         L = 4*m + 1
         if pyprimes.isprime(L):
             this_rank += 1
         if this_rank == rank:
             break
         m += 1
     return L
Example #40
0
def GenerateOrRead(filename):
    if os.path.isfile(filename):  # check if pubparams exist.
        inputfile = open(filename, 'r')
        q = int(inputfile.readline())
        p = int(inputfile.readline())
        g = int(inputfile.readline())
    else:
        small = 1 << 224
        big = 1 << 2048
        foundq = False
        foundp = False
        foundg = False
        while not foundq:
            q = random.randint(0, small - 1)  # generates 224 bit number
            if pyprimes.isprime(q):
                foundq = True

        while not foundp:
            p = q * random.randint(0, int(
                big // small)) + 1  # generates 2048 bit p (q % p-1 = 0 )
            if pyprimes.isprime(p):
                foundp = True

        while not foundg:
            alpha = random.randint(0,
                                   p - 1)  # alpha is a random integer in mod p
            g = pow(alpha, int((p - 1) // q), p)
            if g != 1:
                foundg = True

        outputfile = open('pubparams.txt', 'w')
        outputfile.write(str(q) + "\n")
        outputfile.write(str(p) + "\n")
        outputfile.write(str(g) + "\n")
        outputfile.close()

    return q, p, g
def main():
    biggest_prime_now = 10000
    while biggest_prime_now > 1000:
        biggest_prime_now = max(primes_below(biggest_prime_now - 1))
        for middle_prime in primes_below(biggest_prime_now - 1):
            if set(list(str(biggest_prime_now))) == set(list(
                    str(middle_prime))):
                smallest_prime = 2 * middle_prime - biggest_prime_now
                if smallest_prime < 1000:
                    continue
                if isprime(smallest_prime):
                    if set(list(str(smallest_prime))) == set(
                            list(str(middle_prime))):
                        print('we found a arithmetic seq {},{},{}'.format(
                            smallest_prime, middle_prime, biggest_prime_now))
Example #42
0
def DL_Param_Generator(small_bound, large_bound):
    L = 2048
    N = 256
    seedlen = N
    q = 4
    U = 2
    domain_parameter_seed = 0
    while not isprime(q):
        # domain_parameter_seed = number.getPrime(seedlen)
        domain_parameter_seed = int(random.getrandbits(seedlen))
        U = hash(domain_parameter_seed % pow(2, N - 1))
        q = pow(2, N - 1) + U + 1 - (U % 2)

    # print("q:", q)

    offset = 1
    V = list()
    for counter in range(0, 4 * L - 1):
        outlen = (U.bit_length())
        n = L // outlen - 1
        b = L - 1 - (n * outlen)
        for j in range(0, n):
            V.append(
                hash((domain_parameter_seed + offset + j) % pow(2, seedlen)))
        W = 0
        for i in range(0, n - 1):
            W += V[i] * pow(2, (i) * outlen)
        W += (V[-1] % pow(2, b)) * pow(2, n * outlen)
        X = W + pow(2, L - 1)
        c = X % (2 * q)
        p = X - (c - 1)
        if isprime(p):
            g = subGroupGenerator(p, q)
            return q, p, g
        offset += n + 1
    return (0, 0, 0)
Example #43
0
def main():
    sums = []
    for prime in pyprimes.primes():
        if len(sums) == 0:
            sums.append(prime)
            continue
        if prime + sums[len(sums) - 1] >= 1000000:
            break
        sums.append(prime + sums[len(sums) - 1])
    maximum_length, maximum_value = 0, 0
    for i in xrange(0, len(sums) - 1):
        for j in xrange(i, len(sums)):
            if j - i > maximum_length and pyprimes.isprime(sums[j] - sums[i]):
                maximum_length, maximum_value = j - i, sums[j] - sums[i]
    print maximum_value
Example #44
0
def fast_euler_phi(n, totients):
	if n == 2:
		return 1
	if n % 2 == 0:
		if (n / 2) % 2 == 0:
			return 2 * totients[n / 2]
		else:
			return 1 * totients[n / 2]
	else:
		if pyprimes.isprime(n):
			return n-1
		else:
			phi = 1
			for (p, a) in pyprimes.factorise(n):
				phi *= (p ** (a-1)) * (p-1)
			return phi
def calc_period_old(num):
    """Return the period of amicable chain
    >>>calc_period(5)
    >>>0
    Todo: deficient number, abundant number"""
    if isprime(num):
        return 0
    chain = list()
    chain.append(num)
    while True:
        sum_prodiv = sum_proper_divisors(num) # sum of proper divisors
        if sum_prodiv not in chain:
            chain.append(sum_prodiv)
            num = sum_prodiv
        else:
            break
    return len(chain)
Example #46
0
def euler_phi(n):
    if n == 0: return 0
    if n == 1: return 1
    if n == 2: return 1
    if n % 2 == 0:
        if (n / 2) % 2 == 0:
            phi_memo[n] = 2 * euler_phi(n / 2)
        else:
            phi_memo[n] = 1 * euler_phi(n / 2)
    else:
        if pyprimes.isprime(n):
            return n - 1
        else:
            phi = 1
            for (p, a) in pyprimes.factorise(n):
                phi *= (p ** (a - 1)) * (p - 1)
            phi_memo[n] = phi
    return phi_memo[n]
def main():
    listb = list(primes_below(1000))
    listb = listb[1:]

    max_cnt = 0
    max_a = 0
    max_b = 0
    for b in listb:
        # print b
        for a in [x for x in xrange(-b / 40 - 40, 1000) if x % 2 != 0]:
            cnt = 0
            # print "(a, b)", (a, b)
            while isprime(cnt ** 2 + a * cnt + b):
                cnt += 1
                # print cnt
            if max_cnt < cnt:
                max_cnt = cnt
                max_a = a
                max_b = b
    # print listb
    # print "max_cnt", max_cnt, "max_a", max_a, "max_b", max_b
    print max_a * max_b
Example #48
0
def isPrime( n ):
    '''Uses pyprimes to check for the primality of n.'''
    return pyprimes.isprime( int( n ) )
Example #49
0
def isPrime( arg ):
    return pyprimes.isprime( int( arg ) )
Example #50
0
def concat_still_prime(p1, p2):
	return (pyprimes.isprime(int(str(p1) + str(p2)))
		and pyprimes.isprime(int(str(p2) + str(p1))))
def check_prime(num):
    return isprime(num), num
Example #52
0
import pyprimes

def cumulativeSum(l):
	sum = 0
	i = 0
	for num in l:
		i+=1
		sum += num
		yield (sum,i)


def possibleConsecutiveSums(l):
	for i in xrange(len(l)):
		for num in cumulativeSum(l[i:]):
			yield num

primesSmallEnough = []
for num in pyprimes.primes():
	if sum(primesSmallEnough) > 10**6:
		break
	primesSmallEnough.append(num)
print 'done', len(primesSmallEnough)

toPrint = [x for x in possibleConsecutiveSums(primesSmallEnough) if x[0]<10**6 and pyprimes.isprime(x[0])]
print 'done', len(toPrint)
justSecondNums = [x[1] for x in toPrint]
print toPrint[justSecondNums.index(max(justSecondNums))]
Example #53
0
			if testNum % (fact*i) == 0:
					nonpFactors.add(fact * i)
			i += 1
			nonpFactors.add(1)
			nonpFactors.add(testNum)
	if testNum in pFactors:
		pFactors.remove(testNum)
	if testNum in nonpFactors:
		nonpFactors.remove(testNum)
	return pFactors.union(nonpFactors)

def isPandigital(a,b,c):
	conCatParams = set(str(a) + str(b) + str(c))

	return len(conCatParams) == len(str(a)) +len(str(b)) + len(str(c)) and set(str(a) + str(b) + str(c)) == set(['1','2','3','4','5','6','7','8','9'])

def hasPandigitalProduct(num):
	for i in findDivsorsOf(num):
		if isPandigital(i,num/i,num):
			return True
	return False

previosSum = 0
PanDigitalProductSum = 0
pandigitals = set([])
for i in xrange(4000, 8000):
	if(not(pyprimes.isprime(i)) and len(set(str(i))) == len(str(i)) and hasPandigitalProduct(i)):
		PanDigitalProductSum += i
		pandigitals.add(i)

print sum(pandigitals)
Example #54
0
from serial import Serial
import sys
import pygame
from pygame.locals import *
from pyprimes import isprime
#import math

def GetReading():
    rawin=[]
    while len(rawin)<5:
        while (serialport.inWaiting() > 0) and len(rawin)<5:
            rawin.append(serialport.read(1))
            #Try to make some sanity check on the data
            if not(ord(rawin[0])==0x00):
                rawin=[]
            if len(rawin)>1 and not(ord(rawin[1])==0x00):
                rawin=[]
            if len(rawin)>2 and not(ord(rawin[2])==0x00):
                rawin=[]
    number=(ord(rawin[3])<<8)+ord(rawin[4])
    return number
        
    

portpath=sys.argv[1]
serialport = Serial(port=portpath, baudrate=9600)
connected=1
while True:
    Number=GetReading()
    print(str(Number)+" Prime= "+ str(isprime(Number)))
Example #55
0
def merged_numbers_are_not_prime(first_num, second_num):
	return False in [isprime(int(str(first_num) + str(second_num))), isprime(int(str(second_num) + str(first_num)))]
Example #56
0
def main():
    pandigital_prime = 0
    for number in itertools.permutations("123456"):
        if pyprimes.isprime(int("7" + "".join(number))):
            pandigital_prime = max(pandigital_prime, int("7" + "".join(number)))
    print pandigital_prime
Example #57
0
from utils.math_tools import *

import pyprimes

step_len, start_num = 2, 1

spiral_prime = []

primes_counter = 0
n_counter = 2

while True:
    crycle = 4
    while crycle:
        start_num += step_len
        crycle -= 1
        # spiral_prime.append(start_num)
        if pyprimes.isprime(start_num):
            primes_counter += 1

    n_counter += 2
    step_len += 2

    # per = per_primes(spiral_prime)
    per = primes_counter / (2.0 * n_counter)
    # print("side_length %s, primes %s, per %s" % (2 * n_counter, primes_counter, per))
    if per < 0.1:
        break

print(n_counter - 1)
Example #58
0
def isRotatingPrime(num):
	listToFill = rotation(list(str(num)))
	for numberToTest in listToFill:
		if not(pyprimes.isprime(toInt(numberToTest))):
			return False
	return True
Example #59
0
curr_sum = 0
for p in primes:
    curr_sum += p
    prefix_sums[p] = curr_sum

index = 0
max_len = -1
max_len_subseq = []
for i in xrange(0, len(primes)):
    for j in xrange(i, len(primes)):
    	index += 1
    	if index % 1000000 == 0:
    		print 'progress: ', float(index) / UB**2, '% (', float(index), '/', UB**2, ')'
    		print 'time: ', str(datetime.timedelta(seconds=(time.time() - startTime)))

        sum_to_i = prefix_sums[primes[i]]
        sum_to_j = prefix_sums[primes[j]]
        sum_from_i_to_j = sum_to_j - sum_to_i + primes[i]

        if sum_from_i_to_j < UB and pyprimes.isprime(sum_from_i_to_j):
        	curr_length = len(primes[i:j+1])
        	if max_len < curr_length:
        		print curr_length, ' : ',
        		print primes[i:j+1]
        		print ''
        		max_len = curr_length
        		max_len_subseq = primes[i:j+1]

print ''
print ''
print max_len_subseq, ' - len ', len(max_len_subseq), ', sum ', sum(max_len_subseq)