Exemplo n.º 1
0
import math

side1 = 15
side2 = 17

hyptoneouse = math.isqrt((side1 * side1) + (side2 * side2))
print(hyptoneouse)

degrees1 = 180
radians1 = 2
degrees2 = 270
radians2 = 5

radians_Degrees1 = math.radians(degrees1)
radians_Degrees2 = math.radians(degrees2)
degrees_Radians1 = math.degrees(radians1)
degrees_Radians2 = math.degrees(radians2)

print(radians_Degrees1)
print(radians_Degrees2)
print(degrees_Radians1)
print(degrees_Radians2)
Exemplo n.º 2
0
def is_perfect_square(x):
    return x == math.isqrt(x) ** 2
Exemplo n.º 3
0
def loss2d(args,
           model,
           data,
           directions_path,
           results_path,
           xmin=-1,
           xmax=1,
           ymin=-1,
           ymax=1,
           mode="random"):
    """

    Args:
        args:
        model:
        data:
        directions_path:
        results_path:
        xmin:
        xmax:
        ymin:
        ymax:
        mode:

    Returns:

    """
    print("Looking for existing directions.")
    try:
        xdirection = torch.load(directions_path + "_xdirection.pt")
        ydirection = torch.load(directions_path + "_ydirection.pt")
        try:
            results = list(np.load(results_path + ".npy"))
        except IOError:
            results = list()
            np.save(results_path + ".npy", results)
    except IOError:
        print("No existing directions found, creating new ones.")
        xdirection = create_random_direction(model, norm='filter')
        ydirection = create_random_direction(model, norm='filter')
        torch.save(xdirection, directions_path + "_xdirection.pt")
        torch.save(ydirection, directions_path + "_ydirection.pt")

        results = list()
        np.save(results_path + ".npy", results)

    # Check direction similarity: 1/-1 -> perpendicular, 0 -> orthogonal
    xdir = tensorlist_to_tensor(xdirection)
    ydir = tensorlist_to_tensor(ydirection)
    print("Direction similarity:", (torch.dot(xdir, ydir) / (xdir.norm() * ydir.norm()).item()).item())
    print("Locations evaluated:", len(results))

    # Generate (random) points in xy-plane
    if mode == "random":
        samples = args.samples if args.samples % 2 != 0 else args.samples - 1
        xcoordinates = np.random.uniform(xmin, xmax, samples)
        ycoordinates = np.random.uniform(ymin, ymax, samples)
    elif mode == "grid":
        samples = isqrt(args.samples)
        samples = samples if samples % 2 != 0 else samples - 1
        xcoordinates, ycoordinates = np.mgrid[xmin:xmax:samples * 1j, ymin:ymax:samples * 1j]
        xcoordinates, ycoordinates = np.vstack([xcoordinates.ravel(), ycoordinates.ravel()])

    # Remove previously evaluated points
    if len(results) > 0:
        xcoordinates = xcoordinates[~np.isin(xcoordinates, np.array(results)[:, 0])]
        ycoordinates = ycoordinates[~np.isin(ycoordinates, np.array(results)[:, 1])]
    else:
        xcoordinates[0] = 0.
        ycoordinates[0] = 0.

    # Setup initial state and loss
    initial_state = copy.deepcopy(model.state_dict())
    criterion = CrossEntropyLoss().to(args.device)

    with torch.no_grad():
        for point, (x, y) in tqdm(enumerate(zip(xcoordinates, ycoordinates)),
                                  total=len(xcoordinates),
                                  disable=args.verbose):
            loss = 0
            correct = 0
            total = 0
            results = list(np.load(results_path + ".npy"))
            set_state(model, initial_state, directions=[xdirection, ydirection], steps=[x, y])
            data = tqdm(data, desc=f"Point [{point + 1}/{len(xcoordinates)}]", disable=not args.verbose)

            for images, labels in data:
                logits = model(images.to(args.device, non_blocking=True))
                loss += criterion(logits, labels.to(args.device, non_blocking=True)).item() * images.size(0)
                _, predicted = torch.max(logits.detach().cpu(), 1)
                correct += predicted.eq(labels).sum().item()
                total += images.size(0)

                if args.verbose:
                    data.set_postfix({'x': x,
                                      'y': y,
                                      'loss': loss / total,
                                      'acc': 100. * correct / total})

            results.append([x, y, loss / total, 100. * correct / total])
            np.save(results_path + ".npy", results)
    plot_surfaces(np.array(results), path=results_path)
