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

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the total numbers that can be formed using the m digits given in the array. Let's see an example.

## Input

n = 2
m = 3
arr = {5, 6, 3}

## Output

Let's see the steps to solve the problem.

• Check for the 0 and 5 as the number must contain 0 or 5 to be divisible by 5.
• If there are both 0 and 5 then there are two ways to place a digit in units place. Otherwise there will be a single way to place a digit.
• Now, the remaining place can have m - 1, m - 2, m - 3, ... n ways to fill them respectively.

Let's see the code.

Live Demo

#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;
}

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

2

## Conclusion

If you have any queries in the tutorial, mention them in the comment section.