Beispiel #1
0
    def __init__(self, difficulty):

        if difficulty not in [1, 2, 3]:
            raise ValueError('You gave an invalid difficulty of %d!' %
                             difficulty)

        while True:
            a = not_named_yet.randint_no_zero(-coefficients_bound + 2,
                                              coefficients_bound - 2)
            b = random.randint(-coefficients_bound * 4, coefficients_bound * 4)
            c = random.randint(-coefficients_bound * 4, coefficients_bound * 4)
            discriminant = b**2 - 4 * a * c
            if difficulty == 1 and discriminant == 0 and (b == 0 or c == 0):
                break
            elif difficulty == 2 and discriminant > 0 and gmpy.is_square(
                    discriminant):
                break
            elif difficulty == 3 and discriminant > 0 and not gmpy.is_square(
                    discriminant):
                break

        self.equation = a * x**2 + b * x + c
        self.discriminant = b**2 - 4 * a * c

        self.domain = sympy.Interval(-sympy.oo, sympy.oo, True, True)
        vertex_x = -sympy.Rational(b, 2 * a)
        vertex_y = self.equation.subs({x: vertex_x})

        if a > 0:
            self.range = sympy.Interval(vertex_y, sympy.oo, False, True)
        else:
            self.range = sympy.Interval(-sympy.oo, vertex_y, True, False)
Beispiel #2
0
    def __init__(self, difficulty):

        if difficulty not in [1, 2, 3]:
            raise ValueError("You gave an invalid difficulty of %d!" % difficulty)

        while True:
            a = not_named_yet.randint_no_zero(-coefficients_bound + 2, coefficients_bound - 2)
            b = random.randint(-coefficients_bound * 4, coefficients_bound * 4)
            c = random.randint(-coefficients_bound * 4, coefficients_bound * 4)
            discriminant = b ** 2 - 4 * a * c
            if difficulty == 1 and discriminant == 0 and (b == 0 or c == 0):
                break
            elif difficulty == 2 and discriminant > 0 and gmpy.is_square(discriminant):
                break
            elif difficulty == 3 and discriminant > 0 and not gmpy.is_square(discriminant):
                break

        self.equation = a * x ** 2 + b * x + c
        self.discriminant = b ** 2 - 4 * a * c

        self.domain = sympy.Interval(-sympy.oo, sympy.oo, True, True)
        vertex_x = -sympy.Rational(b, 2 * a)
        vertex_y = self.equation.subs({x: vertex_x})

        if a > 0:
            self.range = sympy.Interval(vertex_y, sympy.oo, False, True)
        else:
            self.range = sympy.Interval(-sympy.oo, vertex_y, True, False)
Beispiel #3
0
def Euler_98(i_file='98.txt'):
	'''Find the largest square anagram in the given text file
		The anagram of the word must exist in the text file
	'''
	with open(i_file, encoding="utf-8") as data:
		for a_line in data:
			word_tuple = tuple([x.strip('"') for x in a_line.split('","')])
	
	if not word_tuple:
		return None
	word_list = [x for x in reversed(sorted(list(word_tuple), key=len))]
	dict_list = [{a:x.count(a) for a in x} for x in word_list]
	'''
	word_tuple = tuple(word_list)
	for x in range(len(word_tuple)):
		pair = False
		for y in range(len(word_list)):
			if (not word_tuple[x] == word_list[y]) and dict_list[
				print(x,y)
				pair = True
				break
		if not pair:
			word_list.remove(x) 
	
	'''
	print(word_list)
	word_tuple = tuple(word_list)
	max_length = 0
	max_sq = 0
	digits = tuple(ord(c) for c in '0123456789')
	for index in range(word_tuple):
		word = word_tuple[index]
		tmp = dict_list[index]
		dict_list[index] = 0
		if not tmp in dict_list:
			break
		if len(word) < max_length:
			break
		letter_set = tuple(ord(c) for c in set(word))
		for guess in itertools.permutations(digits, len(letter_set)):
			translation = dict(zip(letter_set, guess))
			if not gmpy.is_square(int(word.translate(translation))):
				continue
			word_dict = {x:word.count(x) for x in word}
			for candidate in word_tuple:
				if word_dict == {x:candidate.count(x) for x in candidate} and gmpy.is_square(int(candidate.translate(translation))):
					if int(candidate.translate(translation)) > max_sq:
						max_sq = int(candidate.translate(translation))
						max_length = len(candidate)
					if int(word.translate(translation)) > max_sq:
						max_sq = int(word.translate(translation))
						max_length = len(word)
	
	return max_sq
