File tree Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Expand file tree Collapse file tree 1 file changed +65
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 633. Sum of Square Numbers
2
+ // Given a non-negative integer c, decide whether there're two integers a and b such that a2 + b2 = c.
3
+
4
+ // Example 1:
5
+ // Input: c = 5
6
+ // Output: true
7
+ // Explanation: 1 * 1 + 2 * 2 = 5
8
+ // Example 2:
9
+ // Input: c = 3
10
+ // Output: false
11
+
12
+ // Constraints:
13
+ // 0 <= c <= 231 - 1
14
+
15
+
16
+ //Approch 1 Fermat's theorem
17
+ public class Solution {
18
+ public bool JudgeSquareSum ( int c ) {
19
+ if ( c < 0 ) return false ; // Negative numbers cannot be expressed as the sum of two squares
20
+
21
+ int originalC = c ; // Store the original value of c
22
+
23
+ for ( int divisor = 2 ; divisor * divisor <= c ; divisor ++ ) {
24
+ if ( c % divisor == 0 ) {
25
+ int exponentCount = 0 ;
26
+ while ( c % divisor == 0 ) {
27
+ exponentCount ++ ;
28
+ c /= divisor ;
29
+ }
30
+ if ( divisor % 4 == 3 && exponentCount % 2 != 0 ) {
31
+ return false ;
32
+ }
33
+ }
34
+ }
35
+
36
+ // If the remaining c is a prime number of the form 4k+3, it should appear an even number of times
37
+ // If after factorization, c is still greater than 1 and of the form 4k+3, it means it's a prime factor itself
38
+ return c % 4 != 3 ;
39
+ }
40
+ }
41
+
42
+ // The code provided is a solution to check if a given number c can be expressed as the sum of two squares.
43
+ // It implements Fermat's theorem on sums of two squares, which states that a number c can be expressed as the sum of two
44
+ // squares if every prime factor of the form 4k+3 in its prime factorization appears with an even exponent.
45
+
46
+ //Approch 2 Two Sum
47
+ public class Solution {
48
+ public bool JudgeSquareSum ( int c ) {
49
+ int left = 0 ;
50
+ int right = ( int ) Math . Sqrt ( c ) ;
51
+
52
+ while ( left <= right ) {
53
+ long sum = ( long ) left * left + ( long ) right * right ;
54
+ if ( sum == c ) {
55
+ return true ;
56
+ } else if ( sum < c ) {
57
+ left ++ ;
58
+ } else {
59
+ right -- ;
60
+ }
61
+ }
62
+
63
+ return false ;
64
+ }
65
+ }
You can’t perform that action at this time.
0 commit comments