示例#1
0
def main():
    """Main program."""
    answer = 0

    start_time = time.time()

    if len(sys.argv) > 1:
        lim = int(sys.argv[1])
    else:
        lim = 5000
    n = 10
    c = 0
    while c < lim:
        S = list(primerange(0, n))
        m = len(S)
        c = count_partitions(S, m, n)
        n = n + 1

    answer = n - 1 # subtract off the last increment of n

    end_time = time.time()
    print("The answer is %d" % answer)
    print("%f seconds elapsed." % (end_time - start_time))

    import pyperclip
    pyperclip.copy(str(answer))
    print("The answer has been placed in the clipboard.")
def main(n):
    import sympy
    import itertools

    p_list = list(sympy.primerange(1, n + 1))
    lucky_set = {2}
    for i in p_list:
        if i in lucky_set:
            continue
        local_list = [i]
        digits = str(i)
        n_order = len(digits)
        for j in digits[:]:
            if int(j) % 2 == 0:
                break
        else:
            for k in range(0, n_order):
                s = digits[k:] + digits[:k]
                tmp_int = int(s)
                if tmp_int in p_list:
                    local_list.append(tmp_int)
                else:
                    break
            else:
                for m in local_list:
                    lucky_set.add(m)

    print(sorted(lucky_set))
    print(len(lucky_set))
示例#3
0
def ep10():
	primes = list(primerange(1,2000000))
	total = 0
	for p in primes:
		total += p

	return total
示例#4
0
def main():
    cities = pd.read_csv("./data/cities.csv")
    tour = pd.read_csv("./data/best2.csv")
    ids = cities["CityId"]
    primes = [p for p in sympy.primerange(0, len(ids))]

    arr = dict()
    all_x = cities["X"]
    all_y = cities["Y"]
    for i, id in enumerate(cities["CityId"]):
        arr[id] = (all_x[i], all_y[i])
    score = 0.0
    s = tour["Path"].values
    with open("./data/tour_distances3.csv", "w") as tour_dist:
        tour_dist.write("Path, dist, is_prime, needs_to_be_prime\n")
        tour_dist.write("0, 0, 0, 0\n")
        for i in range(0, len(s) - 1):
            p1 = arr[s[i]]
            p2 = arr[s[i + 1]]
            stepSize = math.sqrt((p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]))
            if s[i + 1] in primes:
                r = "1"
            else:
                r = "0"
            if ((i + 1) % 10 == 0) and (s[i] not in primes):
                stepSize *= 1.1
                tour_dist.write(str(s[i + 1]) + "," + str(stepSize) + "," + r + ",1\n")
            elif ((i + 1) % 10 == 0) and (s[i] in primes):
                tour_dist.write(str(s[i + 1]) + "," + str(stepSize) + "," + r + ",1\n")
            else:
                tour_dist.write(str(s[i + 1]) + "," + str(stepSize) + "," + r + ",0\n")
            # print(stepSize)
            score += stepSize
    print(score)
示例#5
0
def function_find_out_on_prime_number_vol_4(number):
# Генерируем список , который уже содержит простые числа из заданного диапазона !!
    prime_number = list(sympy.primerange(0, 1000))
    if number in prime_number:
        result = True
    else :
        result = False
    return result
