| | 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.SumMultiples; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class SumMultiplesMath : ISumMultiples |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(1) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="n"></param> |
| | 22 | | /// <returns></returns> |
| | 23 | | public int SumOfMultiples(int n) |
| 3 | 24 | | { |
| 3 | 25 | | var sum = 0; |
| | 26 | |
|
| 3 | 27 | | sum += SumDivisibleBy(n, 3); |
| 3 | 28 | | sum += SumDivisibleBy(n, 5); |
| 3 | 29 | | sum += SumDivisibleBy(n, 7); |
| | 30 | |
|
| 3 | 31 | | sum -= SumDivisibleBy(n, 3 * 5); |
| 3 | 32 | | sum -= SumDivisibleBy(n, 3 * 7); |
| 3 | 33 | | sum -= SumDivisibleBy(n, 5 * 7); |
| | 34 | |
|
| 3 | 35 | | sum += SumDivisibleBy(n, 3 * 5 * 7); |
| | 36 | |
|
| 3 | 37 | | return sum; |
| 3 | 38 | | } |
| | 39 | |
|
| | 40 | | private static int SumDivisibleBy(int n, int d) |
| 21 | 41 | | { |
| 21 | 42 | | var p = n / d; |
| | 43 | |
|
| 21 | 44 | | return d * p * (p + 1) / 2; |
| 21 | 45 | | } |
| | 46 | | } |