Exemple #1
0
def main():
	primes.init(10**6)
	sums = [0]*(10**6+1)
	for x in range(1,10**6):
		primes.factor(x)
		print x
	print x
Exemple #2
0
def func(num):
    fracs = num - 1
    for x in range(2, num):
        for y in range(x + 1, num + 1):
            if y % x:
                if not set(factor(y)) & set(factor(x)):
                    fracs += 1
    return fracs
Exemple #3
0
def collapseNumIntoFactorPowers(number):
    factors = primes.factor(number)
    powerDict = dict()
    for f in factors:
        try:
            powerDict[f] += 1
        except KeyError:
            powerDict[f] = 1
    return tuple(sorted(powerDict.values()))[::-1]
Exemple #4
0
def find_consecutive_n_factor_integers(goal):
    n = 1
    in_a_row = 0
    while in_a_row < goal:
        factors = factor(n)
        if len(factors) == goal:
            in_a_row += 1
        else:
            in_a_row = 0
        n += 1
    return n - goal
Exemple #5
0
def find_consecutive_n_factor_integers(goal):
    n = 1
    in_a_row = 0
    while in_a_row < goal:
        factors = factor(n)
        if len(factors) == goal:
            in_a_row += 1
        else:
            in_a_row = 0
        n += 1
    return n - goal
Exemple #6
0
def smallest_k(n,min=0):
	if gcd(n,10) != 1:
		return None
	if gcd(n-9,n) != 1:
		return None
#		return handle_zero_divisors(n)
	factors = primes.all_factors(primes.factor(primes.euler_phi(n)))
	if factors[-1] < min:
		return None
	for factor in factors:
		factor = int(factor)
		if pow(10,factor,n) == 1:
			if factor < min:
				return None
			return factor
Exemple #7
0
def handle_zero_divisors(n):
	print "Zero divisors",
	factors = primes.all_factors(primes.factor(primes.euler_phi(n)))
	possibilities = PriorityQueue()
	for factor in factors:
		factor = int(factor)
		if pow(10,factor,n) == 1:
			possibilities.put((factor,factor,1))
	if possibilities.empty():
		return None
	while True: #should eventually terminate
		_,factor,multiple = possibilities.get()
		if pow(100,factor,n) == 1:
			print n,factor*multiple
			return factor*multiple
		possibilities.put((factor*(multiple*1),factor,multiple+1))
Exemple #8
0
def gendivs(divs, n): # 3*n^2
    c = factor(divs, n)
    c = c+c
    c[3] += 1
    f = list(c.items())
    c, go, m = [0]*len(f), True, 1
    while go:
        yield m
        go = False
        for i,(fact,num) in enumerate(f):
            if c[i] < num:
                c[i] += 1
                m *= fact
                go = True
                break
            m //= fact**num
            c[i] = 0
Exemple #9
0
def recurse(n,num,denom, result=[]):
    if num * 2 == denom:
        print int(denom**.5), factor(int(denom**.5)), n-1
        print '\t\t', result
        used.update(set(result))
        return 1
    elif num*2 > denom or n > MAX_SIZE or num*1./denom + partial_sums[n] < .4999999:
        return 0
    while n in numToExclude:
        n+=1
    if n > MAX_SIZE:
        return 0


    if denom % n**2 == 0:
        b = recurse(n+1, num+denom/n**2, denom, result + [n])
    else:
        b = recurse(n+1, num*n**2+denom, denom*n**2, result + [n])

    a = recurse(n+1,num,denom, result)

    return a+b
Exemple #10
0
size = 10**6
if len(sys.argv) > 1:
    size = int(sys.argv[1])


lst = bitarray('0' * (size+1))

count = 0

