| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 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.FourDivisors; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class FourDivisorsIterativeDivision : IFourDivisors |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(n * sqrt(m)) |
| | | 19 | | /// Space complexity - O(1) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="nums"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int SumFourDivisors(int[] nums) |
| | 3 | 24 | | { |
| | 3 | 25 | | var result = 0; |
| | | 26 | | |
| | 26 | 27 | | for (var i = 0; i < nums.Length; i++) |
| | 10 | 28 | | { |
| | 10 | 29 | | var num = nums[i]; |
| | | 30 | | |
| | 10 | 31 | | result += GetSum(num); |
| | 10 | 32 | | } |
| | | 33 | | |
| | 3 | 34 | | return result; |
| | 3 | 35 | | } |
| | | 36 | | |
| | | 37 | | private static int GetSum(int num) |
| | 10 | 38 | | { |
| | 10 | 39 | | var count = 1; |
| | 10 | 40 | | var sum = num + 1; |
| | | 41 | | |
| | 10 | 42 | | var divisor = 2; |
| | | 43 | | |
| | 23 | 44 | | while (divisor * divisor <= num) |
| | 13 | 45 | | { |
| | 13 | 46 | | if (num % divisor == 0) |
| | 5 | 47 | | { |
| | 5 | 48 | | var pairedDivisor = num / divisor; |
| | | 49 | | |
| | 5 | 50 | | sum += divisor; |
| | | 51 | | |
| | 5 | 52 | | count++; |
| | | 53 | | |
| | 5 | 54 | | if (pairedDivisor != divisor) |
| | 3 | 55 | | { |
| | 3 | 56 | | sum += pairedDivisor; |
| | | 57 | | |
| | 3 | 58 | | count++; |
| | 3 | 59 | | } |
| | | 60 | | |
| | 5 | 61 | | if (count > 3) |
| | 0 | 62 | | { |
| | 0 | 63 | | return 0; |
| | | 64 | | } |
| | 5 | 65 | | } |
| | | 66 | | |
| | 13 | 67 | | divisor++; |
| | 13 | 68 | | } |
| | | 69 | | |
| | 10 | 70 | | return count < 3 ? 0 : sum; |
| | 10 | 71 | | } |
| | | 72 | | } |