LeetCode - Algorithms - 633. Sum of Square Numbers

Problem

633. Sum of Square Numbers

Java

1

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
class Solution {
public boolean judgeSquareSum(int c) {
if (c == 0 || c == 1)
return true;
int root = mySqrt(c);
for (int i = root; i >= 0; i--) {
int re = c - i * i;
if (isPerfectSquare(re)) {
return true;
}
}
return false;
}

private int mySqrt(int x) {
if (x == 0 || x == 1)
return x;

long start = 1, end = x, ans = 0;
while (start <= end) {
long mid = (start + end) / 2;

if (mid * mid == x)
return new Long(mid).intValue();

if (mid * mid < x) {
start = mid + 1;
ans = mid;
} else
end = mid - 1;
}
return new Long(ans).intValue();
}

private boolean isPerfectSquare(int num) {
long lo = 1, hi = num;
while (lo <= hi) {
long mid = (lo + hi) / 2;
if (mid * mid == num)
return true;
if (mid * mid > num) {
hi = mid - 1;
} else
lo = mid + 1;
}
return false;
}
}

Submission Detail

  • 124 / 124 test cases passed.
  • Runtime: 242 ms, faster than 5.54% of Java online submissions for Sum of Square Numbers.
  • Memory Usage: 37.6 MB, less than 14.48% of Java online submissions for Sum of Square Numbers.

2

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
class Solution {
public boolean judgeSquareSum(int c) {
if (c == 0 || c == 1)
return true;
for (int i = 0; i <= c/2; i++) {
int re = c - i * i;
if (re < 0)
break;
if (isPerfectSquare(re)) {
return true;
}
}
return false;
}

private boolean isPerfectSquare(int num) {
long lo = 1, hi = num;
while (lo <= hi) {
long mid = (lo + hi) / 2;
if (mid * mid == num)
return true;
if (mid * mid > num) {
hi = mid - 1;
} else
lo = mid + 1;
}
return false;
}
}

Submission Detail

  • 124 / 124 test cases passed.
  • Runtime: 206 ms, faster than 7.18% of Java online submissions for Sum of Square Numbers.
  • Memory Usage: 35.5 MB, less than 93.83% of Java online submissions for Sum of Square Numbers.

number theory

An integer greater than one can be written as a sum of two squares if and only if its prime decomposition contains no term \( p^k \), where prime \( p \equiv 3{\pmod {4}} \) and k is odd.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public boolean judgeSquareSum(int c) {
if (c == 0 || c == 1)
return true;

while (c % 2 == 0) {
c = c >> 1;
}

for (int p = 3; p * p <= c; p += 2) {
int k = 0;
if (c % p == 0) {
while (c % p == 0) {
k++;
c /= p;
}
if (p % 4 == 3 && (k & 1) == 1)
return false;
}
}
return c % 4 != 3;
}
}

Submission Detail

  • 124 / 124 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Sum of Square Numbers.
  • Memory Usage: 35.7 MB, less than 74.91% of Java online submissions for Sum of Square Numbers.

References