| | 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.Sqrt; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SqrtNewtonsMethod : ISqrt |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(log x) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="x"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int MySqrt(int x) |
| 9 | 24 | | { |
| 9 | 25 | | if (x is 0 or 1) |
| 2 | 26 | | { |
| 2 | 27 | | return x; |
| | 28 | | } |
| | 29 | |
|
| 7 | 30 | | var xOld = x / 2.0; |
| | 31 | |
|
| 29 | 32 | | while (true) |
| 29 | 33 | | { |
| 29 | 34 | | var xNew = (xOld + (x / xOld)) / 2; |
| | 35 | |
|
| 29 | 36 | | if (Math.Abs(xNew - xOld) < 1) |
| 7 | 37 | | { |
| 7 | 38 | | return (int)xNew; |
| | 39 | | } |
| | 40 | |
|
| 22 | 41 | | xOld = xNew; |
| 22 | 42 | | } |
| 9 | 43 | | } |
| | 44 | | } |