Beispiel #4
0
def q1():
    N = gmpy.mpz(
        "17976931348623159077293051907890247336179769789423065727343008115 \
                  77326758055056206869853794492129829595855013875371640157101398586 \
                  47833778606925583497541085196591615128057575940752635007475935288 \
                  71082364994994077189561705436114947486504671101510156394068052754 \
                  0071584560878577663743040086340742855278549092581")

    A = gmpy.sqrt(N) + 1
    x1 = A**2 - N
    assert gmpy.is_square(x1)
    x = gmpy.sqrt(x1)
    p = A - x
    q = A + x
    assert p * q == N

    print "Answer to Question 1:"
    print p
    #print q
    #print x
    # Answer:
    assert p == gmpy.mpz(
        "134078079299425970995740249982058461274793658205923933777235614437217640300736 \
                          62768891111614362326998675040546094339320838419523375986027530441562135724301"
    )

    return N, p, q
Beispiel #5
0
 def parseFile(self, input_file):#parses a text file for its Sudoku grid
     '''
     files will be saved in the the following format:
         1,2,3,4,5,6,7,8,9
         2,3,4,5,6,7,8,9,1
         ...
         9,8,7,6,4,5,3,1,2
     '''
     try:
         with open(input_file,"r") as f:
             self.grid = f.read().split("\n")
             if self.grid[-1] == "":
                 self.grid.pop(-1)
             self.size = len(self.grid)
             if not is_square(self.size):
                 sys.exit("Invalid input file length")
             for i in range(self.size):
                 self.grid[i] = self.grid[i].split(",")
                 if len(self.grid[i]) != self.size:
                     sys.exit("Input file is formatted incorrectly")
                 for j in range(self.size):
                     try:
                         self.grid[i][j] = [int(self.grid[i][j])]
                     except ValueError:
                         if self.grid[i][j] == "-"
                             self.grid[i][j] = [i for i in range(1,self.size+1)]
                         else:
                             sys.exit("Input file is formatted incorrectly")
     except IOError:
         sys.exit("Input file does not exist")
Beispiel #6
0
def rational_golden_nugget(N):
#	assert N > 10, "N should be an integer larger than 10"
#	k = 74049691

#(k, 5*k^2 + 2*k + 1)
#(2, 25)
#(15, 1156)
#(104, 54289)
#(714, 2550409)
#(4895, 119814916)
#(33552, 5628750625)
#(229970, 264431464441)
#(1576239, 12422650078084)
#(10803704, 583600122205489)
#(74049690, 27416783093579881)
#(507544127, 1288005205276048900)

	#s = [2,15,104,714,4895,33552,229970,1576239,10803704,74049690,507544127]
	
	index = 8
	k = 10803704
	kold = k
	d = 5*k**2 + 2*k + 1
	while index < N:
		if gmpy.is_square(d):
			index += 1
			print(index, k, d)
			kold = k
			k = int(6.8541*k)
			d = 5*k**2 + 2*k + 1
		d += 10*k + 7
		k += 1
	return kold
Beispiel #7
0
def check(a,b,p):
    semip = p/2
    c = (semip*(semip-b))
    if gmpy.is_square(c):
        print (a,a,b,p)
        return True
    return False
Beispiel #8
0
def q2():
    N = gmpy.mpz(
        "6484558428080716696628242653467722787263437207069762630604390703787 \
                  9730861808111646271401527606141756919558732184025452065542490671989 \
                  2428844841839353281972988531310511738648965962582821502504990264452 \
                  1008852816733037111422964210278402893076574586452336833570778346897 \
                  15838646088239640236866252211790085787877")

    A0 = gmpy.sqrt(N) + 1
    for i in xrange(2**20):
        A = A0 + i
        x1 = A**2 - N
        if gmpy.is_square(x1):
            x = gmpy.sqrt(x1)
            p = A - x
            q = A + x
            if p * q == N:
                break
    assert p * q == N
    print "Answer to Question 2:"
    print p
    # Answer:
    assert p == gmpy.mpz(
        "254647961469961834380088165639739422293414542685241578463285819278857779699852 \
                          22835143851073249573454107384461557193173304497244814071505790566593206419759"
    )
Beispiel #9
0
def to_matrix(s):
    s = s.rstrip()
    if gmpy.is_square(len(s)):
        r = int(round(len(s)**0.5))
        nums = [ord(x.lower()) - 97 for x in s]
        arr = [nums[x:x + r] for x in range(0, len(nums), r)]
        return np.array(arr)
Beispiel #10
0
def solve(A, B):
    counter = 0
    for x in range(A, B + 1):
        if is_fair(str(x)):
            if gmpy.is_square(x):
                if is_fair(str(gmpy.sqrt(x))):
                    counter += 1
    return counter
Beispiel #11
0
def count_odd_periods(max_root):
    count = 0
    for root in xrange(2, max_root + 1):
        if gmpy.is_square(root):
            continue
        period = get_period(root)
        if period % 2 == 1:
            count += 1
    return count
Beispiel #12
0
def diophantine(d):
    """Determines the minimum solution of x for the equation
    x**2 - Dy**2 = 1"""
    x = gmpy.mpz(2)
    while True:
        num = x*x-1
        if num%d == 0 and gmpy.is_square(num/d):
            return x
        x += 1
