Esempio n. 1
0
def solve():
  c,m = 0,0
  while c < N:
    m += 1
    for a in xrange(2,2*m+1):
      if is_square(a*a + m*m):
        c += (m + m + 2 - a)//2 if a > m+1 else a//2
  return m,c
Esempio n. 2
0
def gen_integral_almost_equilateral_triangles(max_x, limit):
    for x in range(2, max_x):
        a = 4 * x * x * x * x - (2 * x * x - (x - 1) * (x - 1)) * \
                                (2 * x * x - (x - 1) * (x - 1))
        if a % 16 == 0:
            if is_square(a / 16):
                perimeter = 3 * x - 1
                if perimeter <= limit:
                    yield perimeter

        a = 4 * x * x * x * x - (2 * x * x - (x + 1) * (x + 1)) * \
                                (2 * x * x - (x + 1) * (x + 1))
        if a % 16 == 0:
            if is_square(a / 16):
                perimeter = 3 * x + 1
                if perimeter <= limit:
                    yield perimeter
Esempio n. 3
0
def rectilinear_shape(population):
    try:
        pos = population.positions
    except Exception, e:
        LOGGER.warning(("Could not retrieve units positions for population "
                         "%s; assuming square shape."), population.label)
        if not is_square(population.size):
            raise TypeError(("The shape population %s is not square and could "
                              "neither be retreived nor guessed."), population.label)
        dim1 = dim2 = int(math.sqrt(population.size))
Esempio n. 4
0
def main():
    cnt = 0
    for a in count(1):
        for s in range(2, 2 * a + 1):

            if is_square(a * a + s * s):
                cnt += min(s, a + 1) - (s + 1) // 2

        if cnt > 1_000_000:
            return a
Esempio n. 5
0
def conjecture_correct(current_odd):
    for i in xrange(1, current_odd - 1):
        if not is_prime_c(i):
            continue
        r = current_odd - i
        if not is_even(r):
            continue
        r /= 2
        if is_square(r):
            #print "%d = %d + 2 * %d" % (current_odd, i, r)
            return True
    return False
Esempio n. 6
0
def continued_fraction(n):
    if is_square(n): return [int(n**0.5)]

    num = 0
    denom = 1
    rep = []
    while True:
        m = int((n**0.5 + num) / denom)
        rep.append(m)
        if m == 2 * int(n**0.5):
            return rep
        num, denom = denom * m - num, (n - (num - denom * m)**2) / denom
Esempio n. 7
0
 def decrypt(self, criptotext):
 	message = ""
 	for c in criptotext:
 		punto, x = c
 		s = (pow(punto[0], 3) + self.curve.A*punto[0] + self.curve.B) % self.curve.p
 		while not is_square(s):
 			s += self.curve.p
 		raiz = int(math.sqrt(s))
 		if punto[1]==1:
 			raiz *= -1
 		pt_desc = ec.scalar_multiplication((punto[0], raiz), self.s, self.curve)
 		valorFinal = (x * modinv(pt_desc[0]%self.curve.p, self.curve.p)) % self.p
 		message += self.alphabet[valorFinal]
     return message
Esempio n. 8
0
def convergents(number):
    if is_square(number):
        return number ** 0.5

    m, d, a = 0, 1, int(number ** 0.5)
    a0 = a
    history = []

    yield a
    while a != 2 * a0 or (m, d, a) not in history:
        history.append((m, d, a))
        m = int(d * a - m)
        d = int((number - m * m) / d)
        a = int((a0 + m) / d)
        yield a
Esempio n. 9
0
def convergents(number):
    if is_square(number):
        return number**0.5

    m, d, a = 0, 1, int(number**0.5)
    a0 = a
    history = []

    yield a
    while a != 2 * a0 or (m, d, a) not in history:
        history.append((m, d, a))
        m = int(d * a - m)
        d = int((number - m * m) / d)
        a = int((a0 + m) / d)
        yield a
Esempio n. 10
0
def num_type(n):
    types = list()
    if utils.is_triangle(n):
        types.append('A')
    if utils.is_square(n):
        types.append('B')
    if utils.is_pentagonal(n):
        types.append('C')
    if utils.is_hexagonal(n):
        types.append('D')
    if utils.is_heptagonal(n):
        types.append('E')
    if utils.is_octagonal(n):
        types.append('F')
    return types
Esempio n. 11
0
def cal_len(n):
    if utils.is_square(n):
        return 0
    h = dict()
    cnt = 0
    s = utils.FracWithSqrt(0, 1, 1, n)
    while True:
        cnt += 1
        rem = s.minus_int(int(s.get_exact()))
        if rem.get_val() not in h:
            h[rem.get_val()] = cnt
        else:
            return cnt - h[rem.get_val()]
        s = rem.reciprocal()
    return None
