Count of N-digit Numbers having Sum of even and odd positioned digits divisible by given numbers

Given integers A, B, and N, the task is to find the total number of N-digit numbers whose sum of digits at even positions and odd positions are divisible by A and B respectively.

Examples:

Input: N = 2, A = 2, B = 5
Output: 5
Explanation:
The only 2-digit numbers {50, 52, 54, 56, 58} with sum of odd-positioned digits equal to 5 and even-positioned digits {0, 2, 4, 6, 8} divisible by 2.

Input: N = 2, A = 5, B = 3
Output: 6
Explanation:
The only two digit numbers {30, 35, 60, 65, 90, 95} have odd digits {3, 6 or 9}, which is divisible by 3 and even digits {0 or 5}, which is divisible by 5.

Naive Approach: The simplest approach to solve this problem is to iterate over all possible N-digit numbers and for each number, check if the sum of digits at even positions is divisible by A and the sum of digits at odd positions is divisible by B or not. If found to be true, increase count



Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate and
// return the reverse of the number
long reverse(long num)
{
    long rev = 0;
    while (num > 0)
    {
        int r = (int)(num % 10);
        rev = rev * 10 + r;
        num /= 10;
    }
    return rev;
}
 
// Function to calculate the total
// count of N-digit numbers satisfying
// the necessary conditions
long count(int N, int A, int B)
{
     
    // Initialize two variables
    long l = (long)pow(10, N - 1),
         r = (long)pow(10, N) - 1;
 
    if (l == 1)
        l = 0;
 
    long ans = 0;
 
    for(long i = l; i <= r; i++)
    {
        int even_sum = 0, odd_sum = 0;
        long itr = 0, num = reverse(i);
 
        // Calculate the sum of odd
        // and even positions
        while (num > 0)
        {
            if (itr % 2 == 0)
                odd_sum += num % 10;
            else
                even_sum += num % 10;
                 
            num /= 10;
            itr++;
        }
         
        // Check for divisibility
        if (even_sum % A == 0 &&
             odd_sum % B == 0)
            ans++;
    }
 
    // Return the answer
    return ans;
}
 
// Driver Code
int main()
{
    int N = 2, A = 5, B = 3;
    cout << (count(N, A, B));
 
}
 
// This code is contributed by 29AjayKumar
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
class GFG {
 
    // Function to calculate and
    // return the reverse of the number
    public static long reverse(long num)
    {
        long rev = 0;
        while (num > 0) {
            int r = (int)(num % 10);
            rev = rev * 10 + r;
            num /= 10;
        }
        return rev;
    }
 
