Exemplo n.º 1
0
def euler69():
    result = 1
    i = 1
    while result * prime(i) < 1000000:
        result *= prime(i)
        i += 1
    print(result)
Exemplo n.º 2
0
def find_tuncatable_primes(limit=100000):
    primes = []
    for x in range(5, limit):
        prime = sympy.prime(x)
        if check_trucations(prime):
            primes.append(prime)
    return primes
Exemplo n.º 3
0
def opt_factorial_factors(factorial_n):
    prime_factors = {}
    for i in xrange(1, sympy.primepi(factorial_n) + 1):
        p = sympy.prime(i)
        k = prime_exponent(factorial_n, p)
        prime_factors[p] = k
    return prime_factors
Exemplo n.º 4
0
def test_mat_inv_mul():
    # Uses SymPy generated primes as matrix entries, so each entry in
    # each matrix should be symbolic and unique, allowing proper comparison.
    # Checks _mat_inv_mul against Matrix.inv / Matrix.__mul__.
    from sympy import Matrix, prime

    # going to form 3 matrices
    # 1 n x n
    # different n x n
    # 1 n x 2n
    n = 3
    m1 = Matrix(n, n, lambda i, j: prime(i * n + j + 2))
    m2 = Matrix(n, n, lambda i, j: prime(i * n + j + 5))
    m3 = Matrix(n, n, lambda i, j: prime(i + j * n + 2))

    assert _mat_inv_mul(m1, m2) == m1.inv() * m2
    assert _mat_inv_mul(m1, m3) == m1.inv() * m3
Exemplo n.º 5
0
    def apply(self, n, evaluation):
        'Prime[n_]'
        n_int = n.to_python()
        if isinstance(n_int, int) and n_int > 0:
            return Integer(sympy.prime(n_int))

        expr = Expression('Prime', n)
        evaluation.message('Prime', 'intpp', expr)
        return
Exemplo n.º 6
0
def consecutive_primes_length(n):
    if n not in sum_of_primes:
        starting_prime_index = 1
        starting_prime = sympy.prime(starting_prime_index)
        while starting_prime <= n:
            total = starting_prime
            # print "Starting at", starting_prime
            run_length = 1

            while total <= n:
                # print "\tTrying run length", run_length
                if sympy.isprime(total):
                    sum_of_primes[total] = max(
                        [run_length, sum_of_primes[total]])
                    # print "\t", total, "Is the sum of", run_length, "primes"
                run_length += 1
                total += sympy.prime(starting_prime_index + run_length - 1)

            starting_prime_index += 1
            starting_prime = sympy.prime(starting_prime_index)

    return sum_of_primes[n]
Exemplo n.º 7
0
def test_mat_inv_mul():
    # Just a quick test to check that KanesMethod._mat_inv_mul works as
    # intended. Uses SymPy generated primes as matrix entries, so each entry in
    # each matrix should be symbolic and unique, allowing proper comparison.
    # Checks _mat_inv_mul against Matrix.inv / Matrix.__mul__.
    from sympy import Matrix, prime
    from sympy.physics.mechanics import ReferenceFrame, KanesMethod

    # Just need to create an instance of KanesMethod to get to _mat_inv_mul
    mat_inv_mul = KanesMethod(ReferenceFrame('N'), [1], [1])._mat_inv_mul

    # going to form 3 matrices
    # 1 n x n
    # different n x n
    # 1 n x 2n
    n = 3
    m1 = Matrix(n, n, lambda i, j: prime(i * n + j + 2))
    m2 = Matrix(n, n, lambda i, j: prime(i * n + j + 5))
    m3 = Matrix(n, n, lambda i, j: prime(i + j * n + 2))

    assert mat_inv_mul(m1, m2) == m1.inv() * m2
    assert mat_inv_mul(m1, m3) == m1.inv() * m3
Exemplo n.º 8
0
def test_swinnerton_dyer_poly():
    raises(ValueError, lambda: swinnerton_dyer_poly(0, x))

    assert swinnerton_dyer_poly(1, x, polys=True) == Poly(x**2 - 2)

    assert swinnerton_dyer_poly(1, x) == x**2 - 2
    assert swinnerton_dyer_poly(2, x) == x**4 - 10*x**2 + 1
    assert swinnerton_dyer_poly(
        3, x) == x**8 - 40*x**6 + 352*x**4 - 960*x**2 + 576
    # we only need to check that the polys arg works but
    # we may as well test that the roots are correct
    p = [sqrt(prime(i)) for i in range(1, 5)]
    assert str([i.n(3) for i in
        swinnerton_dyer_poly(4, polys=True).all_roots()]
        ) == str(sorted([Add(*i).n(3) for i in permute_signs(p)]))
def main():
    import sympy

    lucky_set = set()
    i = 5
    while True:
        m = sympy.prime(i)
        if is_truncatable(m):
            lucky_set.add(m)
        if len(lucky_set) == 11:
            break
        i = i + 1

    print(lucky_set)
    print(sum(lucky_set))
Exemplo n.º 10
0
def FindPrimeMod4(numberOfPrimes):
    #This method calculates given number of primes j, with condition j mod 4 = 3.
    listOfPrimes = []
    i = 1;

    while (len(listOfPrimes) < numberOfPrimes):
        prime = sympy.prime(i)
        if(prime%4 == 3 and prime >= 600):
            listOfPrimes.append(prime)
        i = i + 1

    # print("Lista znalezionych liczb pierwszych spełniających warunki:")
    # for j in range(0, len(listOfPrimes)):
    #     print(listOfPrimes[j], " ", end="")
    # print("\n")

    return listOfPrimes
Exemplo n.º 11
0
from sympy import prime

print prime(10001)

# CORRECT
Exemplo n.º 12
0
import sympy

limit = 10000
primes = set([sympy.prime(n) for n in xrange(1, limit)])
double_squares = [2 * n * n for n in xrange(1, limit)]
odd_composites = [n for n in range(3, limit, 2) if n not in primes]

# print primes
# print double_squares
# print odd_composites


# for odd in odd_composites:
# 	found = False
# 	for p in filter(lambda x: x < odd, primes):
# 		if odd - p in double_squares:
# 			found = True
# 	if not found:
# 		print "Found one!", p


def search(targets, fast_growing_list, remainder_set):
    for target in targets:
        found = False
        # print "target", target
        for x in fast_growing_list:
            # print "testing", x
            if x > target:
                # print x, target
                break
            if target - x in remainder_set:
Exemplo n.º 13
0

def truncate_back(n):
    back = []
    for i in range(len(str(n)) - 1, 0, -1):
        back.append(int(str(n)[:i]))
    return back


i = 5
count = 11
total = 0

while count > 0:
    flag = True
    prime = sympy.prime(i)
    if not sympy.isprime(int(str(prime)[0])) or not sympy.isprime(
            int(str(prime)[-1])):
        i += 1
        continue
    right = prime
    left = 0
    mult = 1
    while right > 0 and flag:
        left += mult * (right % 10)
        flag = sympy.isprime(left) and sympy.isprime(right)
        right //= 10
        mult *= 10
    if flag:
        print(prime)
        count -= 1
Exemplo n.º 14
0
        for p2 in primes:
            if p1 != p2:
                if p1 + p2 not in membership_set:
                    # print p1+p2, "Isn't prime"
                    return False
                if p2 + p1 not in membership_set:
                    return False
                    # print p2+p1, "Isn't prime"
    # return primes, "works"

    return True


perm_set = []

primes = [str(sympy.prime(x)) for x in range(1, 10000)]
# print primes
primes_set = set([str(sympy.prime(x)) for x in range(1, 10000000)])

print "Starting search"

for x in primes:
    new_sets = []
    for perm in perm_set:
        test_set = perm + [x]
        if check_all_concats(test_set, primes_set):
            new_sets.append(test_set)
            if len(test_set) == 5:
                print test_set
                print sum(map(int, test_set))
    perm_set += new_sets
Exemplo n.º 15
0
from sympy import prime, isprime