for i in xrange(2,size+1):
    if i%10240 == 0:
        print i
    if lst[i] == 0:
        if not mr(2*i*i - 1):
            if i < size//500:
                a = set(factor(2*i**2-1)[:-1])
                for j in a:
                    for k in xrange((-i)%j+j,size+1,j):
                        lst[k] = 1
                    for k in xrange(i,size+1,j):
                        lst[k] = 1
            count +=1
    else:
        count +=1

print size -1 - count
print "Time Taken:", time.time() - start


"""
~/Desktop/python_projects/proj_euler $python prob216.py 1000000
Exemple #11
0
import time
from primes import gcd, m_r, factor
START = time.time()
SIZE  = 100

sumz = 0
for i in xrange(1,SIZE+1):
  factors = factor(i+1) + factor(i**2 - i + 1)
  biggestFactor = sorted(factors)[-1]
  print i, biggestFactor
  sumz += biggestFactor - 1

print "Answer:", sumz
print "Time Taken:", time.time() - START


"""
Congratulations, the answer you gave to problem 343 is correct.

You are the 930th person to have solved this problem.

Answer: 269533451410884183
Time Taken: 1570.37111306

Turns out that the 1/k fraction transforms into the (largest prime factor of k+1) - 1, so 1/6 -> 6, and 
  9 -> largestFactor(9+1) = 5 -> 4

"""
Exemple #12
0
start = time.time()
from math import *
fa = factorial
from primes import factor

size = 20


def log10(n):
    return log(n) / log(10)


total = sum([log(n) for n in range(2, size + 1)])
total = int(1000 * total + .5) / 1000.

vals = [int(1000 * log(n) + .5) / 1000. for n in factor(fa(size))[:-1]]

print total
print vals, sum(vals)

goal_val = total / 3.
prev_seen = {}


def helper(n, pos):
    if (n, pos) in prev_seen:
        return prev_seen[(n, pos)]
    #base case
    if pos >= len(vals) or n >= goal_val:
        return n
Exemple #13
0
for m in xrange(2,TEST_SIZE):
  for n in xrange(1,m):
    if 2 * m * n > MAX_TRI_SIZE:
       break
    if gcd(m,n) != 1:
      continue
    for k in xrange(1,TEST_MULT_SIZE):
      if (m**2 - n**2) * k > MAX_TRI_SIZE or \
          2 * m * n * k > MAX_TRI_SIZE:
           break
      tripletSum = 2*m*k*(m+n)
      insertOrIncrement(2*m*n*k)

for key in catDict.keys():
  if catDict[key] >= MIN_LIM:
    print key, catDict[key], factor(key)
print max(catDict.values())
print "Time Taken:", time.time() - START

"""
Suppose that the number b is even. Why does that guarantee a solution for:
    b = k_2 x (m_2^2 - n_2^2)
  if a solution for:
    b = 2mnk
        m_1 > n_1
  exists?

  2mnk:
    m = (m_2^2-n_2^2)
    n = 1
    k = k_2/2
Exemple #14
0
#!/usr/bin/env python
import primes
import sys

#The numerical argument which we should be factoring should
#is the first command line argument:
inputNum = None;
try:
    rawArgument = sys.argv[1];
    inputNum = int(rawArgument);
except (IndexError, ValueError):
    print "You must provide an integer argument for this script to factorize!";
    sys.exit(1);

if inputNum is None:
    print "There was an error parsing the input. Exiting...";
    sys.exit(1);

if inputNum < 2:
    print "Enter a integer argument that is larger than 2";
    sys.exit(1);

listOfFactors = primes.factor(inputNum);
print listOfFactors;
Exemple #15
0
#!/usr/bin/env python
import primes
import sys

#The numerical argument which we should be factoring should
#is the first command line argument:
inputNum = None
try:
    rawArgument = sys.argv[1]
    inputNum = int(rawArgument)
except (IndexError, ValueError):
    print "You must provide an integer argument for this script to factorize!"
    sys.exit(1)

if inputNum is None:
    print "There was an error parsing the input. Exiting..."
    sys.exit(1)

