Example #1
0
def isAmicable(n):
    a1 = sum(divisors(n)) - n
    a2 = sum(divisors(a1)) - a1
    if a1 == a2:
        return False
    elif a2 == n:
        return True
    return False
Example #2
0
File: PE_0088.py Project: mbh038/PE
def test2(n):
    start=timer()    
    for a in range(2,n):        
        divisors(n)
    print('a:',a,'Elapsed time:',timer()-start)
    start=timer()
    for a in range(2,n):
        sp.divisors(n)
    print('a:',a,'Elapsed time:',timer()-start)
Example #3
0
def main():
    ''' Driver function '''
    nums = {n for n in range(2, 10000)}
    amicable = []
    while nums:
        num = nums.pop()
        div_sum = sum(divisors(num)[:-1])
        if num == sum(divisors(div_sum)[:-1]) and num != div_sum:
            amicable.append(num)
    print(sum(amicable))
def main():
    summa = 0
    for i in range(1,10000):
        num1 = sum(sp.divisors(i)) - i
        num2 = sum(sp.divisors(num1)) - num1
        
        if(num1 != num2):
            if(num2 == i):
                summa += i
                #print i
    print summa 
Example #5
0
def func21(arg):
    amiCheck = [False] * arg
    amiCheck[0] = amiCheck[1] = True

    for (n, checked) in enumerate(amiCheck):
        if not checked:
            if isAmicable(n):
                yield n
                yield sum(divisors(n)) - n
                amiCheck[int(sum(divisors(n)) - n)] = True
            amiCheck[n] = True
Example #6
0
def satisfiesCondition(x):
    divs = divisors(x)
    for d in divs:
        n = int(d + x / d)
        if (isprime(n) == False):
            return False
    return True
Example #7
0
def pdc(int):
    a = divisors(int)
    c = []
    for b in a:
        if(isprime(b)):
            c.append(b)
    return(len(c))
Example #8
0
    def _getNLayersInC(self, nAtoms, inpCell):
        #1) Get the possible values we can use
        nPrimAtoms = len(self.primCell.cartCoords)
        divisors = sympy.divisors(nAtoms)
        possibleFactors = [
            int(x / nPrimAtoms) for x in divisors if x % nPrimAtoms == 0
        ]

        #2) Get an objective measure of the "goodness" of each value
        objFunctVals = list()
        inpC, primC = inpCell.lattParams["c"], self.primCell.lattParams["c"]
        perfectVal = inpC / primC
        for factor in possibleFactors:
            currVal = abs(perfectVal - factor)
            objFunctVals.append(currVal)

        #3) Choose the value to use (we choose the highest possible which gives a match within a tolerance).
        tolerance = 0.1
        minObjFunct = min(objFunctVals)
        allowedFactors = list()
        for idx, objVal in enumerate(objFunctVals):
            if abs(objVal - minObjFunct) < tolerance:
                allowedFactors.append(possibleFactors[idx])

        return max(allowedFactors)
Example #9
0
def cond(n):
    if not isprime(int(2 + n/2)): return False
    else:
        d = divisors(n)
        for i in range(2,int(len(d)/2)):
            if not isprime(d[i] + int(n/d[i])): return False
    return True
Example #10
0
def nontrivial_divisors(nums):
    divisors = []
    for num in nums:
        div = sympy.divisors(num)
        if len(div) != 2:
            divisors += [div[1]]
    return divisors
Example #11
0
    def _getNumbImagesAB(self, nAtoms, nLayers, inpCell):
        #1) Get the possible combinations of nA,nB
        nPrimCell = len(self.primCell.cartCoords)
        nPerLayer = int(nAtoms / nLayers)
        assert nAtoms % nLayers == 0
        dimProduct = int(nPerLayer / nPrimCell)
        assert nPerLayer % nPrimCell == 0
        factors = sympy.divisors(dimProduct)
        factorPairs = [[int(dimProduct / x), x] for x in factors]

        #2) Get an objective function for how well these cells match the inpCell ab plane
        inpA, inpB = inpCell.lattParams["a"], inpCell.lattParams["b"]
        primA, primB = self.primCell.lattParams["a"], self.primCell.lattParams[
            "b"]
        perfectA, perfectB = inpA / primA, inpB / primB
        objFunctVals = list()
        for factorCombo in factorPairs:
            errorA, errorB = abs(perfectA -
                                 factorCombo[0]), abs(perfectB -
                                                      factorCombo[1])
            currVal = errorA + errorB
            objFunctVals.append(currVal)

        #3) Choose the value to use (we pick the one with highest n_a that gives a decent match within a tolerance)
        tolerance = 0.1
        minObjFunct = min(objFunctVals)
        allowedFactors = list()
        for idx, objVal in enumerate(objFunctVals):
            if abs(objVal - minObjFunct) < tolerance:
                allowedFactors.append(factorPairs[idx])

        return max(allowedFactors, key=lambda x: x[0])