Esempio n. 12
0
def find(n):
    if utils.is_square(n):
        return None
    s = utils.FracWithSqrt(0, 1, 1, n)
    a_i = list()
    while True:
        a_i.append(int(s.get_exact()))
        cur = utils.FracWithSqrt(a_i[-1], 0, 1, 0)
        for a in a_i[::-1][1:]:
            cur = cur.reciprocal().minus_int(-a)
        x, _, y = cur.get_val()
        if x * x - n * y * y == 1:
            return x
        rem = s.minus_int(a_i[-1])
        s = rem.reciprocal()
    return None
Esempio n. 13
0
    def __init__(self, init_params, xform, num_frames=12):
        random.seed(RANDOM_SEED)

        self.gen_id = str(uuid4())[:18]
        self.xform = xform
        self.num_frames = num_frames
        self.init_params = init_params

        assert utils.is_square(self.xform)
        assert len(self.init_params) == len(self.xform)

        print("calc params")
        self.params = self.gen_params()
        print("calc seeds")
        self.seeds = self.gen_seeds()
        print(f"calc frames {self.gen_id}")
        self.frames = self.gen_frames()
Esempio n. 14
0
def run():
    """
    Solution: We observe that since a triangle number is given by x = n(n+1)/2,
    8*x + 1 = 4n(n+1) + 1 = 4n^2 + 4n + 1 = (2n + 1)^2 which is a perfect
    square.

    So to test for whether a number is a triangle number, we test if 8x + 1 is
    a perfect square.
    """
    words = read_file("data/p042 words.txt")

    count = 0
    for word in words:

        n = sum(map(lambda s: alphabet[s], word.lower()))

        if is_square(8 * n + 1):
            count += 1

    return count
Esempio n. 15
0
squares = defaultdict(list)

for n in range(1, 1000):
    x = n**2
    squares[generalize(str(x))].append(x)

words = defaultdict(list)

with open("./p098_words.txt") as f:
    for word in f.read().split(","):
        word = word[1:-1]
        words["".join(sorted(word))].append(word)

words = {k: l for k, l in words.items() if len(l) > 1}

res = 0
for word_chain in words.values():
    for a in word_chain:
        for b in word_chain:
            if a == b: continue
            if generalize(a) in squares:
                for n in squares[generalize(a)]:
                    if len(a) != len(str(n)): continue
                    mapping = {c: d for c, d in zip(a, str(n))}
                    m = int("".join(mapping[c] for c in b))
                    if is_square(m) and len(str(m)) == len(b):
                        res = max(res, n, m)

print res
Esempio n. 16
0
def refutes(i):
    for p in PRIMES:
        if is_square((i - p) / 2):
            return False
    return True
Esempio n. 17
0
# Odd period square roots
from utils import is_square


def continued_fraction(n):
    m = 0
    d = 1
    a = a0 = int(n**0.5)
    expansion = [a0]
    while a != 2 * a0:
        m = d * a - m
        d = (n - m**2) / d
        a = (a0 + m) / d
        expansion.append(a)
    return expansion


max_N = 10000
n = 0
for i in range(max_N + 1):
    if is_square(i):
        continue
    e = continued_fraction(i)
    if len(e) % 2 == 0:
        n += 1
print n
Esempio n. 18
0
def continous_fraction(sequence):
    if len(sequence) == 1:
        return sequence.pop()
    else:
        return Fraction(sequence.pop(0) + Fraction(1, continous_fraction(sequence)))


# VARIABLES
largest_x = 0
d_answer = 0

timer.start()

for D in range(2, 1001):
    # skip perfect squares
    if is_square(D): continue

    # init variables
    it = convergents(D)
    expansion = []
    expansion.append(next(it))

    # compute continous fraction and test it against Pell's equation.
    # keep expanding until a solution is found
    while True:
        frac = continous_fraction(expansion.copy())
        if frac.numerator ** 2 - D * frac.denominator ** 2 == 1:
            if frac.numerator > largest_x:
                largest_x = frac.numerator
                d_answer = D
            break
Esempio n. 19
0
 def test_is_square(self):
     self.assertTrue(is_square(4))
     self.assertFalse(is_square(8))
     x = 12345678987654321234567**2
     self.assertTrue(is_square(x))
     self.assertFalse(is_square(x + 2))
Esempio n. 20
0
from utils import is_square

from decimal import Decimal, getcontext

getcontext().prec = 120

res = 0

for n in range(1, 101):
    if is_square(n): continue
    root = Decimal(n)**Decimal(0.5)
    res += sum(int(d) for d in str(root).replace(".", "")[:100])
print(res)
Esempio n. 21
0
sqr_list = set()
i = 1
while i * i < RANGE:
    sqr_list.add(i * i)
    i += 1