    // Function to calculate the total
    // count of N-digit numbers satisfying
    // the necessary conditions
    public static long count(int N, int A, int B)
    {
        // Initialize two variables
        long l = (long)Math.pow(10, N - 1),
             r = (long)Math.pow(10, N) - 1;
 
        if (l == 1)
            l = 0;
 
        long ans = 0;
 
        for (long i = l; i <= r; i++) {
            int even_sum = 0, odd_sum = 0;
            long itr = 0, num = reverse(i);
 
            // Calculate the sum of odd
            // and even positions
            while (num > 0) {
 
                if (itr % 2 == 0)
                    odd_sum += num % 10;
                else
                    even_sum += num % 10;
                num /= 10;
                itr++;
            }
            // Check for divisibility
            if (even_sum % A == 0
                && odd_sum % B == 0)
                ans++;
        }
 
        // Return the answer
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int N = 2, A = 5, B = 3;
        System.out.println(count(N, A, B));
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 Program to implement
# the above approach
 
# Function to calculate and
# return the reverse of the number
def reverse(num):
     
    rev = 0;
    while (num > 0):
        r = int(num % 10);
        rev = rev * 10 + r;
        num = num // 10;
     
    return rev;
 
# Function to calculate the total
# count of N-digit numbers satisfying
# the necessary conditions
def count(N, A, B):
     
    # Initialize two variables
    l = int(pow(10, N - 1));
    r = int(pow(10, N) - 1);
    if (l == 1):
        l = 0;
 
    ans = 0;
 
    for i in range(l, r + 1):
        even_sum = 0;
        odd_sum = 0;
        itr = 0;
        num = reverse(i);
         
        # Calculate the sum of odd
        # and even positions
        while (num > 0):
 
            if (itr % 2 == 0):
                odd_sum += num % 10;
            else:
                even_sum += num % 10;
            num = num // 10;
            itr += 1;
         
        # Check for divisibility
        if (even_sum % A == 0 and
            odd_sum % B == 0):
            ans += 1;
 
    # Return the answer
    return ans;
 
# Driver Code
if __name__ == '__main__':
     
    N = 2;
    A = 5;
    B = 3;
    print(count(N, A, B));
 
# This code is contributed by gauravrajput1
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to calculate and
// return the reverse of the number
public static long reverse(long num)
{
    long rev = 0;
    while (num > 0)
    {
        int r = (int)(num % 10);
        rev = rev * 10 + r;
        num /= 10;
    }
    return rev;
}
 
// Function to calculate the total
// count of N-digit numbers satisfying
// the necessary conditions
public static long count(int N, int A, int B)
{
     
    // Initialize two variables
    long l = (long)Math.Pow(10, N - 1),
         r = (long)Math.Pow(10, N) - 1;
 
    if (l == 1)
        l = 0;
 
    long ans = 0;
 
    for(long i = l; i <= r; i++)
    {
        int even_sum = 0, odd_sum = 0;
        long itr = 0, num = reverse(i);
 
        // Calculate the sum of odd
        // and even positions
        while (num > 0)
        {
            if (itr % 2 == 0)
                odd_sum += (int)num % 10;
            else
                even_sum += (int)num % 10;
                 
            num /= 10;
            itr++;
        }
         
        // Check for divisibility
        if (even_sum % A == 0 &&
             odd_sum % B == 0)
            ans++;
    }
 
    // Return the answer
    return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 2, A = 5, B = 3;
    Console.WriteLine(count(N, A, B));
}
}
 
// This code is contributed by 29AjayKumar
chevron_right

Output: 
6





 

Time Complexity: O((10N – 10N – 1 – 1) * N) 
Auxiliary Space: O(N) 

Efficient Approach: To optimize the above approach, use the concept of Dynamic Programming.

Follow the steps below to solve the problem:  

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to calculate the total
// count of N-digit numbers such
// that the sum of digits at even
// positions and odd positions are
// divisible by A and B respectively
long count(int N, int A, int B)
{
    // For single digit numbers
    if (N == 1)
    {
        return 9 / B + 1;
    }
 
    // Largest possible number
    int max_sum = 9 * N;
 
    // Count of possible odd digits
    int odd_count = N / 2 + N % 2;
 
    // Count of possible even digits
    int even_count = N - odd_count;
 
    // Calculate total count of sequences of
    // length even_count with sum divisible
    // by A where first digit can be zero
    long dp[even_count][max_sum + 1] = {0};
    for (int i = 0; i <= 9; i++)
        dp[0][i % A]++;
 
    for (int i = 1; i < even_count; i++)
    {
        for (int j = 0; j <= 9; j++)
        {
            for (int k = 0; k <= max_sum; k++)
            {
                if (dp[i - 1][k] > 0)
                    dp[i][(j + k) % A] += dp[i - 1][k];
            }
        }
    }
 
    // Calculate total count of sequences of
    // length odd_count with sum divisible
    // by B where cannot be zero
    long dp1[odd_count][max_sum + 1] = {0};
    for (int i = 1; i <= 9; i++)
        dp1[0][i % B]++;
 
    for (int i = 1; i < odd_count; i++)
    {
        for (int j = 0; j <= 9; j++)
        {
            for (int k = 0; k <= max_sum; k++)
            {
                if (dp1[i - 1][k] > 0)
                    dp1[i][(j + k) % B] += dp1[i - 1][k];
            }
        }
    }
 
    // Return their product as answer
    return dp[even_count - 1][0] * dp1[odd_count - 1][0];
}
 
// Driver Code
int main()
{
    int N = 2, A = 2, B = 5;
    cout << count(N, A, B);
}
 
// This code is contributed by Rajput-Ji
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to implement
// the above approach
class GFG {
 
    // Function to calculate the total
    // count of N-digit numbers such
    // that the sum of digits at even
    // positions and odd positions are
    // divisible by A and B respectively
    public static long count(int N, int A, int B)
    {
        // For single digit numbers
        if (N == 1) {
            return 9 / B + 1;
        }
 
        // Largest possible number
        int max_sum = 9 * N;
 
        // Count of possible odd digits
        int odd_count = N / 2 + N % 2;
 
        // Count of possible even digits
        int even_count = N - odd_count;
 
        // Calculate total count of sequences of
        // length even_count with sum divisible
        // by A where first digit can be zero
        long dp[][]
            = new long[even_count][max_sum + 1];
        for (int i = 0; i <= 9; i++)
            dp[0][i % A]++;
 
        for (int i = 1; i < even_count; i++) {
            for (int j = 0; j <= 9; j++) {
                for (int k = 0; k <= max_sum; k++) {
                    if (dp[i - 1][k] > 0)
                        dp[i][(j + k) % A]
                            += dp[i - 1][k];
                }
            }
        }
 
        // Calculate total count of sequences of
        // length odd_count with sum divisible
        // by B where cannot be zero
        long dp1[][]
            = new long[odd_count][max_sum + 1];
        for (int i = 1; i <= 9; i++)
            dp1[0][i % B]++;
 
        for (int i = 1; i < odd_count; i++) {
            for (int j = 0; j <= 9; j++) {
                for (int k = 0; k <= max_sum; k++) {
                    if (dp1[i - 1][k] > 0)
                        dp1[i][(j + k) % B]
                            += dp1[i - 1][k];
                }
            }
        }
 
        // Return their product as answer
        return dp[even_count - 1][0]
            * dp1[odd_count - 1][0];
    }
    // Driver Code
    public static void main(String[] args)
    {
        int N = 2, A = 2, B = 5;
        System.out.println(count(N, A, B));
    }
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 Program to implement
# the above approach
 
# Function to calculate the total
# count of N-digit numbers such
# that the sum of digits at even
# positions and odd positions are
# divisible by A and B respectively
def count(N, A, B):
 