Beispiel #13
0
def is_pentagonal(x):
    """Number x is pentagonal if (sqrt(24x+1) + 1) / 6 is natural"""
    root = 24*x+1
    if gmpy.is_square(root):
        return 0 == (int(root**0.5) + 1) % 6
        #if 0 == (int(root**0.5) + 1) % 6:
        #    print (int(root**0.5) + 1) / 6
        #    return True
    return False
Beispiel #14
0
def find_minimal_sol(n):
    j = 1
    while True:
        i_2 = 1 + n * j**2
        if gmpy.is_square(i_2):
            i = math.sqrt(i_2)
            print i, j, n
            return i
        j += 1
Beispiel #15
0
def solve(a,b):
    global count

    aSqrt = int(sqrt(a)) if is_square(a) else int(sqrt(a)) + 1
    bSqrt = int(sqrt(b))

    count = 0
    search([], aSqrt, bSqrt)
    return count
Beispiel #16
0
def fermat(N):
    a = gmpy.sqrt(N)
    b2 = a*a - N
    while not gmpy.is_square(gmpy.mpz(b2)):
        b2 += 2*a + 1
        a += 1
    factor1 = a - gmpy.sqrt(b2)
    factor2 = a + gmpy.sqrt(b2)
    return (long(factor1.digits()), long(factor2.digits()))
def area(a, b, c):
    if (a + b + c) & 1:
        return False

    s = (a + b + c) / 2
    A = s * (s - a) * (s - b) * (s - c)

    if A < 0:
        return False
    return gmpy.is_square(A)
def getDivisors(num):
    """Gets the number of divisors for the number."""
    # Start with 2 for num and 1
    numDivisors = 2
    for i in range(2, (int(math.sqrt(num)) + 1)):
        if num % i == 0:
            numDivisors += 2
    if gmpy.is_square(num):
        numDivisors -= 1
    return numDivisors
Beispiel #19
0
def solution():  # 422ms
    for d in itertools.count(1):
        D_ = 1 + 12*d*(3*d-1)
        for j in range(1, d):  #cheat! (D-1)/3
            J_ = 12*j*(3*j-1)
            K_ = D_ + J_
            if not is_square(K_):
                continue
            N_ = K_ + J_
            if not is_square(N_):
                continue
            k_ = int(math.sqrt(K_))
            if k_ % 6 != 5:
                continue
            n_ = int(math.sqrt(N_))
            if n_ % 6 != 5:
                continue
            #print 'd=',d, 'j=',j
            return pentagonal(d)
Beispiel #20
0
 def __init__(self, size=400, *args, **kwargs):
     '''initializes a square playground. size must be a perfect square
     '''
     if is_square(size):
         self.size = size
         self.length = int(sqrt(self.size))
         self.set_grid()
     else:
         raise ValueError("size must be a perfect square")
     object.__init__(self, *args, **kwargs)
Beispiel #21
0
def palindromeQ(n):
    s = str(n)
    if s[-1] not in goodDigits:
        return False
    else:
        if gmpy.is_square(n):
            return (palindrome(s)
                    and palindrome(str(math.floor(math.sqrt(n)))))
        else:
            return False
Beispiel #22
0
def getDivisors(num):
    """Gets the number of divisors for the number."""
    #Start with 2 for num and 1
    numDivisors = 2
    for i in range(2, (int(math.sqrt(num)) + 1)):
        if (num % i == 0):
            numDivisors += 2
    if gmpy.is_square(num):
        numDivisors -= 1
    return numDivisors
Beispiel #23
0
 def verify(self, f):
     k = f.numerator
     d = f.denominator
     phin = (self.key.e * d - 1) / k
     B = self.key.n - phin + 1
     det = (B * B) - (4 * 1 * self.key.n) 
     if det > 0 and gmpy.is_square(det):
         self.key.d = d
         self.key.phin = phin
         return True
     else:
         return False
Beispiel #24
0
def is_goldbach(n):
    for p in primes():
        if p > n:
            return False
        if (n - p) % 2 != 0:
            continue
        sub_p = (n - p) // 2
        if gmpy.is_square(sub_p):
            if (n % 1000 == 1):
                print(f'{n} = {p} + 2*{sub_p}')
            return True
    return False
Beispiel #25
0
def read_file(f):
    try:
        r = None
        with open(f, "r") as content:
            r = content.read()
        r = [c for c in r.replace('\n', ' ').split() if c != '']
        if not is_square(len(r)):
            error(str(f) + " input is not a square", 5)
        make_matrix(r)
        return r
    except Exception as e:
        error(e.strerror, 4)
Beispiel #26
0
def slaves():
    while True:
        b2 = queue.get()
        if b2 is None:
            break
        if gmpy.is_square(gmpy.mpz(b2)):
            with lock:
                finish.value = 1
                a = gmpy.sqrt(n + b2)
                factor1 = a - gmpy.sqrt(b2)
                factor2 = a + gmpy.sqrt(b2)
                p.value = long(factor1.digits())
                q.value = long(factor2.digits())
Beispiel #27
0
def factor_fermat(N):
    a = gmpy.sqrt(N)
    b2 = a * a - N
    tes = 0
    while not gmpy.is_square(gmpy.mpz(b2)):
        b2 += 2 * a + 1
        a += 1
        tes += 1
        if tes > 3000:
            return "x", "x"
        factor1 = a - gmpy.sqrt(b2)
        factor2 = a + gmpy.sqrt(b2)
    return (long(factor1.digits()), long(factor2.digits()))
Beispiel #28
0
def q3():
    N = gmpy.mpz(
        "72006226374735042527956443552558373833808445147399984182665305798191 \
                  63556901883377904234086641876639384851752649940178970835240791356868 \
                  77441155132015188279331812309091996246361896836573643119174094961348 \
                  52463970788523879939683923036467667022162701835329944324119217381272 \
                  9276147530748597302192751375739387929")
    ''' Given: |3p - 2q| < N**(1/4)                  (1)
        N = pq
        Let A = (3p+2q)/2
        => 2A = (6p+4q)/2
        => 2A is an integer, and lies exactly midway between 6p and 4q
        
        Let 6p = 2A - x
            4q = 2A + x
        => 24pq = 4A**2 - x**2
        => 24N = 4A**2 - x**2
        => x = sqrt(4A**2 - 24N)                     (2)
        
        To find x using (2), we need to find relation between A and N.
        Consider the value A**2 - 6N
        A**2 - 6N = (3p+2q)**2 / 4   -  6pq = (3p-2q)**2 / 4   , on simplifying.
        
        But, A**2 - 6N = (A + sqrt(6N))(A - sqrt(6N))
        Hence, A - sqrt(6N) = (3p-2q)**2 / (4(A + sqrt(6N)))         (3)
        
        Now A = (3p+2q)/2 > sqrt(3p*2q) = sqrt(6N)    since AM > GM for 2 non-equal numbers
        => A > sqrt(6N)
        => A + sqrt(6N) > 2*sqrt(6N)
        
        Using above line in (3), we get the inequality:
        A - sqrt(6N) < (3p-2q)**2 / (8*sqrt(6N)) < sqrt(N) / (8*sqrt(6N))    Using (1)
        
        Thus A - sqrt(6N) < 1 / (8*sqrt(6) < 1              [Proved]'''

    twoA = gmpy.sqrt(
        4 * 6 * N
    ) + 1  # A = sqrt(6N) + 0.5, since A, which is (3p+2q)/2, is NOT an integer.
    v = (twoA**2) - 24 * N
    assert gmpy.is_square(v)
    x = gmpy.sqrt(v)
    p = (twoA - x) / 6
    q = (twoA + x) / 4
    assert p * q == N
    print "Answer to Question 3:"
    print p
    # Answer:
    assert p == gmpy.mpz(
        "219098495924755330922739885315839558989821760933449290300994235841272120781261 \
                          50044721102570957812665127475051465088833555993294644190955293613411658629209"
    )
Beispiel #29
0
def throughRange(low, high):
    count = 0
    for i in range(low, high + 1):
        if (gmpy.is_square(i)):

            x = palindrone(list(str(i)))
            integer = math.sqrt(i)
            y = palindrone(list(str(int(math.sqrt(i)))))

            if (x and y):

                count += 1

    return count
Beispiel #30
0
def check_range(start, end):
	qty = 0
	i = start

	for i in xrange(start, end+1):
		if gmpy.is_square(i):
			strn = str(i)
			if strn == strn[::-1]:
				n = str(gmpy.sqrt(i))
				if n == n[::-1]:
					qty += 1
		i += 1

	return qty
Beispiel #31
0
def factor_fermat(N):
    """
    Guess at a and hope that a^2 - N = b^2,
    which is the case if p and q is "too close".
    """
    a  = gmpy.sqrt(N)
    b2 = a*a - N
    while not gmpy.is_square(gmpy.mpz(b2)):
        b2 += 2*a + 1
        a  += 1

    factor1 = a - gmpy.sqrt(b2)
    factor2 = a + gmpy.sqrt(b2)
    return (int(factor1.digits()),int(factor2.digits()))
Beispiel #32
0
Datei: trmr.py Projekt: trmr/ctf
def wieners_attack(e, n):
    cf = continued_fraction(e, n)
    convergents = convergents_of_contfrac(cf)

    for k, d in convergents:
        if k == 0:
            continue
        phi, rem = divmod(e * d - 1, k)
        if rem != 0:
            continue
        s = n - phi + 1
        # check if x^2 - s*x + n = 0 has integer roots
        D = s * s - 4 * n
        if D > 0 and gmpy.is_square(D):
            return d
def Fermat(n):
    """
        Implementa el Método de Fermat para factorización de enteros
    """
    if 1 & n == 0:
        return "The number is even"
    x = int(ceil(isqrt(n)))
    perfect = (x * x) - n
    isPerfect = False
    while not isPerfect:
        x += 1
        perfect = (x * x) - n
        if gmpy.is_square(perfect):
            isPerfect = True
    return x - isqrt(perfect)
Beispiel #34
0
	def fermat(n, astart, aend, astep, k):		
		if k==len(moduli) or (aend-astart)/astep < 2:
			lista = [astart+i*astep for i in range(0,((aend-astart)/astep)+1)]
			listb2 = [a**2 - n for a in lista]
			return any([gmp.is_square(b2) for b2 in listb2])
		
		result = []
		mod, quadRes = moduli[k]
		a = astart
		
		for i in range(0, min(mod, (aend-astart)/astep + 1)):
			if ((a**2-n) % mod) in quadRes:
				result.append(fermat(n, a, aend, astep*mod, k+1))
			a+=astep
		return any(result)
Beispiel #35
0
def Factor(n, parameter):
	if n % 2 == 0:
		return true

	a = gmp.sqrt(n)
	b2 = a**2-n
	bound = a + parameter

	while not gmp.is_square(b2) and a<=bound:
		b2=b2+2*a+1
		a+=1
	
	if a > bound:
		return False
	else:
		return True
Beispiel #36
0
def check(num):
    '''
		if num is palindrome then add to palindrome dict
		if it is a perfect square then, check if square root is palindrome

	'''
    if isPalindrome(str(num)):
        '''
		'''

        if gmpy.is_square(num):
            sq_root = int(math.sqrt(num))
            if isPalindrome(str(sq_root)):
                return True

    return False
Beispiel #37
0
def wieners_attack(e, n):
    def continued_fraction(n, d):
        """
        415/93 = 4 + 1/(2 + 1/(6 + 1/7))

        >>> continued_fraction(415, 93)
        [4, 2, 6, 7]
        """
        cf = []
        while d:
            q = n // d
            cf.append(q)
            n, d = d, n-d*q
        return cf

    def convergents_of_contfrac(cf):
        """
        4 + 1/(2 + 1/(6 + 1/7)) is approximately 4/1, 9/2, 58/13 and 415/93

        >>> list(convergents_of_contfrac([4, 2, 6, 7]))
        [(4, 1), (9, 2), (58, 13), (415, 93)]
        """
        n0, n1 = cf[0], cf[0]*cf[1]+1
        d0, d1 = 1, cf[1]
        yield (n0, d0)
        yield (n1, d1)

        for i in xrange(2, len(cf)):
            n2, d2 = cf[i]*n1+n0, cf[i]*d1+d0
            yield (n2, d2)
            n0, n1 = n1, n2
            d0, d1 = d1, d2

    cf = continued_fraction(e, n)
    convergents = convergents_of_contfrac(cf)

    for k, d in convergents:
        if k == 0:
            continue
        phi, rem = divmod(e*d-1, k)
        if rem != 0:
            continue
        s = n - phi + 1
        # check if x^2 - s*x + n = 0 has integer roots
        D = s*s - 4*n
        if D > 0 and is_square(D):
            return d
Beispiel #38
0
def main():
    board_size = 0
    if len(sys.argv) < 2:
        print("Usage is ./main.py <N:int:perfect_square>")
        exit()
    try:
        board_size = int(sys.argv[1])
        if not gmpy.is_square(board_size):
            print("Number is not a perfect square")
            exit()
    except ValueError:
        print("Argument is not int")
        exit()

    game = [[0 for _ in range(board_size)] for _ in range(board_size)]
    sudoku = Sudoku(game)
    sudoku.solve()
    sudoku.printGame()
Beispiel #39
0
def main():
    max_D = 0
    max_x = 0
    y = 1
    y_sqr = 1
    while len(todo) > 0:
        for D in list(todo):
            if gmpy.is_square(D * y_sqr + 1):
                int_sqrt = int(sqrt(D * y_sqr + 1))
                Ds[D] = int_sqrt
                todo.remove(D)
                print "D:", D
                print "Minimal (x, y):", int_sqrt, y
                if int_sqrt > max_x:
                    max_x = int_sqrt
                    max_D = D
        y_sqr += 2 * y + 1
        y += 1
    print max_D
Beispiel #40
0
def wiener(e, n):
    """
  Wiener's Attack
  @param  e int: public exponent
  @param  n int: modulus
  @return d int: private key
  """
    cf = continued_fraction(e, n)
    convergents = convergents_of_contfrac(cf)
    for k, d in convergents:
        if k == 0:
            continue
        phi, rem = divmod(e * d - 1, k)
        if rem != 0:
            continue
        s = n - phi + 1
        D = s * s - 4 * n
        if D > 0 and gmpy.is_square(D):
            return d
Beispiel #41
0
def main(loc=""):
    raw = input('input location: ')
    f = open(raw, 'r+')
    o = open("C:/Users/Matt/Desktop/output.txt", 'w')
    num = int(f.readline())  #num of inputs
    board = ""
    inp = []
    for j in xrange(0, num):
        inp = readinput(f, 1, 0)
        inpstr = ''.join(inp)
        bounds = inpstr.split(" ")
        count = 0
        for i in xrange(int(bounds[0]), int(bounds[1]) + 1):
            if str(i) == str(i)[::-1]:
                if gmpy.is_square(i):
                    root = int(math.sqrt(i))
                    print root
                    if str(root) == str(root)[::-1]:
                        count += 1
        done(count, j, o)