示例#6
0
def expansion_fn(state):
    primes_below = np.array(list(sympy.primerange(0, state + 1)))
    possible_child_states = state / primes_below

    child_states = [s for s in possible_child_states if s == s // 1]
    step_costs = np.ones_like(child_states)

    return child_states, step_costs
def score_tour(tour, cities):
    df = cities.reindex(tour + [0]).reset_index()
    primes = list(sympy.primerange(0, len(cities)))
    df['prime'] = df.CityId.isin(primes).astype(int)
    df['dist'] = np.hypot(df.X - df.X.shift(-1), df.Y - df.Y.shift(-1))
    df['penalty'] = df['dist'][9::10] * (1 - df['prime'][9::10]) * 0.1
    print(df.dist.sum(), df.penalty.sum())
    return df.dist.sum() + df.penalty.sum()
示例#8
0
def conjecture(n):
    cota = int(m.sqrt((n - 2.0) / 2.0)) + 1
    primos = list(sp.primerange(2, n))
    assert n % 2 == 1 and not n in primos, 'n no cumple las hipotesis'
    for p in primos:
        for x in range(1, cota):
            if n == p + 2 * x**2:
                return (p, x)
def conjecture(n):
    cota = int(m.sqrt((n-2.0)/2.0)) + 1
    primos = list(sp.primerange(2, n))
    assert n%2==1 and not n in primos, 'n no cumple las hipotesis'
    for p in primos:
        for x in range(1, cota):
            if n == p + 2*x**2:
                return (p, x)
示例#10
0
def DpList(n):
    D = []
    for p in sy.primerange(1, n + 3):
        m = 1
        while (sy.primepi(p - m) == sy.primepi(p + m) - 1):
            m = m + 1
        D.append(m - 1)
    return D
    def check(self, f, min_p=2, max_p=30):
        # checking through few small primes to see if it is perhaps
        # either irreducible in one of those, or the degrees of irreducible factors
        # are imcompatible
        from sympy.polys.galoistools import gf_factor
        from sympy.polys.domains import ZZ
        from sympy import primerange

        irreduc_factors_degrees = {}
        irreduc_primes = []
        for p in primerange(min_p, max_p + 1):
            try:
                irreduc_factors = gf_factor(f.all_coeffs(), p, ZZ)
                degrees = []
                for x in irreduc_factors[1]:
                    pol = x[0]
                    e = x[1]
                    degrees += e * [(len(pol) - 1)]

                if len(degrees) == 1:
                    # irreducible by p...
                    irreduc_primes.append(p)

                # store irreducibility factors degrees for later
                irreduc_factors_degrees[p] = degrees
            except sympy.polys.polyerrors.NotInvertible:
                pass

        res = {}
        if irreduc_primes:
            res["p"] = irreduc_primes

        # check if the degrees are compatible, first for degrees in Fp[x], we calculate by summing
        # all possible degrees of irreducible factors in Z[x]
        sums = {}
        trivial = set(range(1, f.degree() + 1))
        for p in irreduc_factors_degrees:
            sums_p = subsets_sums(irreduc_factors_degrees[p])
            if sums_p != trivial:
                sums[p] = sums_p

        if not sums:
            return UNKNOWN, None

        # then if intersection of these is empty or {deg(f)}, then lesser degree factor is impossible
        # thus polynomial will have to be irreducible
        inter = set.intersection(*list(sums.values()))
        if f.degree() in inter:
            inter.remove(f.degree())

        if not inter:
            # intersection is empty, imcompatible factors!
            res["degrees"] = sums

        if res:
            return IRREDUCIBLE, res

        return UNKNOWN, None
示例#12
0
def calculate_factorization(number1):  #Funtion for geting factor
    dictionary = {}
    for prime in sympy.primerange(2, number1):
        if number1 % prime == 0:
            check_power = calculate_power(number1, prime)
            dictionary[prime] = check_power
            number1 /= pow(prime, check_power)
            if number1 == 1:
                return dictionary
示例#13
0
 def __generateE(self):
     print "generate e"
     # 17 257 65537
     result = 3
     for num in sympy.primerange(2, self.f):
         if gcd(num, self.f) == 1:
             result = num
             break
     return result
def candidats_CA_CB(M=10, m=1):
    # Premiers entre m et M (compris), ie. P inter [|m, ..., M|]
    C_A = list(primerange(m, M + 1))
    # Nombres pairs
    if m % 2 == 0:
        C_B = list(range(m, M - 1, 2))
    else:
        C_B = list(range(m + 1, M - 1, 2))
    return C_A, C_B
def find_factors_of_j():
    small_primes = sympy.primerange(1, 2**16)

    factors = []
    for sp in small_primes:
        if j % sp == 0:
            factors.append(sp)

    return factors
示例#16
0
def candidats_CA_CB(M=10, m=1):
    # Premiers entre m et M (compris), ie. P inter [|m, ..., M|]
    C_A = list(primerange(m, M + 1))
    # Nombres pairs
    if m % 2 == 0:
        C_B = list(range(m, M - 1, 2))
    else:
        C_B = list(range(m + 1, M - 1, 2))
    return C_A, C_B
def find_goldbach(n: int) -> Union[List, None]:
    odd_primes = [prime for prime in primerange(0, n) if prime % 2 != 0]
    shuffle(odd_primes)
    solution_space = product(odd_primes[:], odd_primes[:], odd_primes[:])

    for possible_solution in solution_space:
        if sum(possible_solution) == n:
            return possible_solution
    return None
示例#18
0
文件: 049.py 项目: sorrowise/euler
def main():
    primes = primerange(1000, 10000)
    for p in primes:
        if p != 1487:
            a = p + 3330
            b = p + 6660
            if isprime(a) and isprime(b) and set(str(p)) == set(str(a)) == set(
                    str(b)):
                return str(p) + str(a) + str(b)
示例#19
0
def n_first_primes(n):
    """
    Return first n prime numbers.
    """
    nth_prime = sympy.prime(n)
    primes_gen = sympy.primerange(1, nth_prime + 1)
    primes_lst = [num for num in primes_gen]

    return primes_lst
示例#20
0
def tiny_q():
    priv_key = None
    for prime in sympy.primerange(2, 100000):
        if n % prime == 0:
            q = prime
            p = n // q
            priv_key = PrivateKey(int(p), int(q), int(e), int(n))
            print(priv_key)
    return priv_key
示例#21
0
def public_key(phi_of_n, p, q):
    # Generates prime numbers from range 2 to phi_of_n
    li = list(sympy.primerange(2, phi_of_n))
    # Generates the list possible public keys such that public key and phi_of_n are coprime.
    li1 = []
    for i in li:     
        x = coprime(i, phi_of_n)
        if x == 1 and (i != p and i != q):
            li1.append(i)    
    return li1
示例#22
0
def main(n=20):
    primes = list(primerange(1, n))
    i, ans = 0, 1
    while primes[i] < sqrt(n):
        e = floor(log(n) / log(primes[i]))
        ans *= (primes[i])**e
        i += 1
    for p in primes[i:]:
        ans *= p
    return ans
示例#23
0
    def __init__(self, head=None):
        self._primes_iter = sp.primerange(0, 2 ** 500)
        head = ([2] if head is None else head)
        self._primes = list(head)
        self._primes_set = set(head)
        self._primes_set.add(None)

        self._order = {}
        for idx, v in enumerate(self._primes):
            self._order[v] = idx
示例#24
0
def get_prime(l):
    P = functools.reduce(mul, sympy.primerange(2, 30))
    q = random.randint(2**(l - 1), 2**l)
    while True:
        if sympy.gcd(q, P) == 1:
            break
        q += 1
    while not isprime(q):
        q += P

    return q
示例#25
0
def S(n):
    """return sum of triplet primes in the row"""

    ret = 0
    #yields the primes and their coordinates
    start = (2 - n + n * n) / 2
    for pr in primerange(start, start + n):
        #coordinates of the prime are (pr - start, n)
        if is_prime_triplet(pr - start, n):
            ret += pr
    return ret
示例#26
0
def primes_gen(*args):
    """
    Prime number generator

    Possible usages:
        primes_gen(): infinite generator
        primes_gen(a): generate all primes below a
        primes_gen(a, b): generate all primes below a and b
    """
    if len(args) == 1:
        for x in primerange(2, args[0]):
            yield x
    elif len(args) == 2:
        for x in primerange(*args):
            yield x
    elif len(args) == 0:
        x = 1
        while 1:
            x = nextprime(x)
            yield x
示例#27
0
def factorize(n):
    if isprime(n):
        return []
    res = []
    for i in primerange(0, math.sqrt(n)+1):
        if n % i == 0:
            res.append(i)
            n /= i
            if isprime(n):
                res.append(n)
                break
    return res
示例#28
0
def sum_primes():

    # establishing a zero count to add primes to
    count = 0

    # looping through all primes in range to 2 million
    for i in sympy.primerange(1, 2000000):

        count += i

    # printing the count of the primes
    print(count)
示例#29
0
def primeperms():
    primes = list(sympy.primerange(START, STOP))
    for prime1 in primes:
        for prime2 in filter(lambda x: x > prime1, primes):
            for prime3 in filter(lambda x: x > prime2, primes):
                # check for a constant increment
                if prime1 + INCREMENT  == prime2:
                    if prime2 + INCREMENT == prime3:
                        # and that these are permutations
                        if ispermutation(prime1, prime2):
                            if ispermutation(prime2, prime3):
                                return prime1, prime2, prime3
def main():
    import sympy as sp
    plist = list(sp.primerange(999, 10000))

    for i in plist:
        for j in plist[plist.index(i)+1:]:
            k = 2 * j - i
            if k in plist:
                digi_set_i = set(str(i))
                digi_set_j = set(str(j))
                digi_set_k = set(str(k))
                if digi_set_i == digi_set_j == digi_set_k :
                    print(i, j, k, sep='')
示例#31
0
 def smallp(self):
     # Try an attack where q < 100,000, from BKPCTF2016 - sourcekris
     for prime in list(primerange(0, 100000)):
         if self.pub_key['n'] % prime == 0:
             q = prime
             p = self.pub_key['n'] / q
             self.priv_key = PrivateKey({
                 'p': int(p),
                 'q': int(q),
                 'e': self.pub_key['e'],
                 'n': self.pub_key['n']
             })
     return self.priv_key
示例#32
0
def primeCheckDynamic(maxNumber, currentArray):
    if len(currentArray) < 5:
        for p in primerange(currentArray[-1] + 1, maxNumber):
            if isGood(currentArray,
                      p):  # Move until a number can be added to the array
                copyArray = currentArray[:]
                copyArray.append(p)
                result = primeCheckDynamic(maxNumber, copyArray)
                if result[0]:
                    return result
        return [False, -1]
    else:
        return [True, sum(currentArray)]
示例#33
0
def main():
    start = time.perf_counter()
    tableauchiffres = [6, 2, 5, 5, 4, 5, 6, 4, 7, 6]
    tableaumax = ["01111101", "01010000", "00110111", "01010111", "01011010", "01001111", "01101111", "01011001",
                  "01111111", "01011111"]
    p = sympy.primerange(10 ** 7, 2 * 10 ** 7)
    resultat = 0

    for u in p:
        resultat += test(u, tableauchiffres, tableaumax)

    print(resultat)
    print('temps d execution', time.perf_counter() - start, 'sec')
示例#34
0
def main(N=8400):
    res = []
    primes = list(primerange(3,N))
    index = 0
    for p in primes:
        index += 1
        for i in primes[index:]:
            if is_pair_prime(p,i):
                res.append((p,i))
    G = nx.Graph()
    G.add_edges_from(res)
    ans = [clique for clique in find_cliques(G) if len(clique)==5]
    return min(map(sum,ans))
示例#35
0
def amicable_numbers(n):
    primes = list(primerange(0, n + 1))
    numbers = set()
    for i in range(2, n):
        s1 = sum(divisors(factorize(i, primes))[:-1])
        if i == s1:  #skip perfect number like 6
            continue
        s2 = sum(divisors(factorize(s1, primes))[:-1])
        if s2 == i:
            numbers.add(i)
            numbers.add(s1)
    print(numbers)
    print(sum(numbers))
示例#36
0
def decompose(n):
    if isprime(n):
        return False
    factors = {}
    for i in primerange(2, math.sqrt(n)):
        if n % i == 0:
            n //= i
            factors[i] = factors.get(i, 0) + 1
            if isprime(n):
                factors[n] = factors.get(n, 0) + 1
            if len(factors) > 4:
                break
    return len(factors)
示例#37
0
def main():
    start = time.perf_counter()
    tableauchiffres = [6, 2, 5, 5, 4, 5, 6, 4, 7, 6]
    tableaumax = ["01111101", "01010000", "00110111", "01010111", "01011010", "01001111", "01101111", "01011001",
                  "01111111", "01011111"]
    p = sympy.primerange(10 ** 7, 2 * 10 ** 7)
    resultat = 0

    for u in p:
        resultat += test(u, tableauchiffres, tableaumax)

    print(resultat)
    print('temps d\'exécution', time.perf_counter() - start, 'sec')
示例#38
0
def find_primes_sextuplet(sum_limit):
    import sympy
    for prime in sympy.primerange(0, sum_limit):
        primelist = [
            prime, prime + 4, prime + 6, prime + 10, prime + 12, prime + 16
        ]
        primesum = 0
        for element in primelist:
            primesum += element
            if not sympy.isprime(element):
                break
        if primesum > sum_limit:
            return primelist
示例#39
0
class Tour:
    cities = read_cities()
    coords = (cities.X + 1j * cities.Y).values
    penalized = ~cities.index.isin(sympy.primerange(0, len(cities)))

    def __init__(self, data):
        """Initializes from a list/iterable of indexes or a filename of tour in csv/tsplib/linkern format."""

        if type(data) is str:
            data = self._read(data)
        elif type(data) is not np.ndarray or data.dtype != np.int32:
            data = np.array(data, dtype=np.int32)
        self.data = data

        if (self.data[0] != 0 or self.data[-1] != 0 or len(self.data) != len(self.cities) + 1):
            raise Exception('Invalid tour')

    @classmethod
    def _read(cls, filename):
        data = open(filename, 'r').read()
        if data.startswith('Path'):  # csv
            return pd.read_csv(io.StringIO(data)).Path.values
        offs = data.find('TOUR_SECTION\n')
        if offs != -1:  # TSPLIB/LKH
            data = np.fromstring(data[offs+13:], sep='\n', dtype=np.int32)
            data[-1] = 1
            return data - 1
        else:  # linkern
            data = data.replace('\n', ' ')
            data = np.fromstring(data, sep=' ', dtype=np.int32)
            if len(data) != data[0] + 1:
                raise Exception('Unrecognized format in %s' % filename)
            return np.concatenate((data[1:], [0]))

    def info(self):
        dist = np.abs(np.diff(self.coords[self.data]))
        penalty = 0.1 * np.sum(dist[9::10] * self.penalized[self.data[9:-1:10]])
        dist = np.sum(dist)
        return { 'score': dist + penalty, 'dist': dist, 'penalty': penalty }

    def dist(self):
        return self.info()['dist']

    def score(self):
        return self.info()['score']

    def __repr__(self):
        return 'Tour: %s' % str(self.info())

    def to_csv(self, filename):
        pd.DataFrame({'Path': self.data}).to_csv(filename, index=False)
示例#40
0
def primeFactors(n):
    factors = []
    primes = sympy.primerange(3, n/2)
    print("Prime Generator Ready...")
    for f in primes:

        while isFactor(n, f):
            factors.append(f)
            n = n/f

        if(n==1):
            return factors

    return factors
示例#41
0
def euler111_brute_force():
    digit_counts = defaultdict(int)
    for pr in primerange(10 ** (10 - 1), 10 ** (10 - 1 + 1)):
        cnts = Counter(str(pr))
        for x in cnts.most_common():
            if x[1] < 2:
                break
            digit_counts[x] += pr

    Sd = defaultdict(list)
    for digit_cnt, s in sorted(digit_counts.items()):
        Sd[digit_cnt[0]].append(s)

    return sum(a[-1] for a in Sd.values())
示例#42
0
def consecutive_prime_sum(max_n):
    primes = list(primerange(2,max_n))
    prime_set = set(primes)
    
    prime_len = len(primes)
    max_prime = (0,-1)
    for i in range(prime_len):
        max_p = get_largest_consecutive(primes, prime_set,i)
        if max_p[0]> max_prime[0]:
            max_prime = max_p
        if max_prime[0]> prime_len -i +1:
            break
    
    return max_prime[1]
示例#43
0
def prime_digit_replacements_of(number_of_primes,n):
    primes = primerange(10**(n-1), 10**n)
    rep_dict = {}
    for p in primes:
        p_str = str(p)
        for perm in get_star_perms(p_str):
            if perm not in rep_dict:
                rep_dict[perm] = [p,1]
            else:
                rep_dict[perm][1]+=1
    num_filter = (v for v in rep_dict.values() if v[1] == number_of_primes)
    nums = sorted(num_filter)
    if len(nums):
        return nums[0][0]
    else:
        return None
def main():
    import sympy as sp
    pl1 = list(sp.primerange(3, 10000))
    pl11 = [i for i in pl1 if i % 3 == 1 or i % 3 == 0]
    pl12 = [i for i in pl1 if i % 3 == 2 or i % 3 == 0]

    plen = len(pl1)

    best = 1111111111110
    for a in pl1:
        print(a)
        p_loc_a = []
        for b in pl1:
            if b < a:
                continue
            if ccc(a, b):
                p_loc_a.append(b)
        for b in p_loc_a:
            p_loc_b = []
            for c in p_loc_a:
                if c < b:
                    continue
                if ccc(b, c):
                    p_loc_b.append(c)
            for c in p_loc_b:
                p_loc_c = []
                for d in p_loc_b:
                    if d < c:
                        continue
                    if ccc(c, d):
                        p_loc_c.append(d)
                for d in p_loc_c:
                    for e in p_loc_c:
                        if e < d:
                            continue
                        if ccc(d, e):
                            print(a, b, c, d, e)
                            s = a + b + c + d + e
                            print(s)
                            if s < best:
                                best = s
    print("best is ", best)
def main():
    import sympy as sp
    plist = list(sp.primerange(1, 1000000))
    s, t = 0, 0
    l = 0
    best_l = 1
    best = 1
    best_s = 0
    for i in range(1, len(plist)):
        p = plist[i]
        tmp = 0
        for s in range(0, best_l):
            tmp = tmp + plist[s]
        if tmp > p:
            continue
        for s in range(0, i-1):
            if plist[s] > p // best_l:
                break
            local_sum = 0
            for t in range(s, i):
                local_sum = local_sum + plist[t]
                if local_sum > p:
                    l = t - s + 1
                    break
                if local_sum == p:
                    l = t - s + 1
                    print(p, l, s)
                    if l > best_l:
                        best_l = l
                        best = p
                        best_s = s
                    break
            if l <= best_l and local_sum > p:
                break
            if local_sum == p:
                break

    print("The longest one:", best, best_l)
示例#46
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k.
# For example, R(10) = 1111111111 = 11×41×271×9091, and the sum of these prime factors is 9414.
# Find the sum of the first forty prime factors of R(10^9).
# https://en.wikipedia.org/wiki/Repunit adresinden de görülebileceği gibi bu sayılar R(n)=10^n-1 şeklinde yazılabiliyor.
# n asal sayısının (10^(10^9) - 1)'i bölmesi gerektiğini biliyoruz. Bu nedenle python'un pow fonksiyonunu kullanarak sonucu bulmak çok kolay oluyor.
# pow kullanmak yerine 10**L%n yazmayı denediğinizde işlemlerin süresinin karşılaştırılamayacak kadar uzun sürdüğünü görebilirsiniz.

from sympy import primerange

primes = primerange(5,1000000)

bolen = []
L = 10**9

for n in primes:
    if(pow(10, L, n) == 1):
        bolen.append(n)
        if(len(bolen)==40):
            break
print(sum(bolen))
示例#47
0
This is the longest sum of consecutive primes that adds to a prime
below one-hundred.

The longest sum of consecutive primes below one-thousand that adds to a
prime, contains 21 terms, and is equal to 953.

Which prime, below one-million, can be written as the sum of the most
consecutive primes?
"""
from time import time
import numpy as np
from sympy import primerange, isprime
start_time = time()

# I found 7 below by trial and error. Wrong answer starting with 2, 3, 5 ...
primes = np.array(list(primerange(7, 4000)))

cs = np.cumsum(primes)

ip = np.vectorize(isprime)

smalls = cs[cs <= 1000000][::-1]  # Ordered descending

bools = ip(smalls)

ans = smalls[bools][0]

print("The answer is: %i") % (ans)

running_time = time()
elapsed_time = running_time - start_time
示例#48
0
"""
Created Nov 15, 2012

Author: Spencer Lyon

Project Euler Problem 26

I got the idea for how to do this from the following website:

    http://primes.utm.edu/glossary/xpage/PeriodOfADecimal.html
"""
import sympy as sym
import numpy as np

# The number must be prime and I am guessing it is big so start with highest.
primes = np.asarray(list(sym.primerange(1, 1000)))[::-1][:-3]

periods = np.asarray([sym.ntheory.n_order(10, i) for i in primes])
the_max = np.argmax(periods)

ans = primes[the_max]

print "The answer is: ", ans
示例#49
0
def test_G1():
    assert list(primerange(999983, 1000004)) == [999983, 1000003]
示例#50
0
def qnwequi(n, a, b, kind="N", equidist_pp=None):
    """
    Generates equidistributed sequences with property that averages
    value of integrable function evaluated over the sequence converges
    to the integral as n goes to infinity.

    Parameters
    ----------
    n : int
        Number of sequence points

    a : scalar or array_like(float)
        A length-d iterable of lower endpoints. If a scalar is given,
        that constant is repeated d times, where d is the number of
        dimensions

    b : scalar or array_like(float)
        A length-d iterable of upper endpoints. If a scalar is given,
        that constant is repeated d times, where d is the number of
        dimensions

    kind : string, optional(default="N")
        One of the following:

        - N - Neiderreiter (default)
        - W - Weyl
        - H - Haber
        - R - pseudo Random

    equidist_pp : array_like, optional(default=None)
        TODO: I don't know what this does

    Returns
    -------
    nodes : np.ndarray(dtype=float)
        Quadrature nodes

    weights : np.ndarray(dtype=float)
        Weights for quadrature nodes

    Notes
    -----
    Based of original function ``qnwequi`` in CompEcon toolbox by
    Miranda and Fackler

    References
    ----------
    Miranda, Mario J, and Paul L Fackler. Applied Computational
    Economics and Finance, MIT Press, 2002.

    """
    if equidist_pp is None:
        equidist_pp = np.sqrt(np.array(list(sym.primerange(0, 7920))))

    n, a, b = list(map(np.atleast_1d, list(map(np.asarray, [n, a, b]))))

    d = max(list(map(len, [n, a, b])))
    n = np.prod(n)

    if a.size == 1:
        a = np.repeat(a, d)

    if b.size == 1:
        b = np.repeat(b, d)

    i = np.arange(1, n + 1)

    if kind.upper() == "N":  # Neiderreiter
        j = 2.0 ** (np.arange(1, d+1) / (d+1))
        nodes = np.outer(i, j)
        nodes = (nodes - np.fix(nodes)).squeeze()
    elif kind.upper() == "W":  # Weyl
        j = equidist_pp[:d]
        nodes = np.outer(i, j)
        nodes = (nodes - np.fix(nodes)).squeeze()
    elif kind.upper() == "H":  # Haber
        j = equidist_pp[:d]
        nodes = np.outer(i * (i+1) / 2, j)
        nodes = (nodes - np.fix(nodes)).squeeze()
    elif kind.upper() == "R":  # pseudo-random
        nodes = np.random.rand(n, d).squeeze()
    else:
        raise ValueError("Unknown sequence requested")

    # compute nodes and weights
    r = b - a
    nodes = a + nodes * r
    weights = (np.prod(r) / n) * np.ones(n)

    return nodes, weights
示例#51
0
#!/usr/bin/env python3

from sympy import primerange
from itertools import combinations

limit = 1000000
sieve = list(primerange(2, limit))
set_sieve = set(sieve)

for p in sieve:
    p_str = str(p)
    for i in range(1, len(p_str)+1):
        for x in combinations(range(len(p_str)), i):
            ok, ukupno, z = False, 1, p_str[x[0]]
            for k in x:
                if p_str[k] != z: ok = True
            if ok: continue
            for j in range(10):
                p_str = str(p)
                for k in x: p_str = p_str[:k] + str(j) + p_str[k+1:]
                novi = int(p_str)
                if novi > p and novi in set_sieve: ukupno +=1
            if ukupno == 8: print(p)
示例#52
0
def main():
    for p in syp.primerange(1, 20):
        print(p, primitive_root(p))
示例#53
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# The primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime. The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.
# Find the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.

from sympy import primerange
from sympy import isprime
from itertools import permutations

primestest = list(primerange(3,10000))
toplam = 30000
sonuc = False
for n in primestest:
    for m in primestest[primestest.index(n)+1:]:
        if(isprime(int(str(n)+str(m)))==0 or isprime(int(str(m)+str(n)))==0):
            continue
        for p in primestest[primestest.index(m)+1:]:
            if(isprime(int(str(p)+str(m)))==0 or isprime(int(str(m)+str(p)))==0):
                continue
            for q in primestest[primestest.index(p)+1:]:
                if(n+m+p+q>toplam):
                    break
                if(isprime(int(str(p)+str(q)))==0 or isprime(int(str(q)+str(p)))==0):
                    continue
                for r in primestest[primestest.index(q)+1:]:
                    if(n+m+p+q+r>toplam):
                        break
                    if(isprime(int(str(r)+str(q)))==0 or isprime(int(str(q)+str(r)))==0):
                        continue
                    grup = permutations([n,m,p,q,r],2)
                    for i in grup:
示例#54
0
"""
Created August 22, 2012

Author: Spencer Lyon

Project Euler #10
"""
from sympy import primerange
from time import time
start_time = time()

ans = sum(list(primerange(0, 2e6)))


end_time = time()
elapsed_time = end_time - start_time
print "total time elapsed is ", elapsed_time, " seconds"
print ans
示例#55
0
one another.

There are no arithmetic sequences made up of three 1-, 2-, or 3-digit
primes, exhibiting this property, but there is one other 4-digit
increasing sequence.

What 12-digit number do you form by concatenating the three terms in
this sequence?
"""
from time import time
from sympy import primerange
from itertools import permutations

start_time = time()

nums = list(primerange(1000, 10000))
num_set = set(nums)


def is_perm(x, y):
    sx = str(x)
    sy = str(y)
    test_set = set(tuple(permutations(sy, len(sy))))
    test_tup = tuple(sx)
    return test_tup in test_set

set1 = 0

for num in nums:
    a = num
    b = num + 3330
def main(n):
    import sympy as sp
    for i in sp.primerange(100000, 1000000):
        digi_last = i % 10
        s = str(i//10)
        # if len(set(s)) > 3:
        #     continue
        for c in range(0, 2):
            if s.count(str(c)) == 3:
                count = 0
                local_list = []
                for d in range(c, 10):
                    new_s = s.replace(str(c), str(d))
                    new_digi = int(new_s) * 10 + digi_last
                    if p37.is_prime(new_digi):
                        count = count + 1
                        local_list.append(new_digi)
                        if count == n:
                            print("the lucky one:", i)
                            print(local_list)
                            return
                print(local_list)
            if s.count(str(c)) == 4:
                count = 0       # Replace the last one
                local_list = []
                for d in range(c, 10):
                    new_s = s.replace(str(c), str(d), 3)
                    new_digi = int(new_s) * 10 + digi_last
                    if p37.is_prime(new_digi):
                        count = count + 1
                        local_list.append(new_digi)
                        if count == n:
                            print("the lucky one:", i)
                            print(local_list)
                            return
                print(local_list)
                count = 0       # Replace the second one
                local_list = []
                for d in range(c, 10):
                    new_s = s.replace(str(c), str(d), 1)
                    new_s = new_s.replace(str(c), 'a', 1)
                    new_s = new_s.replace(str(c), str(d), 2)
                    new_s = new_s.replace('a', str(c), 1)
                    new_digi = int(new_s) * 10 + digi_last
                    if p37.is_prime(new_digi):
                        count = count + 1
                        local_list.append(new_digi)
                        if count == n:
                            print("the lucky one:", i)
                            print(local_list)
                            return
                print(local_list)
                count = 0       # Replace the third one
                local_list = []
                for d in range(c, 10):
                    new_s = s.replace(str(c), str(d), 2)
                    new_s = new_s.replace(str(c), 'a', 1)
                    new_s = new_s.replace(str(c), str(d), 1)
                    new_s = new_s.replace('a', str(c), 1)
                    new_digi = int(new_s) * 10 + digi_last
                    if p37.is_prime(new_digi):
                        count = count + 1
                        local_list.append(new_digi)
                        if count == n:
                            print("the lucky one:", i)
                            print(local_list)
                            return
                print(local_list)
                count = 0       # Replace the third one
                local_list = []
                for d in range(c, 10):
                    new_s = s.replace(str(c), 'a', 1)
                    new_s = new_s.replace(str(c), str(d), 3)
                    new_s = new_s.replace('a', str(c), 1)
                    new_digi = int(new_s) * 10 + digi_last
                    if p37.is_prime(new_digi):
                        count = count + 1
                        local_list.append(new_digi)
                        if count == n:
                            print("the lucky one:", i)
                            print(local_list)
                            return
                print(local_list)
        else:
            continue
示例#57
0
#!/usr/bin/env python3

from sympy import isprime, primerange
from itertools import permutations

def is_good_prime_pair(a, b):
    return  isprime(int(str(a) + str(b))) and isprime(int(str(b) + str(a)))

primes_1 = set(primerange(1, 10000))

primes_2 = set((a, b) for a, b in permutations(primes_1, 2) 
                       if is_good_prime_pair(a, b))

prime_dict_1 = dict()
prime_dict_2 = dict()
prime_dict_3 = dict()
prime_dict_4 = dict()

for a, b in primes_2:
    if a not in prime_dict_1:
        prime_dict_1[a] = set()
    prime_dict_1[a].add(b)

for a, prime_set in prime_dict_1.items():
    for b in prime_set:
        prime_dict_2[a, b] = prime_set.intersection(prime_dict_1[b])

for (a, b), prime_set in prime_dict_2.items():
    for c in prime_set:
        prime_dict_3[a, b, c] = prime_set.intersection(prime_dict_1[c])
示例#58
0
def GetSetOfPrimesInRange(e):
	primeSet = set()
	for p in primerange(10**e,10**(e+1)):
		if (str(p)[-1] in ('1','3','7')):
			primeSet.add(p)
	return primeSet
示例#59
0
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# A number consisting entirely of ones is called a repunit. We shall define R(k) to be a repunit of length k; for example, R(6) = 111111.
# Let us consider repunits of the form R(10^n).
# Although R(10), R(100), or R(1000) are not divisible by 17, R(10000) is divisible by 17. Yet there is no value of n for which R(10^n) will divide by 19. In fact, it is remarkable that 11, 17, 41, and 73 are the only four primes below one-hundred that can be a factor of R(10^n).
# Find the sum of all the primes below one-hundred thousand that will never be a factor of R(10^n).
# https://en.wikipedia.org/wiki/Repunit adresinden de görülebileceği gibi bu sayılar R(n)=10^n-1 şeklinde yazılabiliyor.

from sympy import primerange

primes = primerange(2,100000)

bolen = 3
L = 10**20

for n in primes:
    if(pow(10, L, n) != 1):
        bolen += n
print(bolen)