Exemplo n.º 4
0
def is_square(N):
    return N == math.isqrt(N)**2  #Bản python 3.8 đổ lên mới có isqrt
Exemplo n.º 5
0
import math
N = int(input())
ans = 0
cnt = {}
for i in range(2, math.isqrt(N) + 1):
    if N % i != 0: continue
    cnt[i] = 0
    while N % i == 0:
        cnt[i] += 1
        N //= i
if N != 1:
    cnt[N] = 1
ans = 0
for k, v in cnt.items():
    cnt = 1
    total = v
    while total >= cnt:
        ans += 1
        total -= cnt
        cnt += 1
print(ans)
Exemplo n.º 6
0
# overflow Error
# from math import sqrt
# print(sqrt(int(input())))

# overflow Error
# N = int(input()) # 800 자리
# print((int(input())**0.5))

# 내가 푼 방식
from math import isqrt
print(isqrt(int(input())))

# 이분탐색
n = int(input())
low = 1
high = n

while 1:
    mid = (low + high) // 2
    if mid**2 == n:
        print(mid)
        break
    elif mid**2 > n:
        high = mid - 1
    elif mid**2 < n:
        low = mid + 1
def is_prime(p):
    for i in range(2, math.isqrt(p)):
        if p % i == 0:
            return False
    return True
Exemplo n.º 8
0
    r_1 = r - 1
    while r_1 % 2 == 0:
        r_1 = r_1 // 2
        r1twoexp += 1

    print("USING r1twoexp=%d" % r1twoexp)
    invr = invert(r_1, 2**2050)
    sum_p_q = ((somme * invr) % (2**2050)) // (2**r1twoexp)

    print("p+q [%d] = %s" % (sum_p_q.bit_length(), sum_p_q))
    if not ONLINE:
        assert sum_p_q == testing_p + testing_q

    prod_p_q = pq
    delta = (sum_p_q**2) - 4 * prod_p_q
    sqrt_delta = math.isqrt(delta)
    if sqrt_delta * sqrt_delta != delta:
        raise ValueError(
            "* ... Unable to find a square root for the discriminant of the polynom"
        )

    p = (sum_p_q - sqrt_delta) // 2
    q = (sum_p_q + sqrt_delta) // 2

    print("Found:\n  p=%d\n  q=%d" % (p, q))
    assert N == p * q * r

    real_phi = (p - 1) * (q - 1) * (r - 1)
    d = invert(e, real_phi)

    assert real_phi % (2**2050) == phi
Exemplo n.º 9
0
# issue 1308
assert math.factorial(
    69
) == 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000

# issue 1312
assert math.comb(5, 2) == 10
assert math.comb(69, 12) == 8815083648488

assert math.perm(69, 12) == 4222439171759589580800

x = math.prod(range(1, 33))
assert x == 263130836933693530167218012160000000

assert math.isqrt(x) == 512962802680363491

y = math.factorial(69)
assert math.isqrt(y) == 13081378078327271990661335578798848847474255303826

assert math.dist([1, 2, 3], [4, 5, 6]) == 5.196152422706632

# issue 1314
assert math.gcd(pow(2, 53) - 2, 2) == 2
assert math.gcd(pow(2, 53) - 1, 2) == 1

# issue 1397
assert math.dist((1.0, 1.0), (1.5, 0.0)) == 1.118033988749895