if inputNum < 2:
    print "Enter a integer argument that is larger than 2"
    sys.exit(1)

listOfFactors = primes.factor(inputNum)
print listOfFactors
Exemple #16
0
import time
from primes import divisors, factor, pfactor_gen
START = time.time()
SIZE = 10**6

factors = pfactor_gen(SIZE)

for i in xrange(2, SIZE, 2):
    if sum(divisors(i)) % i == i / 2:
        print i, factor(i)

print "Time Taken:", time.time() - START
"""
2: 1,3,7,15,31,65,129
3: 1,4,10,40,121,364
5: 1,6,31,156,781,3906

p(2)    = 3/2 -> 1 1/2
p(24)   = (13 * 4)/8 = 6 1/2
p(4320) = (63 * 40 * 6) = 3 1/2
        -> 2^4 * 3^3 * 5 * 7
  4320  = 2^5 * 3^3 * 5



2 [2]
24 [2, 2, 2, 3]
4320 [2, 2, 2, 2, 2, 3, 3, 3, 5]
4680 [2, 2, 2, 3, 3, 5, 13]
26208 [2, 2, 2, 2, 2, 3, 3, 7, 13]
Exemple #17
0
import time
start = time.time()
from math import *
fa = factorial
from primes import factor

size = 20

def log10(n):
    return log(n)/log(10)

total = sum([log(n) for n in range(2,size+1)])
total = int(1000*total+.5)/1000.

vals = [int(1000*log(n)+.5)/1000. for n in factor(fa(size))[:-1]]


print total
print vals, sum(vals)

goal_val = total/3.
prev_seen = {}

def helper(n,pos):
    if (n,pos) in prev_seen:
        return prev_seen[(n,pos)]
    #base case
    if pos >= len(vals) or n >= goal_val:
        return n
        
    a = abs(goal_val - helper(n+vals[pos],pos+1))
Exemple #18
0
import primes, sys

print primes.factor(int(sys.argv[1]))
Exemple #19
0
def factorAndAddToDict(num, valueDict):
  factors = factor(num)
  for num in factors:
    valueDict[num] += 1
Exemple #20
0
            l[i] += 1
        for i in xrange(1, length):
            if l[i] > 10 - length + i:
                l[i] = l[i-1] + 1
        yield l * 1

answers = set([])

unique_ascending_lists = lister(4)
for unique_ascending_list in unique_ascending_lists:
    unique_lists = permutations(unique_ascending_list)
    for unique_list in unique_lists:
        number = digits.collapse(unique_list)
        ps = set(unique_list)
#        print "number: %s" % number
        factors = primes.factor(number)
#        print "factors: %s" % factors
        factorpairs = divisions(factors)
#        print unique_list
        for pair in factorpairs:
#            print "  %s" % (pair,)
            multiplicand = functools.reduce(operator.mul, pair[0], 1)
            m1s = set(digits.get_all(multiplicand))
            multiplier = functools.reduce(operator.mul, pair[1], 1)
            m2s = set(digits.get_all(multiplier))
            if len(m1s) + len(m2s) == 5 and m1s | m2s | ps == set([1,2,3,4,5,6,7,8,9]):
                answers.add((multiplicand, multiplier, number))

pprint(answers)
print sum(set(eq[2] for eq in answers))
Exemple #21
0
#NOTE TODO need to solve it

import time
START = time.time()
from primes import factor


factorsDict = { \
    2 : 9, \
    3 : 5, \
    7 : 1, \
    11: 1 }

factors = []
for f in factorsDict.keys():
    factors += [f] * factorsDict[f]

divisors = {2}
for f in factors:
    divisors = set([x * f for x in divisors] + list(divisors))

print len(divisors)
for d in divisors:
    if d % 100 == 12:
        print d, factor(d)

print "Time taken:", time.time() - START
Exemple #22
0
def factorAndAddToDict(num, valueDict):
  factors = factor(num)
  for num in factors:
    valueDict[num] += 1
Exemple #23
0
# 303963552391 #

import numpy as np
import primes

primes.import_primes()
set_size = 0

for d in range(2, 1000001):
    if d % 10000 == 0:
        print(d)

    factors = primes.factor(d)
    coprimes_per_cycle = 1
    for factor in factors:
        coprimes_per_cycle *= factor - 1
    set_size += d * coprimes_per_cycle / np.prod(factors)

print(set_size)
Exemple #24
0
import primes

factors = primes.factor(600851475143)

print max(factors)
Exemple #25
0
#NOTE TODO need to solve it
import time
START = time.time()
from math import *
fa = factorial
from primes import factor


def sum10(abc):
    sumz = 10 ** (abc[0] / log_err)
    sumz += 10 ** (abc[1] / log_err)
    return sumz + 10 ** (abc[2] / log_err)

size = fa(20) #2 * 3 * 5 * 7 * 11
log_err = 1000.
vals = factor(size)[:-1]

vals = [int(log_err * log(val,10)) for val in vals]
total = sum(vals)
prev = {}
min_val = [10 ** 20]


def helper(a, b, c, pos):

    if sum10((a, b, c)) > min_val[0]:
        return (float('inf'), float('inf'), float('inf'))

    #end of array
    if pos == len(vals):
        if sum10((a, b, c)) < min_val[0]:
Exemple #26
0
import time
START = time.time()
from math import *
fa = factorial
from primes import factor


def sum10(abc):
    sumz = 10**(abc[0] / log_err)
    sumz += 10**(abc[1] / log_err)
    return sumz + 10**(abc[2] / log_err)


size = fa(20)  #2 * 3 * 5 * 7 * 11
log_err = 1000.
vals = factor(size)[:-1]

vals = [int(log_err * log(val, 10)) for val in vals]
total = sum(vals)
prev = {}
min_val = [10**20]


def helper(a, b, c, pos):

    if sum10((a, b, c)) > min_val[0]:
        return (float('inf'), float('inf'), float('inf'))

    #end of array
    if pos == len(vals):
        if sum10((a, b, c)) < min_val[0]:
Exemple #27
0
    return prod


  ###### Attempting to short cut out of any solutions that aren't optimal... =/...
    prod2 = prod
    for i in prime_lst[pos:] :
        prod2 *= i
    if prod2*1.0 / lim < ratio:
        return -1


  no_add = recurse(prod,pos+1, prime_lst, lim, ratio)
  added =  recurse(prod * prime_lst[pos], pos+1,prime_lst, lim, ratio)

  val_no_add, val_add = lim - no_add, lim - added
  if val_no_add < val_add:
    return no_add
  return added

ratio = .5
for iteration in xrange(1,len(PROD_LIM)):
  ans = recurse(1,0, prime_list[:iteration],PROD_LIM[iteration], ratio)
  print "The optimal answer is:", PROD_LIM[iteration], prime_list[iteration-1], iteration
  print "The answer is:", ans, factor(ans)
  print "The new ratio is:", ratio
  print "Time now is:", time.time() - START, '\n'
  ratio = ans*1.0/PROD_LIM[iteration]


print "Time Taken:", time.time() - start
Exemple #28
0
        part_removed = sum_sq(start / 2, end / 2) * 8
        return initial_sum - part_removed - P(f, 1)
    return (f + ((f + 1) % 2) + r - 2)**2 - P(
        f, r - 1)  # was lazy only wanted to compute on case.


""" These are the test cases to make sure I was getting the expected result:"""
print "P(1,1) is:", P(1, 1) == 1
print "P(1,2) is:", P(1, 2) == 3
print "P(2,1) is:", P(2, 1) == 2
print "P(10,20) is:", P(10, 20) == 440
print "P(25,75) is:", P(25, 75) == 4863
print "P(99,100) is:", P(99, 100) == 19454

large_num = 71328803586048  #Given input number, not something I made up.
factors = factor(large_num)

print "factorized 71328803586048", factors

vals = {2: 0, 3: 0, 1: 0}
for i in factors:
    vals[i] += 1
print vals

sumz = 0
for i in xrange(vals[2] + 1):
    for j in xrange(vals[3] + 1):
        n = 2**i * 3**j
        m = large_num / n
        sumz += P(n, m)
Exemple #29
0
#NOTE TODO need to solve it

import time
START = time.time()
from primes import factor


factorsDict = { \
    2 : 9, \
    3 : 5, \
    7 : 1, \
    11: 1 }

factors = []
for f in factorsDict.keys():
  factors += [f] * factorsDict[f]

divisors = {2}
for f in factors:
  divisors = set( [x * f for x in divisors] + list(divisors))

print len(divisors)
for d in divisors:
  if d % 100 == 12:
    print d, factor(d)

print "Time taken:", time.time() - START
Exemple #30
0
644 = 2^2 x 7 x 23
645 = 3 x 5 x 43
646 = 2 x 17 x 19.

Find the first four consecutive integers to have four distinct primes factors.
What is the first of these numbers?
"""

from primes import factor


def find_consecutive_n_factor_integers(goal):
    n = 1
    in_a_row = 0
    while in_a_row < goal:
        factors = factor(n)
        if len(factors) == goal:
            in_a_row += 1
        else:
            in_a_row = 0
        n += 1
    return n - goal


if __name__ == '__main__':
    goal = 4
    n = find_consecutive_n_factor_integers(goal)
    print 'Number\tFactors'
    for offset in range(0, goal):
        print "%d\t%s" % (n + offset, str(factor(n + offset)))
Exemple #31
0
        if gainsDict[otherNum][1] == n:
            merged.add(n**gainsDict[n][2] * otherNum**gainsDict[otherNum][2])
            unusedNum.remove(n)
            unusedNum.remove(otherNum)

errors = True
while errors:
    errors = False
    for m1 in sorted(merged):
        if m1 not in merged:
            continue
        for m2 in sorted(merged):
            if m2 not in merged or m1 not in merged:
                continue

            f1 = factor(m1)
            f2 = factor(m2)
            m11, m12 = f1[0], f1[-1]
            m21, m22 = f2[0], f2[-1]
            m21Pow = int(math.log(SIZE * 1.0 / m12, m21))
            m11Pow = int(math.log(SIZE * 1.0 / m22, m11))

            if m1 + m2 < m11**m11Pow * m22 + m21**m21Pow * m12:
                errors = True
                merged.remove(m1)
                merged.remove(m2)
                merged.add(m11**m11Pow * m22)
                merged.add(m21**m21Pow * m12)
                print "Fixed:", m1, m2, m11, m12, m21, m22