limit = 100000
primes = [str(prime(x)) for x in range(1, limit)]
prime_set = set(primes)

for p in primes:
    for char in p:
        count = 0
        for replacement in map(str, range(10)):
            if p.replace(char, replacement) in prime_set:
                count += 1
        if count == 8:
            print p

# print primes

# print "1234".replace("1","4")
Exemplo n.º 16
0
import sympy

print(sympy.prime(10001))
Exemplo n.º 17
0
#!/usr/bin/env python
from sympy import prime
from itertools import count

# ((pn - 1)**n + (pn + 1)**n) / pn**2

# remainder is 2, 2p, 2, 6p, 2, 10p, ... per problem 120
# which is [2, 2*n*p, 2, 2*n*p, ...]

# only odd-numbered primes
for n in count(1, 2):
    p = prime(n)
    if 2 * n * p >= 1e10:
        print(n, p, 2*n*p)
        break
Exemplo n.º 18
0
import math
import itertools
import numpy as np
from sympy import prime

list2 = []
result = 0
n = int(input())

for i in range(1, n + 1):
    if (not (prime(i))):
        for j in range(1, n):
            for k in range(1, n):
                #            list2.append([i,j,k])
                result += np.gcd.reduce((i, j, k))
#            print(result ,i,k,j)
    else:
        result += (n * n) - 1
for i in range(1, n + 1):
    if (prime(i)):
        result += i
print(result)
#print(list2)
Exemplo n.º 19
0
# Project Euler Problem #7
# What is the 10,001st prime number?

import sympy
print sympy.prime(10001)
Exemplo n.º 20
0
Arquivo: machin.py Projeto: DaveMcW/pi
# I am only interested in arctangents between 1/100 and 1/463
MIN_TERM = 100
MAX_TERM = 463

# Generate and factor a^2+1
factors = {}
for a in range(1, MAX_TERM + 1):
    factors[a] = factorint(a**2 + 1)

# Generate primes of the form 4k+1
primes = []
i = 0
while True:
    i += 1
    p = prime(i)
    if p > MAX_TERM:
        break
    if p % 4 == 1:
        primes.append(p)

# Generate all 5-term combinations of primes
for x1 in range(0, len(primes)):
    for x2 in range(x1 + 1, len(primes)):
        for x3 in range(x2 + 1, len(primes)):
            for x4 in range(x3 + 1, len(primes)):
                for x5 in range(x4 + 1, len(primes)):
                    primes_subset = {2: True, primes[x1]: True, primes[x2]: True,
                                     primes[x3]: True, primes[x4]: True, primes[x5]: True}

                    # Filter squares by selected primes
Exemplo n.º 21
0
    return crt(moduli, residues)[0], time.time() - start


print("___________MULTI-PRIME RSA____________")
p, q, r = sympy.randprime(100, 10000), sympy.randprime(100,
                                                       10000), sympy.randprime(
                                                           100, 10000)
# p = 3
# q = 5
# r = 7
print("p =", p)
print("q =", q)
print("r =", r)
n = get_n(p, q, r)
print("n =", n)