Beispiel #42
0
def almostEqualTri(x, y):
	if gmpy.is_square(x**2-(y/2)**2):
		print("found %d" % x)
		return x+x+y
	return 0
Beispiel #43
0
solution by Kevin Retzke, May 2012
"""
import math
import gmpy

def diophantine(d):
    """Determines the minimum solution of x for the equation
    x**2 - Dy**2 = 1"""
    x = gmpy.mpz(2)
    while True:
        num = x*x-1
        if num%d == 0 and gmpy.is_square(num/d):
            return x
        x += 1

if __name__ == '__main__':
    assert map(diophantine, [2,3,5,6,7]) == [3,2,9,5,8]
    maxx = 0
    maxd = 0
    for d in xrange(2,62):
        if gmpy.is_square(d):
            continue
        x = diophantine(d)
        print d, x
        if x > maxx:
            maxx = x
            maxd = d
            #print maxd, maxx
    print maxd
            
                        while len(i) > 1:
                            i.insert(0, i.pop(0) + i.pop(0))
                        while len(j) > 1:
                            j.insert(0, j.pop(0) + j.pop(0))
#                        print i, j
                        if i == j:
                            print len(queue), str(current[0][0]) + ": " + (answers[str(current)][0]) + "\n",
                            writefile.write(str(current[0][0]) + ": " + answers[str(current)][0] + "\n")
#            print curscore, len(queue), current,
            current = [Fraction(i[0], i[1]) for i in current]
#            print answers[str([(k.numerator, k.denominator) for k in current])]
            for i in range(len(current)):
                # sqrt
                temp = copy(current)
                tempstr = copy(stringrep)
                if is_square(temp[i].numerator) and is_square(temp[i].denominator):
                    temp[i] = Fraction(-isqrt(temp[i].numerator), isqrt(temp[i].denominator))
                    tempstr.insert(i, "-sqrt(" + tempstr.pop(i) + ")")
                    if str([(k.numerator, k.denominator) for k in temp]) not in answers:
                        heapq.heappush(queue, (score(tempstr), [(k.numerator, k.denominator) for k in temp]))
                        answers[str([(k.numerator, k.denominator) for k in temp])] = tempstr
                # Factorial
                temp = copy(current)
                tempstr = copy(stringrep)
                try:
                    if temp[i].numerator >= 0 and temp[i].numerator < 20 and temp[i].denominator == 1:
                        temp.insert(i, Fraction(-factorials[temp.pop(i).numerator], 1))
                        tempstr.insert(i, "-(" + tempstr.pop(i) + ")! ")
                        if str([(k.numerator, k.denominator) for k in temp]) not in answers:
                            heapq.heappush(queue, (score(tempstr), [(k.numerator, k.denominator) for k in temp]))
                            answers[str([(k.numerator, k.denominator) for k in temp])] = tempstr
Beispiel #45
0
words = []
for key in dic.keys():
	if len(dic[key])==2:
		words.append(dic[key])
	elif len(dic[key])>=3:
		comb = itertools.combinations(dic[key],2)
		while (1):
			try:
				words.append(list(comb.next()))
			except StopIteration:
				break

for word_pair in words:
	word0, word1 = word_pair
	a = itertools.permutations([1,2,3,4,5,6,7,8,9], len(word0))
	print word_pair
	while(1):
		try:
			numbers = list(a.next())
			dic = dict(zip(sorted(word0),numbers))
			number0 = int("".join([str(dic[i]) for i in word0]))
			if gmpy.is_square(number0):
				number1 = int("".join([str(dic[i]) for i in word1]))
				if gmpy.is_square(number1):
					print number0, number1
		except StopIteration:
			break


Beispiel #46
0
    a = 1
    yield a
    b = 5
    yield b
    r = 0
    while r < n:
        r = 6 * b - a
        yield r
        a = b
        b = r



nums = seq_A001653()

tr = next(nums)
while True:
    tr = next(nums)
    s = tr ** 2
    if (not gmpy.is_square(2 * s - 1)):
        continue
    t = (1 + gmpy.sqrt(2 * s - 1)) / 2
    r = 1 + 2 * t ** 2 - 2 * t
    if (gmpy.is_square(r)):
        if (r % 2 == 1):
            print int(1+gmpy.sqrt(r))/2, t
            if (t > 10 ** 12):
                break
            

Beispiel #47
0
import gmpy

side = 333333334
solution = 0
for x in xrange( 2, side ):
    for ( a, b, c ) in [ ( x, x, x + 1 ), ( x, x, x - 1 ) ]:
        if c % 2 == 0:
            s = ( a + b + c ) / 2
            if gmpy.is_square( s * ( s - a ) * ( s - b ) * ( s - c ) ):
                solution = solution + a + b + c
    if x % 1000000 == 0:
        print "Progress: %i%%" % ( 100 * x / side )
print solution
Beispiel #48
0
def gevp(plotting_function, plotdata, bootstrapsize,
         pdfplot, logscale=False, verbose=False):
    """
  Create a multipage plot with a page for every element of the rho gevp

  Parameters
  ----------

  plotdata: pd.DataFrame

      Table with a row for each gevp element (sorted by gevp column running
      faster than gevp row) and hierarchical columns for gauge configuration
      number and timeslice

  bootstrapsize : int

      The number of bootstrap samples being drawn from `plotdata`.

  pdfplot : mpl.PdfPages object

      Plots will be written to the path `pdfplot` was created with.

  See also
  --------

  utils.create_pdfplot()
  """

    assert np.all(plotdata.notnull()), 'Gevp contains null entires'
    plotdata = mean_and_std(plotdata, bootstrapsize)

    # abs of smallest positive value
    #linthreshy = plotdata['mean'][plotdata['mean'] > 0].min().min()
    # abs of value closest to zero
    linthreshy = 1e3 * plotdata['mean'].iloc[plotdata.loc[:,
                                                          ('mean', 0)].nonzero()].abs().min().min()

    # Create unique list of gevp elements to loop over while keeping order intact
    seen = set()
    plotlabel = []
    for item in [(i[0], i[1]) for i in plotdata.index.values]:
        if item not in seen:
            seen.add(item)
            plotlabel.append(item)
    assert gmpy.is_square(len(plotlabel)), 'Gevp is not a square matrix'
    gevp_size = int(gmpy.sqrt(len(plotlabel)))

    # Prepare Figure
    fig, axes = plt.subplots(gevp_size, gevp_size, sharex=True, sharey=True)

    for counter, graphlabel in enumerate(plotlabel):

        if verbose:
            print '\tplotting ', graphlabel[0], ' - ', graphlabel[1]

        # Prepare Axes
        ax = axes[counter // gevp_size, counter % gevp_size]
#        ax.set_title(r'Gevp Element ${}$ - ${}$'.format(graphlabel[0], graphlabel[1]))
        ax.set_xlabel(r'$%s$' % graphlabel[1], fontsize=3, rotation=30)
        ax.set_ylabel(r'$%s$' % graphlabel[0], fontsize=3, rotation=30)
        # https://stackoverflow.com/questions/4209467/matplotlib-share-x-axis-but-dont-show-x-axis-tick-labels-for-both-just-one
        ax.label_outer()

        if logscale:
            #            ax.locator_params(axis='y', numticks=3)
            ax.set_yscale('symlog', linthreshy=linthreshy)

        ax.set_xticks([])
#        ax.tick_params(labelleft='off')
        ax.set_yticks([])

        # Select data for plot
        graphdata = plotdata.xs(graphlabel, level=['gevp_row', 'gevp_col'])

        plotting_function(graphdata, ax, scale=gevp_size)
        if ax.legend_:
            ax.legend_.remove()

#    plt.locator_params(axis='y', numticks=2)
    plt.tight_layout(h_pad=0.1, w_pad=0.15)
    pdfplot.savefig(fig)
    plt.close(fig)

    return
Beispiel #49
0
def test_difficulty_three():
    obj = quadratic.Quadratic(difficulty=3)

    assert obj.discriminant > 0
    assert not gmpy.is_square(obj.discriminant)
Beispiel #50
0
def test_difficulty_two():
    obj = quadratic.Quadratic(difficulty=2)

    assert obj.discriminant > 0
    assert gmpy.is_square(obj.discriminant)
Beispiel #51
0
def is_diophantine_solution(d, x):
    tmp = x ** 2 - 1
    if tmp % d != 0:
        return False
    return tmp / d > 0 and gmpy.is_square(tmp / d)
Beispiel #52
0
import gmpy

def gcd(a,b):
    if b == 0:
        return a
    else:
        return gcd(b, a % b)

l = set()

for a in range(2,10**4):
    for b in range(1,a):
        if gcd(a,b) > 1:
            continue
        n = a**3*b+b**2
        c = 1
        if n > 10 ** 12:
            break
        if gmpy.is_square(n):
            print n
            l.add(n)
        while n < 10**12:
            c += 1
            n = c**2*a**3*b+c*b**2
            if gmpy.is_square(n):
                l.add(n)
                print n

print sum(l)
Beispiel #53
0
    q_n = int(x_n)
    P_n_minus_2 = 1
    P_n_minus_1 = q_0
    P_n = q_n * P_n_minus_1 + P_n_minus_2
    Q_n_minus_2 = 0
    Q_n_minus_1 = 1
    Q_n = q_n * Q_n_minus_1 + Q_n_minus_2
    while True:
        P_n_minus_2 = P_n_minus_1
        Q_n_minus_2 = Q_n_minus_1
        x_n, q_n, P_n, P_n_minus_1, Q_n, Q_n_minus_1 = pells_reccurence(x_n, q_n, P_n, P_n_minus_1, Q_n, Q_n_minus_1)
        n = n + 1
        print "\tx_n=%s" % x_n
        if x_n == x_1:
            # n == k + 1
            # k = n - 1
            # x = P_k_minus_1 = P_n_minus_2
            P = P_n_minus_2
            Q = Q_n_minus_2
            if P**2 - d * Q**2 == 1:
                return P
            else:
                assert(P**2 - d * Q**2 == -1)
                return P**2 + d * Q**2

if __name__ == '__main__':
    max_d = 1000
    solutions = [(d, solve_pells_equation(d)) for d in xrange(1, max_d + 1) if not gmpy.is_square(d)]
    print max(solutions, key=lambda x: x[1])

Beispiel #54
0
#!/usr/bin/python
from gmpy import is_square
import sys
M=int(sys.argv[1])
powers=range(int(((M+M)**2+M**2)**0.5)+1)

count=0
for i in range(1,M+1):
    for j in range(i,M+1):
        a=(i+j)**2
        count+=sum([1 for k in range(j,M+1) if is_square(a+k**2)])
        print count
print count
# Her ne kadar 6 bilinmeyen var gibi görünse de bunlardan üçünü bildiğimizde kalan üçü onlar cinsinden hesaplanabilir.
# 6 değişken tam kare olarak hesaplandığında geri kalan sadece onlara karşılık gelen x,y,z üçlüsünü hesaplamak olacaktır.
# Aşağıdaki kod pisagor üçlüsü olma özelliği de kullanılarak daha verimli hale getirilebilir ama algoritma dersinde kullanmak için bu kadarını bırakıyorum.

from gmpy import is_square

def solve(a,b,c,d,e,f):
    x = (a+b)/2
    y = (e+f)/2
    z = (c-d)/2
    if(x>y and y>z and z>0 and x==int(x) and y==int(y) and z==int(z)):
        return(int(x+y+z))
    else:
        return(0)

for a in range(2,1000):
    a2 = a**2
    for c in range(2,1000):
        c2 = c**2
        for d in range(2,1000):
            d2 = d**2
            f2 = a2-c2
            if(f2>0 and is_square(f2)):
                e2 = a2-d2
                if(e2>0 and is_square(e2)):
                    b2 = c2-e2
                    if(b2>0 and is_square(b2)):
                        if(solve(a2,b2,c2,d2,e2,f2)!=0):
                            print(solve(a2,b2,c2,d2,e2,f2))
                            break
Beispiel #56
0
def write_ascii_gevp(path, basename, data, verbose=1):

    ensure_dir(path)

    # Cast data into longish data format with only gevp_row and gevp_col as index
    data = data.T.reset_index().set_index(['cnfg', 'T']).stack(
        level=['gevp_row', 'gevp_col', 'p_{cm}', '\mu']).reset_index(['p_{cm}', '\mu', 'cnfg', 'T'])
    data[['p_x', 'p_y', 'p_z']] = data['p_{cm}'].apply(literal_eval).apply(pd.Series)
    del data['p_{cm}']
    data.rename(columns={0: 'value', '\mu': 'alpha'}, inplace=True)

    gevp_indices = data.index.unique()
    operator_indices = data.loc[gevp_indices[0]].set_index(
        ['p_x', 'p_y', 'p_z', 'alpha']).index.unique()

    assert np.all(data.notnull()), ('Gevp contains null entires')
    assert gmpy.is_square(len(gevp_indices)), 'Gevp is not a square matrix'

    gevp_size = gmpy.sqrt(len(gevp_indices))

    # Write file with physical content corresponding to gevp index number (gevp_col)
    gevp_elements = [i[1] for i in gevp_indices.values[:gevp_size]]
    np.savetxt(os.path.join(path,
                            basename + '_gevp-indices.tsv'),
               np.array(zip(range(gevp_size),
                            gevp_elements)),
               fmt='%s',
               delimiter='\t',
               comments='',
               header='id\telement')

    # Write file with physical content corresponding to operator (p_cm, alpha)
    operator_elements = np.array([tuple(i) for i in operator_indices.values])
    np.savetxt(
        os.path.join(path, basename + '_operator-indices.tsv'),
        np.column_stack(
            (np.arange(
                operator_elements.shape[0]),
                operator_elements)),
        fmt='%s',
        delimiter='\t',
        comments='',
        header='id\tp_x\tp_y\tp_z\talpha')

    if verbose:
        print 'Creating a {} x {} Gevp from {} operators'.format(
            gevp_size, gevp_size, operator_elements.shape[0])

    # Loop over all projected operators and gevp elements and write an ascii file
    for gevp_counter, gevp_index in enumerate(gevp_indices):
        for operator_counter, operator_index in enumerate(operator_indices):

            filename = os.path.join(
                path,
                basename +
                '_op%d_gevp%d.%d.tsv' %
                (operator_counter,
                 gevp_counter /
                 gevp_size,
                 gevp_counter %
                 gevp_size))

            df = data.loc[gevp_index].set_index(
                ['p_x', 'p_y', 'p_z', 'alpha']).loc[operator_index]

            df.to_csv(filename, sep='\t', index=False)