forked from keon/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnext_perfect_square.py
More file actions
54 lines (40 loc) · 1.11 KB
/
next_perfect_square.py
File metadata and controls
54 lines (40 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
"""
Next Perfect Square
Given a number, find the next perfect square if the input is itself a perfect
square. Otherwise, return -1.
Reference: https://en.wikipedia.org/wiki/Square_number
Complexity:
Time: O(1)
Space: O(1)
"""
from __future__ import annotations
def find_next_square(sq: float) -> float:
"""Find the next perfect square after sq.
Args:
sq: A non-negative number to check.
Returns:
The next perfect square if sq is a perfect square, otherwise -1.
Examples:
>>> find_next_square(121)
144
>>> find_next_square(10)
-1
"""
root = sq**0.5
if root.is_integer():
return (root + 1) ** 2
return -1
def find_next_square2(sq: float) -> float:
"""Find the next perfect square using modulo check.
Args:
sq: A non-negative number to check.
Returns:
The next perfect square if sq is a perfect square, otherwise -1.
Examples:
>>> find_next_square2(121)
144
>>> find_next_square2(10)
-1
"""
root = sq**0.5
return -1 if root % 1 else (root + 1) ** 2