| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.SumOfSquareNumbers; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SumOfSquareNumbersBinarySearch : ISumOfSquareNumbers |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(Sqrt(c) * log c) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="c"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public bool JudgeSquareSum(int c) |
| 11 | 24 | | { |
| 14166 | 25 | | for (long a = 0; a * a <= c; a++) |
| 7080 | 26 | | { |
| 7080 | 27 | | var b = c - (int)(a * a); |
| | 28 | |
|
| 7080 | 29 | | if (BinarySearch(0, b, b)) |
| 8 | 30 | | { |
| 8 | 31 | | return true; |
| | 32 | | } |
| 7072 | 33 | | } |
| | 34 | |
|
| 3 | 35 | | return false; |
| 11 | 36 | | } |
| | 37 | |
|
| | 38 | | private static bool BinarySearch(long s, long e, int n) |
| 7080 | 39 | | { |
| 225945 | 40 | | while (true) |
| 225945 | 41 | | { |
| 225945 | 42 | | if (s > e) |
| 7072 | 43 | | { |
| 7072 | 44 | | return false; |
| | 45 | | } |
| | 46 | |
|
| 218873 | 47 | | var mid = s + ((e - s) / 2); |
| | 48 | |
|
| 218873 | 49 | | if (mid * mid == n) |
| 8 | 50 | | { |
| 8 | 51 | | return true; |
| | 52 | | } |
| | 53 | |
|
| 218865 | 54 | | if (mid * mid > n) |
| 157633 | 55 | | { |
| 157633 | 56 | | e = mid - 1; |
| | 57 | |
|
| 157633 | 58 | | continue; |
| | 59 | | } |
| | 60 | |
|
| 61232 | 61 | | s = mid + 1; |
| 61232 | 62 | | } |
| 7080 | 63 | | } |
| | 64 | | } |