# issue 1401
Exemplo n.º 10
0
 def bulbSwitch(self, n: int) -> int:
     return isqrt(n)
def find_next_square(sq):
    # Return the next square if sq is a square, -1 otherwise
    int_sqrt = math.isqrt(sq)
    if int_sqrt**2 == sq:  # if in_sqrt is root_square of sq
        return (int_sqrt + 1)**2  # rerutn square value of (int_sqrt+1)
    return -1
Exemplo n.º 12
0
def sqrtTime(N):
    sum = 0
    for number in range(math.isqrt(N)):
        sum += number
    print(sum)
Exemplo n.º 13
0
from math import gcd, isqrt

A, B = map(int, input().split())

X = gcd(A, B)

if isqrt(X) * isqrt(X) == X:
    print('Odd')
else:
    print('Even')
Exemplo n.º 14
0
# On importe une fonction nous donnant la partie entière d'une racine
from math import isqrt

# On demande n et prépare une liste vide
n = int(input("Entrez n : "))
nombrePremiers = []

# Pour chaque nombre entre 2 et √n + 1
for i in range(2, isqrt(n) + 1):
    # On ajoute un set (liste non organisée) à la liste des nombres premiers
    nombrePremiers.append(set({}))

    # Pour chaque nombre de 2 à n
    for j in range(2, n + 1):
        # Si le nombre est égal à ce que l'on teste, ou non divisible
        if j % i != 0 or j == i:
            # On l'ajoute au set (on fait l'union entre le set principal et un set contenant uniquement ce nombre)
            nombrePremiers[i - 2] = nombrePremiers[i - 2] | {j}

# On a maintenant une liste contenant plusieurs sets correspondant chacun aux nombres premiers à i

# Maintenant, on utilise une boucle pour faire l'intersection de tout ces sets
for i in range(1, len(nombrePremiers)):
    # On redéfinit donc le premier set comme l'intersection entre lui même et le set suivant
    nombrePremiers[0] = nombrePremiers[0] & nombrePremiers[i]

# On fini par afficher le premier set (trié), contenant l'intersection de tout les sets
print(sorted(nombrePremiers[0]))
Exemplo n.º 15
0
import math
import random
print(math.pow(10, 2))

print(math.sqrt(64))  #Raiz cuadrada de un Number.

print(math.isqrt(64))  #Isqrt cuadrada de negativo 64.
print(math.sin(90))  #Seno de 90.
print(math.cos(90))  #Coseno de 90.
print(math.tan(90))  #Tangente de 90.
print(math.factorial(5))  #5*4*3*2*1

print(random.randint(1, 11))  #Aleatorio entre 1 y 10.

lista = [1, "hola", "randomlist", "rosario", "like"]

print(random.choice(lista))
Exemplo n.º 16
0
def factors(n):
    factors = {1, n}
    for i in range(2, isqrt(n) + 1):
        if n % i == 0:
            factors |= {i, n / i}
    return factors
Exemplo n.º 17
0
 def __init__(self, tiles):
     self.tiles = tiles
     self.size = math.isqrt(len(tiles))
     self.tiles_by_edge = self.__tile_index()
Exemplo n.º 18
0
#         print(0)
#     exit()
# for i in range(min_x,max_x+1):
#     if abs(r)==abs(x-i) and int(y)==y:
#         ans+=1
#     else:
#         rt=sqrt(r*r-(x-i)*(x-i))
#         max_y=int(y+rt)
#         min_y=int(-((y-rt)//-1))
#         if max_y>=min_y:
#             ans+=int(max_y-min_y+1)
# print(ans)
# x,y,r=map(lambda x:int(float(x)*z),input().split())
from decimal import Decimal
from math import isqrt

z = 10000
x, y, r = map(lambda x: int(Decimal(x) * z), input().split())
max_x = (x + r) // z
min_x = (x - r) // z
ans = 0
for i in range(min_x, max_x + 2):
    yy = r**2 - (i * z - x)**2
    if yy < 0:
        continue
    rt = isqrt(yy)
    max_y = (y + rt) // z
    min_y = (y - rt + z - 1) // z
    ans += max_y - min_y + 1