    # For single digit numbers
    if (N == 1):
        return 9 // B + 1
   
    # Largest possible number
    max_sum = 9 * N
 
    # Count of possible odd digits
    odd_count = N // 2 + N % 2
 
    # Count of possible even digits
    even_count = N - odd_count
 
    # Calculate total count of
    # sequences of length even_count
    # with sum divisible by A where
    # first digit can be zero
    dp = [[0 for x in range (max_sum + 1)]
             for y in range (even_count)]
     
    for i in range(10):
        dp[0][i % A] += 1
 
    for i in range (1, even_count):
        for j in range (10):
            for k in range (max_sum + 1):
                if (dp[i - 1][k] > 0):
                    dp[i][(j + k) % A] += dp[i - 1][k]
 
    # Calculate total count of sequences of
    # length odd_count with sum divisible
    # by B where cannot be zero
    dp1 = [[0 for x in range (max_sum)]
              for y in range (odd_count)]
    for i in range (1, 10):
        dp1[0][i % B] += 1
 
    for i in range (1, odd_count): 
        for j in range (10):      
            for k in range (max_sum + 1):
                if (dp1[i - 1][k] > 0):
                    dp1[i][(j + k) % B] += dp1[i - 1][k]
            
    # Return their product as answer
    return dp[even_count - 1][0] * dp1[odd_count - 1][0]
 
# Driver Code
if __name__ == "__main__":
   
    N = 2
    A = 2
    B = 5
    print (count(N, A, B))
 
# This code is contributed by Chitranayal
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
 
class GFG{
 
// Function to calculate the total
// count of N-digit numbers such
// that the sum of digits at even
// positions and odd positions are
// divisible by A and B respectively
public static long count(int N, int A, int B)
{
     
    // For single digit numbers
    if (N == 1)
    {
        return 9 / B + 1;
    }
 
    // Largest possible number
    int max_sum = 9 * N;
 
    // Count of possible odd digits
    int odd_count = N / 2 + N % 2;
 
    // Count of possible even digits
    int even_count = N - odd_count;
 
    // Calculate total count of sequences of
    // length even_count with sum divisible
    // by A where first digit can be zero
    long [,]dp = new long[even_count, max_sum + 1];
    for(int i = 0; i <= 9; i++)
        dp[0, i % A]++;
 
    for(int i = 1; i < even_count; i++)
    {
        for(int j = 0; j <= 9; j++)
        {
            for(int k = 0; k <= max_sum; k++)
            {
                if (dp[i - 1, k] > 0)
                    dp[i, (j + k) % A] += dp[i - 1, k];
            }
        }
    }
 
    // Calculate total count of sequences of
    // length odd_count with sum divisible
    // by B where cannot be zero
    long [,]dp1 = new long[odd_count, max_sum + 1];
    for(int i = 1; i <= 9; i++)
        dp1[0, i % B]++;
 
    for(int i = 1; i < odd_count; i++)
    {
        for(int j = 0; j <= 9; j++)
        {
            for(int k = 0; k <= max_sum; k++)
            {
                if (dp1[i - 1, k] > 0)
                    dp1[i, (j + k) % B] += dp1[i - 1, k];
            }
        }
    }
     
    // Return their product as answer
    return dp[even_count - 1, 0] *
           dp1[odd_count - 1, 0];
}
 
// Driver Code
public static void Main(String[] args)
{
    int N = 2, A = 2, B = 5;
     
    Console.WriteLine(count(N, A, B));
}
}
 
// This code is contributed by 29AjayKumar
chevron_right

Output: 
5





 

Time Complexity: O(N2)
Auxiliary Space: O(N2)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :