1922. Count Good Numbers #1554
-
Topics: A digit string is good if the digits (0-indexed) at even indices are even and the digits at odd indices are prime (
Given an integer A digit string is a string consisting of digits Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to count the number of good digit strings of length Approach
Let's implement this solution in PHP: 1922. Count Good Numbers <?php
/**
* @param Integer $n
* @return Integer
*/
function countGoodNumbers($n) {
$mod = 1000000007;
$even_count = (int)(($n + 1) / 2);
$odd_count = (int)($n / 2);
$even_power = pow_mod(5, $even_count, $mod);
$odd_power = pow_mod(4, $odd_count, $mod);
return (int)(($even_power * $odd_power) % $mod);
}
/**
* @param $base
* @param $exponent
* @param $mod
* @return int
*/
function pow_mod($base, $exponent, $mod) {
$result = 1;
$base = $base % $mod;
while ($exponent > 0) {
if ($exponent % 2 == 1) {
$result = ($result * $base) % $mod;
}
$base = ($base * $base) % $mod;
$exponent = (int)($exponent / 2);
}
return $result;
}
//Test cases
echo countGoodNumbers(1) . "\n"; // Output: 5
echo countGoodNumbers(4) . "\n"; // Output: 400
echo countGoodNumbers(50) . "\n"; // Output: 564908303
?> Explanation:
This approach ensures that we efficiently compute the result even for the upper constraint of n = 1015 by leveraging modular arithmetic and efficient exponentiation. |
Beta Was this translation helpful? Give feedback.
We need to count the number of good digit strings of length
n
where a digit string is considered good if the digits at even indices are even and the digits at odd indices are prime numbers (2, 3, 5, or 7). The result should be returned modulo 109 + 7.Approach
n
, determine the number of even and odd indices. Even indices are 0, 2, 4, ..., and odd indices are 1, 3, 5, ... . The count of even indices is (n + 1) // 2 and the count of odd indices is n // 2.