phi_n = phi(p, q, r)
print("phi(n) =", phi_n)
# e = sympy.randprime(3, 5)
e = 3
print("e =", e)
d = library_modular_inverse(e, phi(p, q, r))
print("d =", d)
x = sympy.prime(30)  # n-th prime number
# print("y = enc(x) =", encryption())
y = modular_exponentiation(x, e, n)
computed_crt, t = library_CRT(e, d, p, q, y)
print("library CRT: ", computed_crt, '\n', "time = ", t, sep='')
computed_crt, t = our_CRT(e, d, p, q, y)
print("our CRT: ", computed_crt, '\n', "time = ", t, sep='')
Exemplo n.º 22
0
# triples = [(1021, 1201, 2011), (1033, 1303, 3301), (1051, 5011, 5101), (1063, 3061, 6301), (1181, 1811, 8111), (1223, 2213, 3221), (1229, 2129, 9221), (1259, 2591, 9521), (1433, 3413, 4133), (1471, 1741, 7411), (1489, 8419, 8941), (1619, 6911, 9161), (1663, 6163, 6361), (1777, 7177, 7717), (1801, 8011, 8101), (2053, 2503, 5023), (2069, 2609, 6029), (2141, 2411, 4211), (2239, 2293, 3229), (2441, 4241, 4421), (2459, 2549, 4259), (2543, 4253, 4523), (2633, 3623, 6323), (2677, 2767, 6277), (2707, 7027, 7207), (2749, 4297, 4729), (2857, 5827, 8527), (3253, 5233, 5323), (3373, 3733, 7333), (3389, 8933, 9833), (3583, 3853, 8353), (3863, 6833, 8363), (4057, 4507, 5407), (4099, 4909, 9049), (4261, 4621, 6421), (4691, 6491, 9461), (4789, 4987, 7489), (4969, 6949, 9649), (5039, 5309, 5903), (5077, 7057, 7507), (5081, 5801, 8501), (5399, 5939, 9539), (5477, 7457, 7547), (5563, 5653, 6553), (5669, 6569, 6659), (6089, 8069, 8609), (6679, 6967, 7669), (6689, 6869, 8669), (7687, 7867, 8677), (8191, 9181, 9811), (9091, 9109, 9901)]

# for triple in triples:
# 	diff1 = triple[2] - triple[1]
# 	diff2 =  triple[1] - triple[0]
# 	print diff1 == diff2, diff1, diff2, triple

# print prime_sets

# def contains_three_permutations(n, collection):

# for x in :

# 	print x, sympy.prime(x)

primes_of_interest = [sympy.prime(x) for x in range(169, 1230)]


def is_permutation(n1, n2):
    return Counter(str(n1)) == Counter(str(n2))


for prime in primes_of_interest:
    for second_prime in primes_of_interest:
        if second_prime <= prime:
            continue
        if is_permutation(prime, second_prime):
            third_prime = 2 * second_prime - prime
            if third_prime in primes_of_interest:
                if is_permutation(third_prime, second_prime):
                    print prime, second_prime, third_prime
Exemplo n.º 23
0
from itertools import compress