print sum(forSureNum) + sum(merged)
Exemple #32
0
import time
from primes import gcd, m_r, factor
START = time.time()
SIZE = 100

sumz = 0
for i in xrange(1, SIZE + 1):
    factors = factor(i + 1) + factor(i**2 - i + 1)
    biggestFactor = sorted(factors)[-1]
    print i, biggestFactor
    sumz += biggestFactor - 1

print "Answer:", sumz
print "Time Taken:", time.time() - START
"""
Congratulations, the answer you gave to problem 343 is correct.

You are the 930th person to have solved this problem.

Answer: 269533451410884183
Time Taken: 1570.37111306

Turns out that the 1/k fraction transforms into the (largest prime factor of k+1) - 1, so 1/6 -> 6, and 
  9 -> largestFactor(9+1) = 5 -> 4

"""
Exemple #33
0
def totient(n):
    fx = set(factor(n))
    for x in fx:
        n *= (1 - 1.0 / x)
    return int(n)
Exemple #34
0
import primes

primes.init(10**4)
for x in range(2,10**4):
	primes.factor(x)
Exemple #35
0
The first three consecutive numbers to have three distinct prime factors are:

644 = 2^2 x 7 x 23
645 = 3 x 5 x 43
646 = 2 x 17 x 19.

Find the first four consecutive integers to have four distinct primes factors.
What is the first of these numbers?
"""

from primes import factor

def find_consecutive_n_factor_integers(goal):
    n = 1
    in_a_row = 0
    while in_a_row < goal:
        factors = factor(n)
        if len(factors) == goal:
            in_a_row += 1
        else:
            in_a_row = 0
        n += 1
    return n - goal

if __name__ == '__main__':
    goal = 4
    n = find_consecutive_n_factor_integers(goal)
    print 'Number\tFactors'
    for offset in range(0, goal):
        print "%d\t%s" % (n+offset, str(factor(n+offset)))
Exemple #36
0
def get_divisors(factors):
    factors = filter(lambda x: x > 1, factors)
    divisors = set([1])
    for f in factors:
        divisors = divisors.union(set([x * f for x in divisors]))
    return sorted(divisors)


count = 0

for a in xrange(2, SIZE / 3):
    if math.sqrt(2 * a**2 + 1) + 2 * a > SIZE:
        break

    div = get_divisors(factor(a**2 + 1))

    # a+b+c = a + (a^2 - 1)/k, which has to be less than the lim
    # also, c - b < a
    kLowerLim = (a**2 + 1) / (SIZE - a)
    div = filter(lambda k: k < a and k > kLowerLim, div)

    # b = (a^2 - k^2 - 1)/2k. We need to make sure b is an int
    # tangent: c = (a^2 + k^2 - 1)/2k. If b is an int, then so is c
    div = filter(lambda k: (a + k) % 2 == 1, div)
    div = filter(lambda k: \
         (a % 2 == 0) or \
         ((a**2 + 1) % (2*k) == 0) \
        , div)

    # make sure that a <= b
Exemple #37
0
import time
from primes import divisors, factor, pfactor_gen
START = time.time()
SIZE  = 10**6

factors = pfactor_gen(SIZE)

for i in xrange(2,SIZE,2):
  if sum(divisors(i)) % i == i/2:
    print i, factor(i)

print "Time Taken:", time.time() - START


"""
2: 1,3,7,15,31,65,129
3: 1,4,10,40,121,364
5: 1,6,31,156,781,3906

