# N digit numbers divisible by 5 formed from the M digits in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

We have given a number N along with an array of M digits. Our job is to find the number of n digit numbers formed from the given M digits that are divisible by 5.

Let's see some examples to understand the problem inputs and outputs.

In −

N = 2
M = 3
arr = {5, 6, 3}

Out −

2

There are 2 N digit numbers 35 and 65 possible that are divisible by 5. Let's see another example.

Input −

N = 1
M = 7
arr = {2, 3, 4, 5, 6, 7, 8}

Output −

1

There is only 1 number with 1 digit in the given array that is divisible by 5. So, our task is to find the number of numbers that can be formed from the given number with N digits that are divisible by 5.

The number must end with the digits 0 or 5 to be divisible by 5. Let's see the algorithm

## Algorithm

• Check for the 0 and 5 in the given array. 2. If there are both 0 and 5 then there are two ways to place a digit in the units place. Otherwise, there will be a single way to place a digit.
• Initialise the count to 2.
• Now, the remaining place can have m - 1, m - 2, m - 3, ... n ways to fill them respectively.
• Write a loop that iterates from 0 to n - 1.
• Decrement that size of the array.
• Multiply it with count.
• If there is a single digit 0 or 5 then there is only one way to place a digit in the units place.
• Initialise the count to 2.
• Now, the remaining place can have m - 1, m - 2, m - 3, ... n ways to fill them respectively.
• Write a loop that iterates from 0 to n - 1.
• Decrement that size of the array.
• Multiply it with count.
• If there are no digits 0 or 5 than we can form a number that can be divisible by 5. Return -1 in that case.

## Implementation

Following is the implementation of the above algorithm in C++

#include <bits/stdc++.h>

using namespace std;

int numbers(int n, int m, int arr[]) {
bool isZeroPresent = false, isFivePresent = false;
int numbersCount = 0;
if (m < n) {
return -1;
}
for (int i = 0; i < m; i++) {
if (arr[i] == 0) {
isZeroPresent = true;
}
if (arr[i] == 5) {
isFivePresent = true;
}
}
if (isZeroPresent && isFivePresent) {
numbersCount = 2;
for (int i = 0; i < n - 1; i++) {
m--;
numbersCount = numbersCount * m;
}
} else if (isZeroPresent || isFivePresent) {
numbersCount = 1;
for (int i = 0; i < n - 1; i++) {
m--;
numbersCount = numbersCount * m;
}
} else {
return -1;
}
return numbersCount;
}
int main() {
int arr[] = {5, 6, 3};
cout << numbers(2, 3, arr) << endl;
return 0;
}

## Output

If you run the above code, then you will get the following result.

2
Updated on 21-Oct-2021 12:57:36