def rwh_primes1v1(n):
    """ Returns  a list of primes < n for n > 2 """
    sieve = bytearray([True]) * (n // 2)
    for i in range(3, int(n**0.5) + 1, 2):
        if sieve[i // 2]:
            sieve[i * i // 2::i] = bytearray((n - i * i - 1) // (2 * i) + 1)
    return [2, *compress(range(3, n, 2), sieve[1:])]


def rwh_primes1v2(n):
    """ Returns a list of primes < n for n > 2 """
    sieve = bytearray([True]) * (n // 2 + 1)
    for i in range(1, int(n**0.5) // 2 + 1):
        if sieve[i]:
            sieve[2 * i * (i + 1)::2 * i +
                  1] = bytearray((n // 2 - 2 * i * (i + 1)) // (2 * i + 1) + 1)
    return [2, *compress(range(3, n, 2), sieve[1:])]


rwh_primes1v1(100)
rwh_primes1v2(100)

# %%
import sympy as sp

sp.prime(6)
sp.prime(10001)
Exemplo n.º 24
0
# Consider the divisors of 30: 1,2,3,5,6,10,15,30.
# It can be seen that for every divisor d of 30, d+30/d is prime.

# Find the sum of all positive integers n not exceeding 100 000 000
# such that for every divisor d of n, d+n/d is prime.

import numbthy
import sympy


def divisors(n):
    return set(reduce(list.__add__,
                      ([i, n // i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))


def is_prime_generator(n):
    return n if all([sympy.isprime(d + n / d) for d in divisors(n)]) else 0

counter = 0
limit = 100000000
index = 1
n = 1
while n < limit:
    n = sympy.prime(index) - 1
    index += 1
    counter += is_prime_generator(n)


print counter
num_blocks = len(ascii_chunks)
print('No. of blocks = ', num_blocks)

# Fixing the value of q based on blocksize using prime number theory
n = np.exp(-lambertw(-1 / blocksize, k=-1))
n = int(n.real)
q = sympy.ntheory.generate.nextprime(n, ith=1)
print('Q = ', q)

prime_list = []
count = 0
temp = []
while True:
    if count == blocksize:
        break
    p = sympy.prime(random.randint(1, blocksize))
    if p not in prime_list and mod_inverse(p, q**m) != None:
        prime_list.append(p)
        count += 1
print('Initial Primes List (shuffled): ', prime_list)

prime_list_permutations = get_prime_list_permutations(prime_list, num_blocks)
print(prime_list_permutations)

t1 = time.time()

print('\nEncrypted : ')
encrypted_cipher = []
for chunk in range(len(ascii_chunks)):
    cipher = []
    for c in range(len(ascii_chunks[chunk])):
Exemplo n.º 26
0
    rhs = Gcd(*(v for k,v in test_values.items()))
    largs = list(lhs.args).sort()
    rargs = list(rhs.args).sort()
    assert largs == rargs
    assert \
            Gcd(x, y, z).subs(test_values).evalf() == \
            gcd_list(tuple(v for k,v in test_values.items())).evalf()
    assert \
            Gcd(x, y, z).evalf(subs=test_values) == \
            gcd_list(tuple(v for k,v in test_values.items())).evalf()

    # test Prime
    assert \
            Prime(x).subs({x:4}) == \
            Prime(4)
    assert \
            Prime(x).subs({x:5}).evalf() == \
            Number(prime(5)).evalf()
    assert \
            Prime(x).evalf(subs={x:6}) == \
            Number(prime(6)).evalf()

    print("All tests successfully passed")

else:

    print(
            "The test script must be run from an interpreter, "
            "instead of imported as a module."
    )
Exemplo n.º 27
0
def test_get_nth_prime():
    """Prime numbers are generated"""
    assert sympy.prime(4) == 7
    assert sympy.prime(9999999) == 179424671
    with pytest.raises(ValueError):
        assert sympy.prime(0)
Exemplo n.º 28
0
# If a is exact power b return True else return False
def is_power(a, b):
    return b**int(round(math.log(a, b))) == a


power = 10
# row, column
for e in range(3, power + 1):
    total.write(e, 0, "p^" + str(e))
    prop.write(e, 0, "p^" + str(e))

examples.set_column(1, 13, 30.0)

# Iterate through the primes
for k in range(1, 10):
    p = prime(k)
    if p > 4: power = 4
    if p > 10: power = 3
    if p > 20: power = 1

    # Write p to each rows
    total.write(0, k, p)
    prop.write(0, k, p)
    examples.write(0, k, p)

    # Initialize counts
    ired_count = 0
    wi_count = 0

    n = p**power
    for i in range(n + 1):
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 18:22:58 2020

@author: neel
"""
"""
Program to calculate 10,001st prime number
"""
import numpy
from sympy import prime
import time
#using sympy libraries
t = time.time()
primes = prime(10001)
print(primes)
print(time.time() - t)


def chk_prime(num):
    if num == 1:
        return False

    i = 2
    if not ((num + 1) % 6 == 0 or (num - 1) % 6 == 0):
        return False

    # This will loop from 2 to sqrt(x)
    while i * i <= num:
        if num % i == 0:
Exemplo n.º 30
0
import sympy

print('5 is a Prime Number',sympy.isprime(5))

print(list(sympy.primerange(0,100))


print(sympy.randprime(0,100)) #Output 83
print(sympy.randprime(0,100)) #Output 41
print(sympy.prime(3)) #Output 5
print(sympy.prevprime(50)) #Output 47
print(sympy.nextprime(50)) #Output 53
Exemplo n.º 31
0
from sympy import prime

print(prime(10001))
Exemplo n.º 32
0
def gen_primes(n):
    return list(sympy.primerange(0, sympy.prime(n) + 1))
Exemplo n.º 33
0
# Problem 10 - Find the sum of all the primes below two million.

res10 = 0
from sympy import prime
for i in range(1,2000000):
  if prime(i) > 2000000:
    break
  res10 += prime(i)

print("Answer for problem 10 is : " + "\n" + str(res10) + '\n')
Exemplo n.º 34
0
    if g != 1:
        return None
    else:
        return x % m


plaintext = input('Enter a Message : ')

m = int(input('Enter a positive integer m : '))

ascii_values = []
for c in plaintext:
    ascii_values.append(ord(c))
print('ASCII values : ', ascii_values)

q = sympy.prime(10 * len(plaintext) + 1)
print('q = ', q)

prime_list = []
count = 0
temp = []
while True:
    if count == len(plaintext):
        break
    p = sympy.prime(random.randint(1, 10 * len(plaintext)))
    if p not in prime_list and mod_inverse(p, q**m) != None:
        prime_list.append(p)
        count += 1
print('Primes : ', prime_list)

t1 = time.time()
    prime = 1

    while numberOfPrimes < n:
        prime += 1
        if isPrime(prime):
            numberOfPrimes += 1
    return prime


print(nthPrime(10001))

#Solution 2
# Pip install sympy first
from sympy import prime

x = prime(10001)
print(x)


#Solution 3
def nth_prime(n):
    primes = [2]
    num = 3
    while len(primes) < n:

        for i in primes:
            if num % i == 0:
                break

        else:
            primes.append(num)
Exemplo n.º 36
0
from sympy import prime
from math import log
from sys import exit
""" The algorith is based on the idea that if n= p1^a1 * p2^a2 *... pk^ak then div(n) = (a1+1)(a2+1)(a3+1)..(ak+1). div(n) = 2**500500 then ai = 2^q - 1.
the basic idea is to compute the first 500500 prime and then eliminate the last ones and increment the power of the firsts when possible. """
n = 500500
arr = [[prime(i + 1), 1] for i in xrange(0, n)]
i = n - 1
j = 0
while 1:
    if j == i:
        p = 1
        for k in xrange(0, i + 1):
            p = (p * (arr[k][0]**(arr[k][1]))) % 500500507
        print p
        exit(0)
    if arr[j][0]**(arr[j][1] + 1) < arr[i][0]:
        arr[j][1] = arr[j][
            1] * 2 + 1  #the power incrementation is a power of 2 so the div(n) remain 2**500500
        i -= 1
        j = 0
    else:
        j += 1
Exemplo n.º 37
0
import sympy

ans = sympy.prime(10001)

print(ans)

# Copyright Junipyr. All rights reserved.
# https://github.com/Junipyr
Exemplo n.º 38
0
 clientnames.append(connection.getpeername()[1])
 
 #send server public key
 connection.send('public_key='+pb.exportKey()+'\n')
 print 'server send RSA public key to client'
 
 
 #receive client public key
 data=connection.recv(1024)
 data=data.replace("client_key=",'')
 data=data.replace('\r\n','')
 clientPublicKey[connection.getpeername()] =data
 print 'server received client ',connection.getpeername()[1],' RSA public key'
 
 #todo try to send a, q, y
 q= sympy.prime(randint(10,100))
 a= dh_a(q)
 x= randint(3,q)         #private
 y=a**x%q                #public key, need to send 
 print 'server send client: ',connection.getpeername()[1],'Diffie-Hellman a=',a,',q=',q,',y=',y,' encrypted by client ',connection.getpeername()[1],' RSA public key' 
 #session_key=(client_public_key)**(own_private_key)%q
 DHellman=str(a)+' '+str(q)+' '+str(y)    #here can use random, but keep difficult we use 1234            
 client_publickey=RSA.importKey(clientPublicKey[connection.getpeername()])
 DHellman=str(client_publickey.encrypt(DHellman,32))
 connection.send(DHellman)
 
 DH_client_pu_key=connection.recv(1024)
 DH_client_pu_key=eval(DH_client_pu_key)
 DH_client_pu_key=pr.decrypt(DH_client_pu_key)
 sessionkey=str(int(DH_client_pu_key)**x%q)
 print 'server received client: ',connection.getpeername()[1],' pu:',DH_client_pu_key,' and compute seesion key:',sessionkey
Exemplo n.º 39
0
def primeList(beg, n):
    primeList = list()
    for i in range(beg,n+beg):
        primeList.append(prime(i))
    return primeList
Exemplo n.º 40
0
import sympy


def is_pandigital(n):
    return sorted(str(n)) == [str(i) for i in xrange(1, len(str(n)) + 1)]


limit = 100000000
for i in xrange(1, 100000000):
    prime = sympy.prime(i)
    if i % (limit / 100) == 0:
        print "Checked", i, "of", limit
    if is_pandigital(prime):
        print prime
Exemplo n.º 41
0
def get_test_input(_min, _max, max_list_len, _type):
    test_list = list()
    test_item = list()
    test_item2 = list()
    test_item3 = list()
    test_item4 = list()

    test_list.append(list())
    rand = 0
    prime = 0
    prime_n = 0
    prev_prime = 0
    next_prime = 0

    # Random number test case
    for i in range(max_list_len + 1):
        rand = random.randrange(_min, _max + 1)
        test_item.append(rand)

    test_list.append(test_item)
    test_item = []

    for i in range(max_list_len + 1):
        num = i**2
        if num <= _max:
            test_item.append(num)
        else:
            break

    for j in range(i, max_list_len + 1):
        test_item.append(test_item[j % i])

    test_list.append(test_item)

    test_item = []

    for i in range(max_list_len + 1):
        num = i**3
        if num <= _max:
            test_item.append(num)
        else:
            break

    for j in range(i, max_list_len + 1):
        test_item.append(test_item[j % i])

    test_list.append(test_item)
    test_item = []

    for i in range(max_list_len + 1):
        num = i**4
        if num <= _max:
            test_item.append(num)
        else:
            break

    for j in range(i, max_list_len + 1):
        test_item.append(test_item[j % i])
    test_list.append(test_item)
    test_item = []

    if _min < 0:

        for i in range(max_list_len + 1):
            rand = random.randrange(_min, 0)
            test_item.append(rand)
    test_list.append(test_item)
    test_item = []

    for i in range(max_list_len + 1):
        test_item.append(0)
    test_list.append(test_item)
    test_item = []

    for i in range(max_list_len + 1):
        prime = sympy.primerange(_min, _max + 1)
        prime_n = sympy.prime(n)
        prev_prime = sympy.prevprime(n)
        next_prime = sympy.nextprime(n)
        test_item.append(prime)
        test_item2.append(prime_n)
        test_item3.append(prev_prime)
        test_item4.append(next_prime)

    test_list.append(test_item)
    test_list.append(test_item2)
    test_list.append(test_item3)
    test_list.append(test_item4)

    test_item = []
    test_item2 = []
    test_item3 = []
    test_item4 = []

    for item in test_list:
        print("test_list", item)
Exemplo n.º 42
0
def PrimeGenerator():
  i = 0
  while True:
    i += 1
    yield prime(i)
Exemplo n.º 43
0
# Problem 7 - What is the 10 001 st prime number?

from sympy import prime  # Infinite list of prime numbers
print("Answer for problem 7 is : " + "\n" + str(prime(10001)) + "\n")
Exemplo n.º 44
0
"""Project Euler 7 - 10001st prime

url: https://projecteuler.net/problem=7
keywords: nth-prime
status: complete
"""
import sympy

print sympy.prime(10001)
Exemplo n.º 45
0
    def __init__(
        self,
        path: str,
        philosophy: str = "democratic",
        criterion: str = "mass",
        data=None,
    ):
        self.philosophy = philosophy
        self.criterion = criterion
        self.is_forced = False

        assert self.philosophy in {"democratic", "stringent"}
        assert self.criterion in {"mass", "dimension"}

        if data is None:
            self.path = path

            # print("Initialising database...")
            filenames = glob(os.path.join(self.path, "*.dat"))
            mvdb_data = [dict(read_completions(f)) for f in filenames]
            mv_dict = {k: v for d in mvdb_data for k, v in d.items()}
            self.data = mv_dict

        else:
            self.path = None
            self.is_ordered = True
            self.data = data

        # initialise prime dictionary
        exotics = {}
        counter = 1
        for k, v in self.data.items():
            for model in v:
                for exotic in model.quantum_numbers:
                    if exotic not in exotics:
                        exotics[conjugate_field(exotic)] = prime(counter)
                        exotics[exotic] = prime(counter)
                        counter += 1

        # dict mapping exotic field (str representation) to unique prime number
        self.exotic_prime_dict = exotics
        self.inv_exotic_prime_dict = {v: k for k, v in self.exotic_prime_dict.items()}

        term_dict = {}
        counter = 1
        for k, v in self.data.items():
            for model in v:
                n_terms = len(model.head["terms"])
                for i in range(n_terms):
                    # sort all of the terms by side effect
                    term = tuple(sorted(model.head["terms"][i]))
                    model.head["terms"][i] = term
                    if term not in term_dict:
                        # add conj term first so that when filtering you keep
                        # the unconjugated term
                        term_dict[conjugate_term(term)] = prime(counter)
                        term_dict[term] = prime(counter)
                        counter += 1

        # dict mapping sorted tuple of strings representing interaction (and
        # conjugate) to unique prime number
        self.term_prime_dict = term_dict
        self.inv_term_prime_dict = {v: k for k, v in self.term_prime_dict.items()}

        # dict mapping operator label to neutrino-mass scale estimate
        self.scale_dict = None
        self.symbolic_scale_dict = None

        # 2D array with number of models rejected from completions of jth
        # ordered operator because a subset features in completions of ith
        # ordered operator
        self.filter_data = np.zeros([len(self.data), len(self.data)])
Exemplo n.º 46
0
# 	diff2 =  triple[1] - triple[0]
# 	print diff1 == diff2, diff1, diff2, triple


# print prime_sets

# def contains_three_permutations(n, collection):


# for x in :


# 	print x, sympy.prime(x)


primes_of_interest = [sympy.prime(x) for x in range(169, 1230)]


def is_permutation(n1, n2):
    return Counter(str(n1)) == Counter(str(n2))

for prime in primes_of_interest:
    for second_prime in primes_of_interest:
        if second_prime <= prime:
            continue
        if is_permutation(prime, second_prime):
            third_prime = 2 * second_prime - prime
            if third_prime in primes_of_interest:
                if is_permutation(third_prime, second_prime):
                    print prime, second_prime, third_prime
Exemplo n.º 47
0
from sympy import prime
from sympy import nextprime
from sys import exit
""" by doing the math we find out that when n=2p , the remainder is 2, otherwise it's 2*n*Pn :D, alse, 2*n < Pn
for big n """
n = 7037
p = prime(7037)
while 1:
    if (2*p*n) - 10**10 >0:
        print n, 2*(prime(n-2))*(n-2)
        exit(1)
    p = nextprime(nextprime(p))
    n+=2
Exemplo n.º 48
0
from sympy import prime, isprime


limit = 100000
primes = [str(prime(x)) for x in range(1, limit)]
prime_set = set(primes)

for p in primes:
    for char in p:
        count = 0
        for replacement in map(str, range(10)):
            if p.replace(char, replacement) in prime_set:
                count += 1
        if count == 8:
            print p


# print primes


# print "1234".replace("1","4")
Exemplo n.º 49
0
from sympy import prime

n = 10001
print(prime(n))
Exemplo n.º 50
0
def primenth(n):
    nth_prime = prime(n)
    return nth_prime
Exemplo n.º 51
0
import random
import math
from sympy import prime

#暗号化する平文
message = 19961031

########################
###### 公開鍵の作成 ######
########################

#素数配列の作成
for i in range(500, 600):
    p_candidates = []
    p_candidates.append(prime(i))
    print(p_candidates)

    q_candidates = []
    q_candidates.append(prime(i + 100))
    print(q_candidates)

#randomモジュールの関数でランダムに要素を1つ選択
p = random.choice(p_candidates)
q = random.choice(q_candidates)

#数Nを作成
N = p * q


#関数lcm(最小公倍数を求める)を用意
def lcm(x, y):