예제 #1
0
def primeSet(primes, n):
    #print(primes, n)
    if n < 1:
        print("n must be greater than 1")
        return
    if n == 1:
        returnSet = [[primes[i]] for i in range(len(primes))]
        return returnSet
    else:
        print(n, "start")
        returnSet = []
        pSets = primeSet(primes, n - 1)
        Timer.startTimer()
        for i in range(len(pSets)):
            for j in range(i, len(pSets)):
                if pSets[i][1:] == pSets[j][:-1]:
                    if Primes.isPrime(concat(
                            pSets[i][0], pSets[j][-1])) and Primes.isPrime(
                                concat(pSets[j][-1], pSets[i][0])):
                        temp = list(pSets[i])
                        temp.append(pSets[j][-1])
                        returnSet.append(temp)
        Timer.endTimer()
        Timer.printTime()
        print("Sets of", n, ":", len(returnSet))
        return returnSet
    return
예제 #2
0
def Program(nMax=100, GRAPHICS=False):
    primes = Primes.MakePrimeList(nMax)
    primeGraph = Networks.UndirectedGraph()

    for p in primes:
        primeGraph.AddNode(p)
        for p2 in primeGraph.GetNodes():
            if Primes.isPrime(concatenateIntegers(p, p2), primes):
                if Primes.isPrime(concatenateIntegers(p2, p), primes):
                    primeGraph.AddEdge(p, p2)

    for p1 in primes:
        possibles = primeGraph.GetNeighbors(p1)
        for p2 in possibles:
            possibles2 = listIntersection(possibles,
                                          primeGraph.GetNeighbors(p2))
            for p3 in possibles2:
                possibles3 = listIntersection(possibles2,
                                              primeGraph.GetNeighbors(p3))
                for p4 in possibles3:
                    possibles4 = listIntersection(possibles3,
                                                  primeGraph.GetNeighbors(p4))
                    for p5 in possibles4:
                        print(p1, p2, p3, p4, p5), p1 + p2 + p3 + p4 + p5

    if GRAPHICS:
        NetGraphics.DisplayCircleGraph(primeGraph)

    return primeGraph
예제 #3
0
def eightDivisorCount(n):
    ps = Primes.MakePrimeList(int(n**0.5)+2)
    primePi = Primes.Prime_Pi()
    f = 0
    for p in ps:
        if p**7 > n:
            break
        #print p
        f += 1
    for p in ps:
        if 2*p**3 > n:
            break
        f += primePi(n//(p**3), ps)
        print p,f,len(primePi.restricted_memo)
        if (n//(p**3)) >= p:
            f -= 1
        #print p, primePi(n//(p**3), ps)
    for n1,p1 in enumerate(ps):
        if p1**3 >= n:
            break
        for p2 in ps[n1+1:]:
            if p1*p2*p2 >= n:
                break
            f += primePi(n//(p1*p2),ps) - primePi(p2,ps)
            #print p1,p2,primePi(n//(p1*p2),ps),primePi(p2,ps)
            if p2 < 10000:
                print p1,p2,f,len(primePi.restricted_memo)
        print p1,f,len(primePi.restricted_memo)

    return f
예제 #4
0
def new_432(m):
    #primes = Primes.MakePrimeList(int(1.2*m**(1./2))+100)
    primes = Primes.MakePrimeList(int(1.2 * m**(1. / 2)) + 120)
    prime_pi = Primes.Prime_Pi()
    ans = sum_range(1, 18) + func(m, 7, primes, prime_pi)
    ans *= 510510
    for ix in range(7):
        ans *= (primes[ix] - 1)
        ans /= primes[ix]
    return ans
def Euler131(N):
    primes = Primes.MakePrimeList(int(sp.sqrt(N))+4)
    x = 1
    p = 3*x*x+3*x+1
    count = 0
    while p <= N:
        if Primes.isPrime(p, primes):
            count += 1
        x += 1
        p = 3*x*x + 3*x + 1
    return count
예제 #6
0
def highly_divisible(n):
    numfactors = 0
    i = n
    ti = triangle_num (i)
    while numfactors <= n:
        if not Primes.isPrime(ti):
            numfactors = Primes.get_num_factors(ti)
        if numfactors <= n:
            i += 1
            ti = triangle_num (i)
            #print (ti)
    else:
        return ti
예제 #7
0
def main(): 
	truncPrimes = getTruncPrimes(Primes.getPrimes(1000000));
	truncSum = 0;
	for p in truncPrimes: 
		truncSum += p

	print truncSum
예제 #8
0
def primeFrogProbability(N, croak_string):
    ps = Primes.MakePrimeList(N)
    ans = Fraction(0)
    memo = {}
    for position in range(1, N + 1):
        ans += calcCroakProbability(N, position, croak_string, ps, memo)
    return ans / N
예제 #9
0
def calcCroakProbability(N, position, croak_string, ps, memo):
    if len(croak_string) == 0:
        return 1
    key = (N, position, croak_string)
    try:
        return memo[key]
    except KeyError:
        pass

    prob_croak_correct = Fraction(1, 3)
    is_prime = Primes.isPrime(position, ps)
    if ((is_prime and croak_string[0] == 'P')
            or (not is_prime and croak_string[0] == 'N')):
        prob_croak_correct *= 2

    if position == 1:
        memo[key] = calcCroakProbability(N, 2, croak_string[1:], ps, memo)
    elif position == N:
        memo[key] = calcCroakProbability(N, N - 1, croak_string[1:], ps, memo)
    else:
        memo[key] = (
            calcCroakProbability(N, position - 1, croak_string[1:], ps, memo) +
            calcCroakProbability(N, position + 1, croak_string[1:], ps, memo))
        memo[key] /= 2

    memo[key] *= prob_croak_correct
    return memo[key]
예제 #10
0
def compute_jamcoins(digits, n):
	
	b2_max = int("1"*digits,2)
	b2_min = int("1" + (digits-2)*"0" + "1", 2)
	
	primes = Primes.primes

	jamcoins = {}

	i = b2_min

	while len(jamcoins) < n:

		potential = bin(i)[2:]

		value = 0
		
		factors = [potential]

		for j in range(2, 11):
			value = 0
			value = Primes.isPrime(int(potential,j))
			if not value:
				break
			factors.append(str(value))

		if value:
			jamcoins[potential] = factors
			print(' '.join(factors))

		i += 2

	return jamcoins 
def Euler118_2():
    primes = Primes.MakePrimeList(100000000)
    print 'Primes Calculated'
    primes = [p for p in primes if not repeats_digits(p)]
    print 'Primes with repeated digits eliminated'
    num_sets = build_sets(0,[], primes)
    print 'Number of Pandigital Prime Sets: '+str(num_sets)
    return num_sets
def PossiblePrimesList(N):
    # Get all the candidates for primes changing 3 digits
    ps = Primes.PrimeList(N)
    possList = []
    for p in ps:
        if Has3sameDigits(p):
            possList.append(p)

    return possList
예제 #13
0
def Euler484a(N):
    start = time.clock()
    p_max = int(sp.sqrt(N) + 1000)
    primes = Primes.MakePrimeList(p_max)
    print 'Primes up to %d calculated.  %d primes' % (p_max, len(primes))
    ans = F(N, 0, primes)
    end = time.clock()
    print '%f seconds' % (end - start, )
    return ans
def Euler118_1():
    permutes   = itertools.permutations([1,2,3,4,5,6,7,8,9])
    primes     = Primes.MakePrimeList(10000)
    prime_sets = set()
    
    for digit_list in permutes:
        find_prime_sets(digit_list, set(), prime_sets, primes)
    print 'Number of Pandigital Prime Sets: '+str(len(prime_sets))
    return prime_sets
예제 #15
0
def make_dfact(n, primes):
    dfact = {}
    r = 1
    while r <= len(primes) and sp.prod(primes[:r]) <= n:
        for c in Primes.combProdLessThan(primes, r, n):
            d = int(round(sp.prod(c)) + 0.01)
            dfact[d] = c
        r += 1
    return dfact
예제 #16
0
def Euler77(numWays):
    """
    Finds the first number that can be partitioned into primes in numWays.
    """
    primeList = Primes.MakePrimeList(max(numWays, 100))
    partialPrimeMemo = {}
    n = 2
    while primePartition(n, primeList, partialPrimeMemo) < numWays:
        n += 1
    return n
예제 #17
0
def old_432(m):
    primes = Primes.MakePrimeList(int(m * 2))
    ans = sum_range(1, 18)
    ans += weird_sum_tot(m, 7, primes)
    ans *= 510510
    for ix in range(7):
        ans *= (primes[ix] - 1)
        ans /= primes[ix]

    return ans
예제 #18
0
def Euler231(n, m):
    """ n choose m
    """
    pList = Primes.MakePrimeList(n + 1)
    summ = 0
    for p in pList:
        summ += p * (Number_Ps_in_N_factorial(n, p) - Number_Ps_in_N_factorial(
            m, p) - Number_Ps_in_N_factorial(n - m, p))

    return summ
예제 #19
0
def main():
    try:
        os.remove('output.txt')
        print('removed output file!')
    except Exception as e:
        print(f'Error: {e}')

    if sys.argv[1] == "--sequence":
        start = time.time()
        processes = []
        video = cv2.VideoCapture('video_sample.mp4')
        w, h = int(video.get(3)), int(video.get(4))

        for i in range(int(sys.argv[4])):
            video.set(cv2.CAP_PROP_POS_FRAMES,
                      time.time() * 1000 % video.get(cv2.CAP_PROP_FRAME_COUNT))
            res, frame = video.read()
            p = multiprocessing.Process(target=worker,
                                        args=(
                                            frame,
                                            w,
                                            h,
                                            int(sys.argv[2]),
                                            int(sys.argv[3]),
                                            int(sys.argv[4]),
                                        ))
            processes.append(p)
            p.start()

        for process in processes:
            process.join()

        end = time.time()
        with open('output.txt') as f:
            print(
                f'{sys.argv[2]} random numbers sequence generated in {end - start}\nentropy: {entropy_handler([int(line.strip()) for line in f if line.strip()], base=2)}'
            )

        f.close()

    elif sys.argv[1] == "--single":
        primes = Primes.Primes()
        rng = RNGutils.RNGutils()
        print("Single mode\n")
        video = cv2.VideoCapture('video_sample.mp4')
        seed = get_seed_from_pixel()
        video.release()
        with open("output.txt", "w+") as file:
            string = f'{rng.single(primes=primes, pixel_seed=seed, rnd_range=int(sys.argv[2]))}\n'
            if "-" not in string:
                file.write(string)
                print(string)

        file.close()
def find_prime_sets(digit_list, current_set, prime_sets, primes):
    '''
    Recursively finds the prime sets.

    digit_list:  The digits to make primes of
    current_set: The set of primes found so far
    prime_sets:  The set of all the pandigital prime_sets found so far
    primes:      A list of primes
    '''
    if len(digit_list) != 9:  # Nine digit lists are composite.  Don't check.
        num = make_num_from_list(digit_list)
        if Primes.isPrime(num):
            current_set.add(num)
            prime_sets.add(frozenset(current_set))

    for ix in range(1,len(digit_list)):
        num = make_num_from_list(digit_list[:ix])
        if Primes.isPrime(num):
            next_set = current_set.copy()
            next_set.add(num)
            find_prime_sets(digit_list[ix:], next_set, prime_sets, primes)
    return
예제 #21
0
def main(): 
	maxN = 0; 
	nums = [1,2,3,4,5,6,7]
	nums.reverse(); 
	print nums
	for perm in itertools.permutations(nums): 
		#print perm
		num = getListNumber(perm)
		#print num
		if(num > maxN and Primes.isPrime(num)): 
			maxN = num
			print maxN
	print maxN
예제 #22
0
 def prepareGrid(self, page):
     exportGrid = ExportGrid()
     try:
         with UnstartedRaceWrapper():
             if self.pageInfo[page][0] == 'Primes':
                 exportGrid = ExportGrid(**Primes.GetGrid())
             else:
                 exportGrid.setResultsOneList(self.pageInfo[page][0],
                                              True,
                                              showLapTimes=False)
     except KeyError:
         return ExportGrid()
     exportGrid.title = u'\n'.join(
         [_('Podium Results'), u'', exportGrid.title])
     return exportGrid
예제 #23
0
 def prepareGrid(self, page):
     showLapTimes = (not Model.race) or getattr(
         Model.race, 'includeLapTimesInPrintout', True)
     try:
         with UnstartedRaceWrapper():
             if self.pageInfo[page][0] == 'Primes':
                 exportGrid = ExportGrid(**Primes.GetGrid())
             else:
                 exportGrid = ExportGrid()
                 exportGrid.setResultsOneList(self.pageInfo[page][0],
                                              True,
                                              showLapTimes=showLapTimes)
     except KeyError:
         return ExportGrid()
     return exportGrid
예제 #24
0
def worker(seed, length, threads, rnd_range):
    primes = Primes.Primes()
    rng = RNGutils.RNGutils()

    with open("output.txt", "a+") as file:
        [
            file.write(f'{number}\n')
            for number in rng.sequence(primes=primes,
                                       pixel_seed=seed,
                                       length=int(length / threads),
                                       rnd_range=rnd_range)
        ]

    file.close()

    return
예제 #25
0
def calc_mobius(n):
    primes = Primes.MakePrimeList(n)
    mu = [1]*(n+1)
    mu[0] = 0
    mu[1] = 1
    for p in primes:
        mu[p] = -1
        i = 2
        while p * i <= n:
            mu[p*i] *= -1
            i += 1
        i = 1
        while p*p*i <= n:
            mu[p*p*i] = 0
            i += 1
    return mu
예제 #26
0
def generate_keys(k):
    p, g1, g2 = Primes.prime_and_generators(k)
    rand = SystemRandom()
    x1 = rand.randint(2, p)
    x2 = rand.randint(2, p)
    y1 = rand.randint(2, p)
    y2 = rand.randint(2, p)
    w = rand.randint(2, p)

    X = (pow(g1, x1, p) * pow(g2, x2, p)) % p
    Y = (pow(g1, y1, p) * pow(g2, y2, p)) % p
    W = pow(g1, w, p)

    private_key = [p, x1, x2, y1, y2, w, k]
    public_key = [p, g1, g2, X, Y, W, k]
    return private_key, public_key
예제 #27
0
def worker(frame, w, h, length, rnd_range, threads):
    primes = Primes.Primes()
    rng = RNGutils.RNGutils()

    with open("output.txt", "a+") as file:
        seed = get_seed_from_pixel(frame=frame, w=w, h=h)
        [
            file.write(f'{number}\n')
            for number in rng.sequence(primes=primes,
                                       pixel_seed=seed,
                                       length=int(length / threads),
                                       rnd_range=rnd_range)
        ]

    file.close()

    return
예제 #28
0
def Euler268(N, M=100):
    primes = Primes.MakePrimeList(M)
    #return f(primes, 4, N)
    added = [0] * (len(primes) + 1)
    ans = 0
    for r in range(4, len(primes) + 1):
        print N, r, ans
        if prod(primes[:r]) > N:
            break
        multiplier = 1 - added[r]
        # Update how many times we have added numbers divisible by
        # exactly x primes in the list.
        for x in range(r, len(primes) + 1):
            added[x] += multiplier * comb(x, r, True)
        # Actually add them
        ans += multiplier * sum(N // prod(c) for c in combinations(primes, r))
    return ans
예제 #29
0
def Euler351(N):
    M = N / 2
    primes = Primes.MakePrimeList(M)
    ans = 0
    r = 1
    while r < len(primes) and prod(primes[:r]) <= M:
        sign = int((-1)**(r + 1))
        count = 0
        for c in combProdLessThan(primes, r, M):
            count += 1
            x = prod(c)
            p = int(N // x)
            q = int(N // (2 * x))
            ans += sign * (p * q - q * (q + 1))
        print '%d from list of len %d: %d times; \ttotal %d' % (r, len(primes),
                                                                count, ans)
        r += 1
    return 6 * (2 * ans + M + N - 2)
예제 #30
0
def Euler122():
    primes = Primes.MakePrimeList(200)
    m = {}
    m[1] = 0
    for x in range(2, 201):
        if x in primes:
            m[x] = m[x - 1] + 1
        else:
            m[x] = 0
            y = x
            for p in primes:
                while y % p == 0 and y > 0:
                    m[x] += m[p]
    ans = 0
    for x in range(1, 201):
        ans += m[x]

    print 'Sum: ', ans
    return ans
예제 #31
0
def lcm(integerlist):
    """
    lcm stands for least common multiple.
    this function calculate the lcm of some integers.
    """
    lcmdict = {}
    for i in integerlist:
        factorslist = Primes.factors(i)
        factorsdict = {}
        for k in factorslist:
            factorsdict.setdefault(k, 0)
            factorsdict[k] += 1
        for afactor in factorsdict:
            lcmdict.setdefault(afactor, 0)
            if lcmdict[afactor] < factorsdict[afactor]:
                lcmdict[afactor] = factorsdict[afactor]
    mylcm = 1
    for afactor in lcmdict:
        mylcm *= afactor ** lcmdict[afactor]
    return mylcm, lcmdict
예제 #32
0
def Euler193(N):
    '''
    Calculates the number of squarefree numbers less than N
    '''
    root = round(sp.sqrt(N))
    primes = Primes.MakePrimeList(root)
    num = 0
    
    n = 1
    min_prod = 2
    #---------------------------------------#
    # Loop over the number of primes to use #
    # in the inclusion-exclusion principle. #
    #---------------------------------------#
    while min_prod <= root:
        #-----------------------------------------#
        # Iterate over all the combinations of n  #
        # primes, adding or subtracting according #
        # to the inclusion-exclusion principle.   #
        #-----------------------------------------#
        ix_list = range(n)
        done = False
        while not done:
            # Calculate the number of square including numbers
            p = sp.product([primes[ix]*primes[ix] for ix in ix_list])
            #print [primes[i] for i in ix_list]
            if n % 2 == 0:
                num -= (N-1) / p
                #print '-'+str(N / p)
            else:
                num += (N-1) / p
                #print '+'+str(N/p)
            done = not ix_combo(ix_list, primes, root)
            
        n += 1
        min_prod = sp.product(primes[:n])
        
    num = N - num - 1
    #print 'Number of squarefree numbers below '+str(N)+': '+str(num)
    return num
def Euler122(N):
    primes = Primes.MakePrimeList(N+2)
    m = {}
    m[1] = 0
    for x in range(2, N+1):
        if x in primes:
            #print x, m[x-1]
            m[x] = m[x-1] + 1
        else:
            m[x] = 0
            y = x+0
            for p in primes:
                while y%p == 0 and y > 0:
                    m[x] += m[p]
                    y /= p
    ans = 0
    for x in range(1, N+1):
        ans += m[x]

    print 'Sum: ', ans
    print m
    return ans
def Euler87(n):
    ps = Primes.MakePrimeList(int(scipy.sqrt(n))*2)
    nF = 0
    nums = []
    count = 0
    while ps[nF]**4 <= n:
        nC = 0
        while ps[nF]**4 + ps[nC]**3 <= n:
            nS = 0
            while ps[nF]**4 + ps[nC]**3 + ps[nS]**2 <= n:
                a = ps[nF]**4 + ps[nC]**3 + ps[nS]**2
                count += 1
                nums.append(a)
                nS += 1
            nC += 1
        nF += 1

    nums.sort()
    for x in range(1,len(nums)):
        if nums[x]==nums[x-1]:
            count -= 1
        
    return count
예제 #35
0
import itertools
import Primes

# awesome.
# 1+2+3+4+5+6+7+8+9=45
# 1+2+3+4+5+6+7+8=36

for aper in itertools.permutations(range(7, 0, -1)):
    candidate = int(''.join([str(x) for x in list(aper)]))
    if Primes.isPrime(candidate):
        print(candidate)
        break
예제 #36
0
#            booltemp = False
#            break
#    if booltemp == True:
#        print(ap)
#        break
for ap in Primes.primes:
    print(ap)
    mylist = [[ap]]
    found = False
    while True:
        templist = []
        for a in mylist:
            for b in Primes.primes[Primes.primes.index(a[-1]) + 1:]:
                booltemp = True
                for i in a:
                    if Primes.isPrime(int(str(i) + str(b))) == False or Primes.isPrime(int(str(b) + str(i))) == False:
                        booltemp = False
                        break
                if booltemp == True:
                    templist.append(a + [b])
        mylist = templist
        if mylist == []:
            break
        print(len(mylist[0]))
        if len(mylist[0]) == 5:
            print(mylist)
            found = True
            break
    if found == True:
        break
예제 #37
0
def getListNumber(listN): 
	num = listN[0]; 
	for part in range(1,len(listN)): 
		num = Pandigital.appendNums(num, listN[part]); 
	return num


def main(): 
	maxN = 0; 
	nums = [1,2,3,4,5,6,7]
	nums.reverse(); 
	print nums
	for perm in itertools.permutations(nums): 
		#print perm
		num = getListNumber(perm)
		#print num
		if(num > maxN and Primes.isPrime(num)): 
			maxN = num
			print maxN
	print maxN


if __name__ == "__main__": 
	if(len(sys.argv) > 1 and sys.argv[1] == "test"): 
		assert True
		print Primes.getPrimes(1000000000)[1000]
		
	else: 
		main()
예제 #38
0
import Primes
print(Primes.factors(600851475143))
예제 #39
0
def find_sum_primes(n):
    #getPrimes gets all primes up to, but not including the passed in value
    #primeslist = Primes.getPrimes(n + 1)
    primeslist = Primes.prime_sieve(n)
    return sum(primeslist)
예제 #40
0
import Primes

n = 1
while True:
    found = True
    if n % 100 == 0:
        print(n)
        print(Primes.factors(n + 1))
    step = 0
    for i in range(n, n + 4):
        tempset = set(Primes.factors(i))
        if len(tempset) != 4:
            found = False
            step = i - n
            break
    if found == True:
        print(n)
        break
    n += step + 1
예제 #41
0
import Primes
Primes.extendTo(2000000)
print(sum([int(line.strip()) for line in open('Primes.txt').readlines()]))