p(2)    = 3/2 -> 1 1/2
p(24)   = (13 * 4)/8 = 6 1/2
p(4320) = (63 * 40 * 6) = 3 1/2
        -> 2^4 * 3^3 * 5 * 7
  4320  = 2^5 * 3^3 * 5



2 [2]
24 [2, 2, 2, 3]
4320 [2, 2, 2, 2, 2, 3, 3, 3, 5]
4680 [2, 2, 2, 3, 3, 5, 13]
Exemple #38
0
    if gainsDict[otherNum][1] == n:
      merged.add( n**gainsDict[n][2] * otherNum ** gainsDict[otherNum][2])
      unusedNum.remove(n)
      unusedNum.remove(otherNum)

errors = True
while errors:
  errors = False
  for m1 in sorted(merged):
    if m1 not in merged:
      continue
    for m2 in sorted(merged):
      if m2 not in merged or m1 not in merged:
        continue

      f1 = factor(m1)
      f2 = factor(m2)
      m11, m12 = f1[0], f1[-1]
      m21, m22 = f2[0], f2[-1]
      m21Pow =  int(math.log(SIZE*1.0/m12, m21))
      m11Pow =  int(math.log(SIZE*1.0/m22, m11))
  
      if m1 + m2 < m11**m11Pow * m22 + m21 ** m21Pow * m12:
        errors = True
        merged.remove(m1)
        merged.remove(m2)
        merged.add(m11**m11Pow * m22)
        merged.add(m21**m21Pow * m12)
        print "Fixed:", m1, m2, m11, m12, m21, m22