ans = 0
for p in pairs:
    for s in sqr_list:
        if len(p[0]) == len(str(s)):
            c2d = dict()
            d2c = dict()
            match = True
            for c, d in zip(p[0], str(s)):
                if c not in c2d:
                    c2d[c] = d
                elif c2d[c] != d:
                    match = False
                    break
                if d not in d2c:
                    d2c[d] = c
                elif d2c[d] != c:
                    match = False
                    break
            if match:
                n2 = int(''.join([c2d[c] for c in p[1]]))
                if len(str(s)) == len(str(n2)) and utils.is_square(n2):
                    ans = max(ans, max(s, n2))

print(ans)
Esempio n. 22
0
from fractions import gcd
from utils import is_square

limit = 10**12
res = set()

for a in range(2, 10**4):
    for b in range(1, min(a, limit / a**3)):
        if gcd(a, b) > 1: continue
        for c in range(1, int((limit // a**3 // b)**0.5)):
            n = a**3 * b * c * c + c * b**2
            if is_square(n):
                res.add(n)

print sum(res)
Esempio n. 23
0
from utils import is_square

limit = 10**6
cur = 0

m = 2

while cur <= limit:
    m += 1
    for ab in range(3, 2*m):
        if is_square(ab*ab + m*m):
            cur += min(ab, m+1) - (ab+1)//2

print m

Esempio n. 24
0
"""
Created on Mon Apr 24 15:59:39 2018

@author: lamwa
"""

import utils

SUP = 10**12


def f(a, x, y):
    return a * a * x * x * x * y + a * y * y


ans_set = set()
x = 2
while f(1, x, 1) < SUP:
    y = 1
    while y < x and f(1, x, y) < SUP:
        a = 1
        while f(a, x, y) < SUP:
            ns = f(a, x, y)
            if utils.is_square(ns):
                ans_set.add(ns)
            a += 1
        y += 1
    x += 1
ans = sum(ans_set)
print(ans)
Esempio n. 25
0
from utils import is_square


def combs(x, y, z):
    return (x + y, x - y, x + z, x - z, y + z, y - z)


l = 1000
for i in range(1, l):
    e = i * i
    for j in range(i + 1, l):
        c = j * j
        if not is_square(c - e): continue
        off = 2 - i % 2
        for k in range(j + off, int((c + e)**0.5) + 1, 2):
            a = k * k
            if all(is_square(x) for x in (a - c, a - e, c - e)):
                print(a + c + e) / 2
Esempio n. 26
0
    if len(sequence) == 1:
        return sequence.pop()
    else:
        return Fraction(
            sequence.pop(0) + Fraction(1, continous_fraction(sequence)))


# VARIABLES
largest_x = 0
d_answer = 0

timer.start()

for D in range(2, 1001):
    # skip perfect squares
    if is_square(D): continue

    # init variables
    it = convergents(D)
    expansion = []
    expansion.append(next(it))

    # compute continous fraction and test it against Pell's equation.
    # keep expanding until a solution is found
    while True:
        frac = continous_fraction(expansion.copy())
        if frac.numerator**2 - D * frac.denominator**2 == 1:
            if frac.numerator > largest_x:
                largest_x = frac.numerator
                d_answer = D
            break
Esempio n. 27
0
 def test_is_square(self):
     self.assertTrue(is_square(4))
     self.assertFalse(is_square(8))
     x = 12345678987654321234567 ** 2
     self.assertTrue(is_square(x))
     self.assertFalse(is_square(x + 2))
Esempio n. 28
0
def fracs(x):
    first, l = get_period(x)
    n = 0
    d = 1
    for a in period_to_generator(l):
        n += a * d
        g = gcd(d, n)
        d, n = n / g, d / g
        yield first * d + n, d


def find_solution(D):

    for x, y in fracs(D):
        if x ** 2 - D * y ** 2 == 1:
            return x, y

m = 0
best = 0
for D in range(1001):
    if not is_square(D):
        x, y = find_solution(D)
        print D, x, y
        if x > m:
            best = D
            m = x

print m, best
#
# print find_solution(61)
Esempio n. 29
0
from utils import is_square

pos = 15
res = []

for l in range(900000):
    for add in (2, 4):
        k = (l + (5 * l * l + add)**0.5) / 2.0
        n = k * l
        if n % 1 == 0: res.append(int(n))

    if l > 0:
        for sub in (1, 2):
            k = 2 * l + (5 * l * l - sub)**0.5
            n = k * l
            if n % 1 == 0: res.append(int(n))

res = [n for n in sorted(set(res)) if is_square((n + 1)**2 + 4 * n**2)]

print res[pos]
Esempio n. 30
0
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 27 00:26:01 2018

@author: lamwa
"""

from decimal import getcontext, Decimal
import utils

RANGE = 100

getcontext().prec = 105

ans = 0

for n in range(2, RANGE):
    if utils.is_square(n):
        continue
    sqrt = str(Decimal(n) ** Decimal('0.5'))
    sqrt = sqrt.replace('.', '')
    ans += sum(int(c) for c in sqrt[ : 100])

print(ans)
Esempio n. 31
0
 def test_is_square(self):
     cases = {1:True, 2:False, 3:False, 4:True}
     for case in cases:
         result = utils.is_square(case)
         if result != cases[case]:
             self.fail("is_square failed for %s: it got %s" % (case, result))
Esempio n. 32
0
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 20 19:54:20 2018

@author: lamwa
"""

import utils
import math

a = [8, 136, 2448]

for i in range(4, 13):
    a.append(17 * a[-1] + 17 * a[-2] - a[-3])

ans = 0
for k in a:
    h1 = 2 * k - 1
    h2 = 2 * k + 1
    if utils.is_square(k**2 + h1**2):
        ans += round(math.sqrt(k**2 + h1**2))
    else:
        ans += round(math.sqrt(k**2 + h2**2))

print(ans)
Esempio n. 33
0
Created on Mon Apr 24 16:56:01 2018

@author: lamwa
"""

import utils

done = False
i = 4
while not done:
    a = i * i
    j = i - 1
    while not done and j > 0:
        c = j * j
        f = a - c
        if not utils.is_square(f):
            j -= 1
            continue
        k = j - 1
        while not done and k > 0:
            e = k * k
            d = a - e
            b = c - e
            if not utils.is_square(d) or not utils.is_square(b):
                k -= 1
                continue
            if (a + c + e) % 2 == 0:
                ans = (a + c + e) // 2
                done = True
            k -= 1
        j -= 1
Esempio n. 34
0
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 14:07:27 2018

@author: lamwa
"""

import utils

n = 3
cnt = 0

while True:
    for k in range(2, n * 2 + 1):
        if utils.is_square(k * k + n * n):
            l = max(k - n, 1)
            r = k // 2
            cnt += r - l + 1
            #print(r - l + 1)
    if cnt > 1000000:
        print(n)
        break
    n += 1
Esempio n. 35
0
def solve_eq_for(d):
    """ Solve for minimum integer x: x**2 - d*y**2 = 1 """
    x0, y0 = 0, 1
    x1, y1 = 1, 0
    n = d
    num = 0
    denom = 1
    while True:
        m = int((n**0.5 + num) / denom)
        x, y = m * x1 + x0, m * y1 + y0
        x0, y0 = x1, y1
        x1, y1 = x, y
        num, denom = denom * m - num, (n - (num - denom * m)**2) / denom

        if x * x - d * y * y == 1:
            return x

    return -1


res = None
max_x = 0

for d in range(1, 1001):
    if is_square(d): continue
    x = solve_eq_for(d)
    if x > max_x:
        max_x = x
        res = d
print(res)
Esempio n. 36
0
    l = len(expansion) - 1
    for i in range(n - 1, -1, -1):
        frac = 1 / (a1[i % l] + frac)
    return a0 + frac


def solve_diophantine_equation(D):
    n = 0
    expansion = continued_fraction(D)
    while True:
        frac = approximation(expansion, n)
        x = frac.numerator
        y = frac.denominator
        if x**2 - D * y**2 == 1:
            return x, y
            break
        n += 1


x_max = 0
D_max = 0
for D in range(1000):
    if is_square(D):
        continue
    x, y = solve_diophantine_equation(D)
    if x > x_max:
        x_max = x
        D_max = D

print D_max
Esempio n. 37
0
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 17:06:55 2018

@author: lamwa
"""

import utils

RANGE = 1000000000

f1 = list()

for i in range(1, 1000):
    if utils.is_square((3 * i + 1) * (i + 1)):
        f1.append(i)

while True:
    new = 14 * f1[-1] - f1[-2] + 8
    if 6 * new + 2 <= RANGE:
        f1.append(new)
    else:
        break

f2 = list()

for i in range(2, 1000):
    if utils.is_square((3 * i - 1) * (i - 1)):
        f2.append(i)

while True:
Esempio n. 38
0
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 25 10:56:39 2018

@author: lamwa
"""

import utils
import math

N = 120000

mapping = [set() for _ in range(N)]

for p in range(1, N):
    for q in range(1, min(p, N - p) + 1):
        b = p * p + q * q + p * q
        if utils.is_square(b):
            mapping[p].add(q)

ans_set = set()
for p in range(1, N):
    for q in mapping[p]:
        for r in mapping[q]:
            if p + q + r <= N and r in mapping[p]:
                ans_set.add(p + q + r)
ans = sum(ans_set)
print(ans)