Example #12
0
def abundant(end):
    ''' Return an array of all abundant numbers below 'end' '''
    abundant = np.array([], dtype=int)
    for num in range(1, end + 1):
        if sum(divisors(num)[:-1]) > num:
            abundant = np.append(abundant, num)
    return abundant
Example #13
0
def divisorsum(int):
    a = divisors(int)
    a.pop(len(a) - 1)
    total = 0
    for element in a:
        total += element
    return (total)
Example #14
0
def main():
    total = 0
    for k in range(1, M + 1):
        if k % 10_000 == 0:
            print(f"progress: {k}")
        for d in sympy.divisors(k)[:-1]:
            total += (2 * M - 2 * k + 3 * d + 1) * d // 2
Example #15
0
File: PE_0088.py Project: mbh038/PE
def psnmin(n,primes=[]):
    """returns minimal m=2 sum-product solution for n digits"""
    if len(primes)==0:
        primes=primesfrom2to(n)

#    start=timer() 
    if n==2:
        return 4,2,[2,2]

    m=ndig(n)
    psn=np.inf
#    print (2,psns[2]       
    if n-1 in primes:
        psn=2*n
        solution=[2,n]
        
    if n-1 not in primes:
        abcands=[x+1 for x in sp.divisors(n-1)[1:-1]]
        nf=len(abcands)
        if nf%2==1: 
            abcands=sorted(abcands+[abcands[(nf-1)//2]])                
            nf+=1
        psn=abcands[(nf-1)//2]*abcands[(nf+1)//2]
        solution=[abcands[(nf-1)//2],abcands[(nf+1)//2]]
#        print(psns)
    return psn,2,solution
Example #16
0
def get_divisor(n):
    ds = list(islice(divisors(n, generator=True), 1, 2))
    if not ds:
        return 1
    if ds[0] == n:
        return 1
    return ds[0]
Example #17
0
def proper_divisors(n):
    """The proper factors of n"""
    
    if type(n) != int:
        raise Exception("n must be an integer")
    
    return divisors(n,proper=True)
Example #18
0
 def apply(self, n, evaluation):
     "Divisors[n_Integer]"
     if n == Integer0:
         return None
     return Expression(
         "List", *[from_sympy(i) for i in sympy.divisors(n.to_sympy())]
     )
Example #19
0
def isprime(int):

    if (int == 1):
        return False
    if (len(divisors(int)) == 2):
        return True
    return False
Example #20
0
def divisorsum(int):
    total = 0
    c = divisors(int)
    c.pop(len(c) - 1)
    for a in c:
        total += a
    return total
Example #21
0
def pandigital_divisors(num):
    divisorList = divisors(num)
    for i in range(int(len(divisorList) / 2)):
        temp = [str(divisorList[i]), str(divisorList[-(i + 1)]), str(num)]
        temp = sorted([int(x) for x in ''.join(temp)])
        if (temp == pandigitalList):
            return True
    return False
Example #22
0
def num_sols_gcd(n):
	divs = divisors(n)
	c = 0
	for e, d1 in enumerate(divs):
		for d2 in divs[e:]:
			if are_coprime((d1,d2)):
				c += 1
	return c
Example #23
0
def S(p, m):
    sum = 0
    for k in range(1, p + 1):
        for ds in sympy.divisors(k)[:-1]:
            s = k - ds
            first = m - s + 1
            last = min(m, m - s + ds)
            sum += (last - first + 1) * (first + last) / 2
    return sum
Example #24
0
def sum_d(n):
    divs = sympy.divisors(n)

    sumd = 0

    for i in divs[:-1]:
        sumd += i

    return sumd
def T(n, m):

    if isprime(n): return 1 if n <= m else 0

    A = filter(lambda d: d <= m, divisors(int(n))[1:-1])

    s = sum(T(n / d, d) for d in A)

    return s + 1 if n <= m else s
Example #26
0
def squarest_grid_size(num_images):
    divisors = sympy.divisors(num_images)
    square_root = math.sqrt(num_images)
    width = 1
    for d in divisors:
        if d > square_root:
            break
        width = d
    return (num_images // width, width)
Example #27
0
def isZumkeller(n):
    d = divisors(n)
    s = sum(d)
    if not s % 2 and max(d) <= s / 2:
        for x in range(1, 2 ** len(d)):
            if sum(Subset.unrank_binary(x, d).subset) == s / 2:
                return True

    return False
Example #28
0
def main():
    part_1_solved = False
    for n in count(1):
        divisors = sympy.divisors(n)
        if not part_1_solved and 10 * sum(divisors) >= 36_000_000:
            print("Solution (part 1):", n)
            part_1_solved = True
        if 11 * sum(div for div in divisors if n / div <= 50) >= 36_000_000:
            print("Solution (part 2):", n)
            break
Example #29
0
File: PE_0621.py Project: mbh038/PE
def p621(n):
    
    ds=sp.divisors(8*n+3)
    dsq=[d for d in ds if d**0.5==int(d**0.5)]
   
    delta3=0
    cache={}
    for d in dsq:
        delta3 += R3((8*n+3)//d,cache)
    return delta3//8
Example #30
0
File: PE_0621.py Project: mbh038/PE
def p621(n):

    ds = sp.divisors(8 * n + 3)
    dsq = [d for d in ds if d**0.5 == int(d**0.5)]

    delta3 = 0
    cache = {}
    for d in dsq:
        delta3 += R3((8 * n + 3) // d, cache)
    return delta3 // 8
Example #31
0
def factorsOfNumbers(num1):
    print("\nHere are the factors of your number: ", divisors(num1))
    print("Your number has", divisor_count(num1), "factors within it")
    if divisor_count(num1) == 2:
        print("Your number is a prime number.")
    else:
        print("Your number is a composite number.")
    print()
    print("The prime factors of your number are", primefactors(num1))
    print("A number’s prime factors are the set of prime numbers (including repeats) that equal that number when multiplied together.")
def chercher(N, nb_solutions):
    compteur = 0
    for n in range(1, N):
        if len([
                d for d in divisors(n, generator=True)
                if (d + n // d) % 4 == 0 and (n // d + d) // 4 < d
        ]) == nb_solutions:
            compteur += 1
            print("\r", n, end="")
    return compteur
Example #33
0
 def path_function(path):
     global divs
     # print('path', path)
     trans = make_trans_from_path(cg, path)
     cur_div = len(trans)
     for d in sympy.divisors(len(trans))[::-1]:
         if trans == trans[:int(len(trans) / d)] * d:
             cur_div = d
             break
     if cur_div not in divs and cur_div > 1:
         divs += [cur_div]
Example #34
0
 def get_list_prime_candidates(self):
     for d in sympy.divisors(self.factorial):
         p = d + 1
         if primes.is_prime_opti(p):
             n = self.factorial // d
             exp = 0
             while n % p == 0:
                 n = n // p
                 exp += 1
             self.list_prime_candidates.append((p, exp))
     self.list_prime_candidates.sort()
def primegenerating(n):
    if is_square(n):
        return 0
    for div in divisors(
            n
    ):  #unfortunately a generator does not work, as it does not order the divisors, and we would break out of the loop too soon.
        if div * div > n:
            break
        if not isprime(div + (n // div)):
            return 0
    return n
Example #36
0
def sigma_k(nval, kval=1):
    if nval == 1:
        return 1
    if kval == 1:
        return sigma_1(nval)
    if kval == 0:
        return sigma_0_pow(nval, 1)
    divs = sympy.divisors(nval)
    sigval = 0
    for div in divs:
        sigval += math.pow(div, kval)
    return int(sigval)
Example #37
0
def solve(m):
    count = 1
    for i in range(2, 10**7):
        l = 1
        n = 308*i
        b = sympy.divisors(n)
        for j in b:
            if primes.is_prime_opti(j+1):
                l *= j+1
                if l > 20010:
                    break
        if l == 20010:
            count += 1
            if count == m:
                return n
Example #38
0
def num_sols_gcd(n):
	divs = divisors(n)
	c = 0
	for e, d1 in enumerate(divs):
		for d2 in divs[e:]:
			if are_coprime((d1,d2)):
				c += 1
	return c

# coprimes = set([(1,1)])
# divs = pf_to_divs(PRIME_FACTS[2*2*3*3*5])

# filter(are_coprime, product(divs,divs))


		
def classify(n):
    """
    Classifies a number n as being perfect, decifient, or abundant

    If 0 is returned the number is perfect.

    If 1 is returned the number is deficient.

    If 2 is returned the number is abundant.
    """
    sum_divs = sum(sym.divisors(n)[:-1])
    if sum_divs == n:
        return 0
    elif sum_divs < n:
        return 1
    else:
        return 2
Example #40
0
def classify_aliquot_sum(number):
    """
    Classifies the aliquot sum of the given number.  The aliquot sum is the sum
    of the numbers proper divisors, that is the divisors of the number that are
    less than the number

    Returns:
        0 if the number is perfect i.e. aliquot sum equals number
        1 if the number is abundant i.e. aliquot sum is greater than number
       -1 if the number is deficient i.e. aliquot sum is less than number
    """
    aliquot_sum = sum([i for i in sympy.divisors(number) if i != number])
    if aliquot_sum > number:
        return ABUNDANT
    elif aliquot_sum < number:
        return DEFICIENT
    else:
        return PERFECT
Example #41
0
def sigma_0_nsquared(nval):
    if nval == 1:
        return 1
    if nval in divisors_dict:
        divs = divisors_dict[nval]
    else:
        divs = sympy.divisors(nval)
        divisors_dict[nval] = divs
    sigval = 0
    for div in divs:
        mult = nval // div
        if mult in mobius_dict:
            mob = mobius_dict[mult]
        else:
            mob = int(sympy.mobius(mult))
            mobius_dict[mult] = mob
        sig0 = sigma_0_pow(div, 1)
        sigval += mob * math.pow(sig0, 2)
    return int(sigval)
Example #42
0
File: PE_0088.py Project: mbh038/PE
def test3(nmin,nmax):
    start=timer()

    ps=set()
    nx=0
    hmax=0
    hs=[]
    ns=[]
    sps=[]
    ds=[]
    az=[]
    pz=[]
    for n in range(nmin,nmax+1):
        if n%1000==0:print(n,timer()-start)
        sp,h,a,v,p=ps4(n)
        if a==3:
            print(n,h,a,p,sp,v)
            ns.append(n)
            hs.append(h)
            sps.append(sp)
            az.append(a)
            pz.append(p)
            ds.append(len(sp.divisors(n)))
        if h>hmax:
            hmax=h
            nx=n
        ps.add(sp)

#    plt.plot(ns,sps)
    plt.figure(1)
    plt.subplot(211)
    plt.plot(ns,az)
    
    plt.subplot(212)
    plt.plot(ns,sps)
    plt.show()
    
    print(sum(ps))
    print(nx,hmax)
    
    print (sum([x%10==3 for x in sps]))
Example #43
0
File: PE_0088.py Project: mbh038/PE
def ps4(n):
    okts=[]
    if n in [2, 3, 4, 6, 24, 114, 174, 444]:
        okts.append((n,1,2,2,(2,),2*n))
        return 2*n,1,n,(2),2
    
    
    h=0
#    while len(okts)<=2:
    flag=False
    gmin=np.inf
    while h<=1000:
        h+=1
#        if flag:break            
#        print('n,h',n,h,len(okts))
        d=sp.divisors(n+h-1)
        try:
            az=[(n+h-1)//x for x in d[1:-1]]
            if min(az)>n:break
            ps=[x+1 for x in d[1:-1]]
            if max(ps)<=h:break
#            gs=[(x+1)*(n+h-1)//x for x in d[1:-1]]
            
#            if len(az)==0 and h==3:
#                return 2*n

#            az=[(n+h-1)//x for x in d]
#            ps=[x+1 for x in d]
#            gs=[(x+1)*(n+h-1)//x for x in d]
            
            ts=[(az[x],ps[x]) for x in range(len(az))]
#            print('ts',h,ts)
            for  t in ts:
                a,p=t[0],t[1]
                g=a*p
#                print ('a,p,g',a,p,g)
#                print('rmax',rmax)
                mpp=mp(p)
#                print('mpp',mpp)
                for v in mpp:
                    if max(v)>a:
                        continue
                    s=sum(v)
                    r=s-h
                    if r<1: 
                        flag=True
                        continue
                    if r!=len(v):
                        continue
                    if a+s+n-r-1==a*p and g<=gmin:
                        gmin=g
#                        print(a*p==g)
#                        print('h',h,'s',s,'r',r,'n',n,'a',a,'v',v,'g',g)
                    
                        best=(a,r,s,p,v,g,h)
#                        okts.add((g))
        except:
            pass
#            print('exception')
#        if h>10:
#            break
#    print(okts)
    return best[5],best[6],best[0],best[4],best[3]
Example #44
0
def is_abundant(n):
    return sum(divisors(n)) - n > n
Example #45
0
def get_dividors(num):
	return sympy.divisors(num)
Example #46
0
def is_amicable(n):
    a = sum(divisors(n)) - n
    return a != n and sum(divisors(a)) - a == n
Example #47
0
def properDivisors(n):
    return divisors(n)-set([n])
Example #48
0
def diop_pell(D, N, t=symbols("t", Integer=True)):
    """
    Solves the generalized Pell equation x**2 - D*y**2 = N. Uses LMM algorithm.
    Refer [1] for more details on the algorithm. Returns one solution for each
    class of the solutions. Other solutions can be constructed according to the
    values of D and N. Returns a list containing the solution tuples (x, y).

    Usage
    =====

        diop_pell(D, N, t) -> D and N are integers as in x**2 - D*y**2 = N and t is
        the parameter to be used in the solutions.

    Details
    =======

        ``D`` corresponds to the D in the equation
        ``N`` corresponds to the N in the equation
        ``t`` parameter to be used in the solutions

    Examples
    ========

    >>> from sympy.solvers.diophantine import diop_pell
    >>> diop_pell(13, -4) # Solves equation x**2 - 13*y**2 = -4
    [(3, 1), (393, 109), (36, 10)]

    The output can be interpreted as follows: There are three fundamental
    solutions to the equation x**2 - 13*y**2 = -4  given by (3, 1), (393, 109)
    and (36, 10). Each tuple is in the form (x, y), i. e solution (3, 1) means
    that x = 3 and y = 1.

    >>> diop_pell(986, 1) # Solves equation x**2 - 986*y**2 = 1
    [(49299, 1570)]

    References
    ==========

    ..[1] Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson,
          July 31, 2004, Pages 16 - 17.
          http://www.jpr2718.org/pell.pdf
    """
    if D < 0:
        if N == 0:
            return [(S.Zero, S.Zero)]
        elif N < 0:
            return []
        elif N > 0: # TODO: Solution method should be improved
            sol = []
            for y in range(floor(sqrt(-S(N)/D)) + 1):
                if isinstance(sqrt(N + D*y**2), Integer):
                    sol.append((sqrt(N + D*y**2), y))
            return sol

    elif D == 0:
        if N < 0 or not isinstance(sqrt(N), Integer):
            return []
        if N == 0:
            return [(S.Zero, t)]
        if isinstance(sqrt(N), Integer):
            return [(sqrt(N), t), (-sqrt(N), t)]

    else: # D > 0
        if isinstance(sqrt(D), Integer):
            r = sqrt(D)

            if N == 0:
                return [(r*t, t), (-r*t, t)]
            else:
                sol = []

                for y in range(floor(sign(N)*(N - 1)/(2*r)) + 1):
                    if isinstance(sqrt(D*y**2 + N), Integer):
                        sol.append((sqrt(D*y**2 + N), y))

                return sol
        else:
            if N == 0:
                return [(S.Zero, S.Zero)]

            elif abs(N) == 1:

                pqa = PQa(0, 1, D)
                a_0 = floor(sqrt(D))
                l = 0
                G = []
                B = []

                for i in pqa:

                    a = i[2]
                    G.append(i[5])
                    B.append(i[4])

                    if l != 0 and a == 2*a_0:
                        break
                    l = l + 1

                if l % 2 == 1:

                    if N == -1:
                        x = G[l-1]
                        y = B[l-1]
                    else:
                        count = l
                        while count < 2*l - 1:
                            i = next(pqa)
                            G.append(i[5])
                            B.append(i[4])
                            count = count + 1

                        x = G[count]
                        y = B[count]
                else:
                    if N == 1:
                        x = G[l-1]
                        y = B[l-1]
                    else:
                        return []

                return [(x, y)]

            else:

                fs = []
                sol = []
                div = divisors(N)

                for d in div:
                    if divisible(N, d**2):
                        fs.append(d)

                for f in fs:
                    m = N // f**2
                    zs = []

                    for i in range(floor(S(abs(m))/2) + 1):
                        # TODO: efficient algorithm should be used to
                        # solve z^2 = D (mod m)
                        if (i**2 - D) % abs(m) == 0:
                            zs.append(i)
                            if i < S(abs(m))/2 and i != 0:
                                zs.append(-i)

                    for z in zs:

                        pqa = PQa(z, abs(m), D)
                        l = 0
                        G = []
                        B = []

                        for i in pqa:

                            a = i[2]
                            G.append(i[5])
                            B.append(i[4])

                            if l != 0 and abs(i[1]) == 1:
                                r = G[l-1]
                                s = B[l-1]

                                if r**2 - D*s**2 == m:
                                    sol.append((f*r, f*s))

                                elif diop_pell(D, -1) != []:
                                    a = diop_pell(D, -1)
                                    sol.append((f*(r*a[0][0] + a[0][1]*s*D), f*(r*a[0][1] + s*a[0][0])))

                                break

                            l = l + 1
                            if l == length(z, abs(m), D):
                                break

                return sol
Example #49
0
def diop_quadratic(var, coeff, t):
    """
    Solves quadratic diophantine equations, i.e equations of the form
    Ax**2 + Bxy + Cy**2 + Dx + Ey + F = 0. Returns a set containing
    the tuples (x, y) which contains the solutions.

    Usage
    =====

        diop_quadratic(var, coeff) -> var is a list of variables and
        coeff is a dictionary containing coefficients of the symbols.

    Details
    =======

        ``var`` a list which contains two variables x and y.
        ``coeff`` a dict which generally contains six key value pairs.
        The set of keys is {x**2, y**2, x*y, x, y, Integer(1)}.
        ``t`` the parameter to be used in the solution.

    Examples
    ========

    >>> from sympy.abc import x, y, t
    >>> from sympy import Integer
    >>> from sympy.solvers.diophantine import diop_quadratic
    >>> diop_quadratic([x, y], {x**2: 1, y**2: 1, x*y: 0, x: 2, y: 2, Integer(1): 2}, t)
    set([(-1, -1)])

    References
    ==========

    .. [1] http://www.alpertron.com.ar/METHODS.HTM
    """
    x = var[0]
    y = var[1]

    for term in [x**2, y**2, x*y, x, y, Integer(1)]:
        if term not in coeff.keys():
            coeff[term] = Integer(0)

    A = coeff[x**2]
    B = coeff[x*y]
    C = coeff[y**2]
    D = coeff[x]
    E = coeff[y]
    F = coeff[Integer(1)]

    d = igcd(A, igcd(B, igcd(C, igcd(D, igcd(E, F)))))
    A = A // d
    B = B // d
    C = C // d
    D = D // d
    E = E // d
    F = F // d

    # (1) Linear case: A = B = C = 0 -> considered under linear diophantine equations

    # (2) Simple-Hyperbolic case:A = C = 0, B != 0
    # In this case equation can be converted to (Bx + E)(By + D) = DE - BF
    # We consider two cases; DE - BF = 0 and DE - BF != 0
    # More details, http://www.alpertron.com.ar/METHODS.HTM#SHyperb

    l = set([])

    if A == 0 and C == 0 and B != 0:

        if D*E - B*F == 0:
            if divisible(int(E), int(B)):
                l.add((-E/B, t))
            if divisible(int(D), int(B)):
                l.add((t, -D/B))

        else:
            div = divisors(D*E - B*F)
            div = div + [-term for term in div]

            for d in div:
                if divisible(int(d - E), int(B)):
                    x0  = (d - E) // B
                    if divisible(int(D*E - B*F), int(d)):
                        if divisible(int((D*E - B*F)// d - D), int(B)):
                            y0 = ((D*E - B*F) // d - D) // B
                            l.add((x0, y0))

    # (3) Elliptical case: B**2 - 4AC < 0
    # More Details, http://www.alpertron.com.ar/METHODS.HTM#Ellipse
    # In this case x should lie between the roots of
    # (B**2 - 4AC)x**2 + 2(BE - 2CD)x + (E**2 - 4CF) = 0

    elif B**2 - 4*A*C < 0:

        z = symbols("z", real=True)
        roots = solve((B**2 - 4*A*C)*z**2 + 2*(B*E - 2*C*D)*z + E**2 - 4*C*F)

        solve_y = lambda x, e: (-(B*x + E) + e*sqrt((B*x + E)**2 - 4*C*(A*x**2 + D*x + F)))/(2*C)

        if len(roots) == 1 and isinstance(roots[0], Integer):
            x_vals = [roots[0]]
        elif len(roots) == 2:
            x_vals = [i for i in range(ceiling(min(roots)), ceiling(max(roots)))] # ceiling = floor +/- 1
        else:
            x_vals = []

        for x0 in x_vals:
            if isinstance(sqrt((B*x0 + E)**2 - 4*C*(A*x0**2 + D*x0 + F)), Integer):
                if isinstance(solve_y(x0, 1), Integer):
                    l.add((Integer(x0), solve_y(x0, 1)))
                if isinstance(solve_y(x0, -1), Integer):
                    l.add((Integer(x0), solve_y(x0, -1)))

    # (4) Parabolic case: B**2 - 4*A*C = 0
    # There are two subcases to be considered in this case.
    # sqrt(c)D - sqrt(a)E = 0 and sqrt(c)D - sqrt(a)E != 0
    # More Details, http://www.alpertron.com.ar/METHODS.HTM#Parabol

    elif B**2 - 4*A*C == 0:

        g = igcd(A, C)
        g = abs(g) * sign(A)
        a = A // g
        b = B // g
        c = C // g
        e = sign(B/A)


        if e*sqrt(c)*D - sqrt(a)*E == 0:
            z = symbols("z", real=True)
            roots = solve(sqrt(a)*g*z**2 + D*z + sqrt(a)*F)

            for root in roots:
                if isinstance(root, Integer):
                    l.add((diop_solve(sqrt(a)*x + e*sqrt(c)*y - root)[x], diop_solve(sqrt(a)*x + e*sqrt(c)*y - root)[y]))

        elif isinstance(e*sqrt(c)*D - sqrt(a)*E, Integer):
            solve_x = lambda u: e*sqrt(c)*g*(sqrt(a)*E - e*sqrt(c)*D)*t**2 - (E + 2*e*sqrt(c)*g*u)*t\
                - (e*sqrt(c)*g*u**2 + E*u + e*sqrt(c)*F) // (e*sqrt(c)*D - sqrt(a)*E)

            solve_y = lambda u: sqrt(a)*g*(e*sqrt(c)*D - sqrt(a)*E)*t**2 + (D + 2*sqrt(a)*g*u)*t \
                + (sqrt(a)*g*u**2 + D*u + sqrt(a)*F) // (e*sqrt(c)*D - sqrt(a)*E)

            for z0 in range(0, abs(e*sqrt(c)*D - sqrt(a)*E)):
                if divisible(sqrt(a)*g*z0**2 + D*z0 + sqrt(a)*F, e*sqrt(c)*D - sqrt(a)*E):
                    l.add((solve_x(z0), solve_y(z0)))

    # (5) B**2 - 4*A*C > 0

    elif B**2 - 4*A*C > 0:
        # Method used when B**2 - 4*A*C is a square, is descibed in p. 6 of the below paper
        # by John P. Robertson.
        # http://www.jpr2718.org/ax2p.pdf

        if isinstance(sqrt(B**2 - 4*A*C), Integer):
            if A != 0:
                r = sqrt(B**2 - 4*A*C)
                u, v = symbols("u, v", integer=True)
                eq = simplify(4*A*r*u*v + 4*A*D*(B*v + r*u + r*v - B*u) + 2*A*4*A*E*(u - v) + 4*A*r*4*A*F)

                sol = diop_solve(eq, t)
                sol = list(sol)

                for solution in sol:
                    s0 = solution[0]
                    t0 = solution[1]

                    x_0 = S(B*t0 + r*s0 + r*t0 - B*s0)/(4*A*r)
                    y_0 = S(s0 - t0)/(2*r)

                    if isinstance(s0, Symbol) or isinstance(t0, Symbol):
                        if check_param(x_0, y_0, 4*A*r, t) != (None, None):
                            l.add((check_param(x_0, y_0, 4*A*r, t)[0], check_param(x_0, y_0, 4*A*r, t)[1]))

                    elif divisible(B*t0 + r*s0 + r*t0 - B*s0, 4*A*r):
                        if divisible(s0 - t0, 2*r):
                            if is_solution_quad(var, coeff, x_0, y_0):
                                l.add((x_0, y_0))
            else:
                var[0], var[1] = var[1], var[0] # Interchange x and y
                s = diop_quadratic(var, coeff, t)

                while len(s) > 0:
                    sol = s.pop()
                    l.add((sol[1], sol[0]))

        else:
            # In this case equation can be transformed into a Pell equation
            A, B = _transformation_to_pell(var, coeff)
            D, N = _find_DN(var, coeff)
            solns_pell = diop_pell(D, N)

            n = symbols("n", integer=True)

            a = diop_pell(D, 1)
            T = a[0][0]
            U = a[0][1]

            if (isinstance(A[0], Integer) and isinstance(A[1], Integer) and isinstance(A[2], Integer)
                and isinstance(A[3], Integer) and isinstance(B[0], Integer) and isinstance(B[1], Integer)):
                for sol in solns_pell:

                    r = sol[0]
                    s = sol[1]
                    x_n = S((r + s*sqrt(D))*(T + U*sqrt(D))**n + (r - s*sqrt(D))*(T - U*sqrt(D))**n)/2
                    y_n = S((r + s*sqrt(D))*(T + U*sqrt(D))**n - (r - s*sqrt(D))*(T - U*sqrt(D))**n)/(2*sqrt(D))

                    x_n, y_n = (A*Matrix([x_n, y_n]) + B)[0], (A*Matrix([x_n, y_n]) + B)[1]

                    l.add((x_n, y_n))

            else:
                L = ilcm(S(A[0]).q, ilcm(S(A[1]).q, ilcm(S(A[2]).q, ilcm(S(A[3]).q, ilcm(S(B[0]).q, S(B[1]).q)))))

                k = 0
                done = False
                T_k = T
                U_k = U

                while not done:
                    k = k + 1
                    if (T_k - 1) % L == 0 and U_k % L == 0:
                        done = True
                    T_k, U_k = T_k*T + D*U_k*U, T_k*U + U_k*T

                for soln in solns_pell:
                    x_0 = soln[0]
                    y_0 = soln[1]

                    x_i = x_0
                    y_i = y_0

                    for i in range(k):

                        X = (A*Matrix([x_i, y_i]) + B)[0]
                        Y = (A*Matrix([x_i, y_i]) + B)[1]

                        if isinstance(X, Integer) and isinstance(Y, Integer):
                            if is_solution_quad(var, coeff, X, Y):
                                x_n = S( (x_i + sqrt(D)*y_i)*(T + sqrt(D)*U)**(n*L) + (x_i - sqrt(D)*y_i)*(T - sqrt(D)*U)**(n*L) )/ 2
                                y_n = S( (x_i + sqrt(D)*y_i)*(T + sqrt(D)*U)**(n*L) - (x_i - sqrt(D)*y_i)*(T - sqrt(D)*U)**(n*L) )/ (2*sqrt(D))

                                x_n, y_n = (A*Matrix([x_n, y_n]) + B)[0], (A*Matrix([x_n, y_n]) + B)[1]
                                l.add((x_n, y_n))

                        x_i = x_i*T + D*U*y_i
                        y_i = x_i*U + y_i*T

    return l
Example #50
0
File: PE_0621.py Project: mbh038/PE
def dsq(n):
    ds=sp.divisors(n)
    return sorted([d for d in ds if d**0.5==int(d**0.5)])
Example #51
0
def prime_factors(n):
    assert(n > 0)
    if n == 1:
        return [1]
    else:
        return [ i for i in divisors(n) if isprime(i) ]
def d(n):
    """
    Implementation of the d(n) function in the problem description
    """
    return sum(sym.divisors(n)[:-1])
Example #53
0
 def apply(self, n, evaluation):
     'Divisors[n_Integer]'
     if n == Integer(0):
         return None
     return Expression('List', *[from_sympy(i) for i in sympy.divisors(n.to_sympy())])
Example #54
0
#!/usr/bin/python

import sympy

ans = set([])

for p in xrange(10**5):
	divs = sympy.divisors(p*p+1)
	for i in divs:
		if i>p:
			break
		ans.add(2*p*p*p+p*p*((p*p+1)/i+i)+p)
		
print sorted(ans)[150000-1]
Example #55
0
 def calculate_house_sympy(self, house):
     return sum(divisors(house))*10
Example #56
0
 def calculate_house_sympy_fifty(self, house):
     d = [self.count_elf(i) for i in divisors(house)]
     return sum(d)*11
Example #57
0
def sum_proper_divisors(number):
    """
    Returns the sum of the proper divisors of the given number.
    Proper divisors are those divisors less than the given number.
    """
    return sum([i for i in sympy.divisors(number) if i < number])
Example #58
0
def num_sols_gcd(n):
	divs = divisors(n)
	c = 0
	return len(filter(are_coprime,combinations_with_replacement(divs,2)))
Example #59
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sympy
expr1 = sympy.factorint(1234567890, visual=True) # 素因数
sympy.pprint(expr1)
expr1 = sympy.divisors(1234567890) # 約数
sympy.pprint(expr1)
expr1 = sympy.divisor_count(1234567890) # 約数の個数
sympy.pprint(expr1)

Example #60
0
import os
os.system('clear')

from sympy import divisors, divisor_count

for n in range(90529000,90529999,2):
   divs = divisors(n)
   a = (2**(n-1))-1
   for x in divs.pop(0):
      d = divmod(a,x)
      if d[1] == 0:
         print(n,'-->',x)