| | 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.CountGoodNumbers; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class CountGoodNumbersFastExponentiation : ICountGoodNumbers |
| | 16 | | { |
| | 17 | | private const int Mod = 1_000_000_007; |
| | 18 | |
|
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(log n) |
| | 21 | | /// Space complexity - O(1) |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="n"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public int CountGoodNumbers(long n) |
| 9 | 26 | | { |
| 9 | 27 | | var evenPositions = n / 2; |
| 9 | 28 | | var oddPositions = n - evenPositions; |
| | 29 | |
|
| 9 | 30 | | return (int)(ModPow(5, oddPositions) * ModPow(4, evenPositions) % Mod); |
| 9 | 31 | | } |
| | 32 | |
|
| | 33 | | private static long ModPow(long value, long exponent) |
| 18 | 34 | | { |
| 18 | 35 | | long result = 1; |
| | 36 | |
|
| 57 | 37 | | while (exponent > 0) |
| 39 | 38 | | { |
| 39 | 39 | | if (exponent % 2 == 1) |
| 25 | 40 | | { |
| 25 | 41 | | result = result * value % Mod; |
| 25 | 42 | | } |
| | 43 | |
|
| 39 | 44 | | value = value * value % Mod; |
| | 45 | |
|
| 39 | 46 | | exponent /= 2; |
| 39 | 47 | | } |
| | 48 | |
|
| 18 | 49 | | return result; |
| 18 | 50 | | } |
| | 51 | | } |