print(ans)
Exemplo n.º 19
0
"""
--- Day 20: Jurassic Jigsaw ---
https://adventofcode.com/2020/day/20
"""
import math
import re

import aocd
import numpy as np

DATA = {
    int(i):
    np.array([[c == '#' for c in line] for line in tile_raw.splitlines()])
    for i, tile_raw, _ in re.findall(r"Tile (\d+):\s+(([.#]+\n?)+)", aocd.data)
}
N = math.isqrt(len(DATA))

# Part One


def transform(m):
    for k in range(4):
        yield np.rot90(m, k)
    m = np.flipud(m)
    for k in range(4):
        yield np.rot90(m, k)


# all tiles in all orientations
options = {i: [t for t in transform(m)] for i, m in DATA.items()}
Exemplo n.º 20
0
def isComposite(num):
    for i in range(3, isqrt(num)):
        if (num % i == 0):
            return True
    primes.append(num)
    return False
Exemplo n.º 21
0
def prime3(n):  # n là số nguyên > 1
    for i in range(2, math.isqrt(n) + 1):
        if n % i == 0:
            return False  # n có ước > 1 và <= căn n
    return True
Exemplo n.º 22
0
import math

a = 4
b = 5
c = 1

r1 = (a+b)/2
r2 = (-b+math.isqrt(b**2-4*a*c))/(2*a)
r3 = (3*a + 2*b)/(a+b)

print(f"Resposta 01: {r1:.2f}, Resposta 02: {r2:.2f}, Resposta 03: {r3:.2f}")
def is_square(num):
  return num == math.isqrt(num) ** 2
Exemplo n.º 24
0
import math
n=int(input("enter the lower bound:"))
m=int(input("enter the upper bound:"))
list=[]
for i in range(n,m+1):
    count=flag=0
    num=str(i)
    for j in num:
        count=count+1
        if int(j)%2!=0:
            flag=1
    if (count==4 and int(num)==(math.isqrt(int(num))**2) and flag==0):
        list.append(int(num))
if(len(list)==0):
    print("list is empty")
else:
    print("resultant list is:",list)
Exemplo n.º 25
0
def is_square(i: int) -> bool:
    return i == math.isqrt(i)**2
Exemplo n.º 26
0
 def is_square(self, val: int) -> bool:
     return math.isqrt(val) == math.sqrt(val)
Exemplo n.º 27
0
 def isqrt(self):
     import math
     return AdvInteger(math.isqrt(self))
Exemplo n.º 28
0
import math
minNum = 1
maxNum = 1000000000
primeList = []


def resetDoc():
    doc = open("primeNumbers.txt", "w")
    doc.write("")
    doc.close


def addLine(num):
    doc = open("primeNumbers.txt", "a")
    doc.write(str(num) + "\n")
    doc.close


resetDoc()
if minNum == 1:
    minNum = 2
for number in range(minNum, maxNum + 1):
    prime = True
    for divisor in range(2, (round(math.isqrt(number) + 1))):
        if number % divisor == 0:
            prime = False
    if prime == True:
        primeList.append(number)
        addLine(number)
print(primeList)
Exemplo n.º 29
0
def p2():
    return sum(
        run(vx, vy) for vx in range(isqrt(TARGET.xmin), TARGET.xmax + 1)
        for vy in range(TARGET.ymin,
                        abs(TARGET.ymin) + 1))
Exemplo n.º 30
0
def get_valid_orientations(total_tile_count, border_orientations_per_tile):
    dimension = math.isqrt(total_tile_count)
    tile_id_with_index = [[''] * dimension for _ in range(dimension)]
    return find_valid_orientation_of_tiles(tile_id_with_index,
                                           border_orientations_per_tile,
                                           dimension)