给定一个正整数n(n>0),请编写一个函数,求出并返回最小的一个平方数N(N>0),满足 n + N 的值恰好也是一个平方数。如果没有符合条件的数,则返回-1。
示例:
输入:13,返回:36。因为13+62 =72 。
题目难度:中等
题目来源:codewars: Simple square numbers
def solution(n: int) -> int:
# your code
assert solution(13) == 36
assert solution(3) == 1
assert solution(12) == 4
assert solution(4) == -1
阈值设置为1-100000
def solution(n: int) -> int:
i = 1
while True:
if pow(n + i ** 2, 1.0 / 2).is_integer():
return i ** 2
if i > 100000:
return -1
i += 1
assert solution(13) == 36
assert solution(3) == 1
assert solution(12) == 4
assert solution(4) == -1
Kawi
2021 年12 月 9 日 02:53
5
import math
def solution(n: int) -> int:
i = 1
while True:
num = math.sqrt(pow(i, 2) + n) % 1
if num == 0:
return i ** 2
if (i + 1) ** 2 - i ** 2 > n:
return -1
i += 1
if __name__ == '__main__':
assert solution(13) == 36
assert solution(3) == 1
assert solution(12) == 4
assert solution(4) == -1
def solution(n: int) -> int:
N = 0
while True:
N+=1
if pow((n+pow(N,2)),0.5).is_integer():
return N**2
if N>100:
return -1
assert solution(13)==36
assert solution(3)==1
assert solution(12)==4
assert solution(4)==-1
Mooii
2021 年12 月 9 日 04:58
7
def solution(n: int) -> int:
i = 1
while True:
num = math.sqrt(n + pow(i,2))
if num % 1 == 0:
return i ** 2
if i > 1000:
return -1
i = i + 1
assert solution(13) == 36
assert solution(3) == 1
assert solution(12) == 4
assert solution(4) == -1
def solution(n):
for x in range(1,100000):
for j in range(x,100000):
if n+x**2==j**2:
return x**2
return -1
assert solution(13) == 36
assert solution(3) == 1
assert solution(12) == 4
assert solution(4) == -1
import math
def solution(n: int) -> int:
# your code
num = 1
while True:
a = math.sqrt(n + num ** 2)
if a == int(a):
return num ** 2
elif n < (num + 1) ** 2 - num ** 2:
return -1
else:
num += 1
assert solution(13) == 36
assert solution(3) == 1
assert solution(12) == 4
assert solution(4) == -1
standy
(standy)
2021 年12 月 9 日 07:40
12
import math
def solution(n: int) -> int:
result = 1
while 1:
if math.sqrt(n + result **2) % 1 == 0:
return result * result
elif (result + 1) ** 2 > (result ** 2 + n):
return -1
else:
result += 1
1 个赞
Huis
2021 年12 月 9 日 14:53
13
def solution(n: int) -> int:
for i in range(1,n):
total = n + i**2
for j in range(i+1,n):
if j**2 == total:
return i**2
elif j**2 > total: break
return -1
import math
def solution(n: int) -> int:
for i in range(1,n):
if math.sqrt(n + i**2)%1 == 0: return i**2
return -1
def solution(n: int) -> int:
for j in range(1,n):
for i in range(3,n+1):
if n == i*j and (i-j)%2 == 0:
print(i,j,int((i-j)/2)**2)
return int((i-j)/2)**2
return -1
assert solution(13) == 36
assert solution(3) == 1
assert solution(12) == 4
assert solution(4) == -1
def solution(n: int) -> int:
for x in range(1, 10000):
# if int((n + x ** 2) ** 0.5) - (n + x ** 2) ** 0.5 == 0:
if ((n + x ** 2) ** 0.5).is_integer():
return x ** 2
else:
return -1
assert solution(13) == 36
assert solution(3) == 1
assert solution(12) == 4
assert solution(4) == -1