# Divisible by 37 for large numbers in C++ Program

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that checks whether the given large number is divisible by 37 or not.

We are going to use a little bit of math here. Let's see the steps to solve the problem.

• Initialize the number.

• If the length of the given number is not divisible by 3, then add zeroes at the beginning of the number to make length is divisible by 3.

• Divide the number into 3 digits groups and add them.

• If the resultant sum is divisible by 37, then the given number is divisible by 37.

• If the resultant sum is 4 digits number, then repeat the steps from 2.

• Print whether the given number is divisible by 37 or not.

## Example

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isNumberDivisibleBy37(string number, int n) {
if (number == "0") {
return 0;
}
if (n % 3 == 1){
number = "00"+ number;
n += 2;
}
else if (n % 3 == 2){
number = "0"+ number;
n += 1;
}
int groups_sum = 0;
while (n != 0){
string group = number.substr(n - 3, n);
int group_value = (group[0] - '0') * 100 + (group[1] - '0') * 10 + (group[2] - '0') * 1;
groups_sum += group_value;
n = n - 3;
}
if (groups_sum >= 1000) {
string new_number = to_string(groups_sum);
return isNumberDivisibleBy37(new_number, new_number.length());
}
else {
return groups_sum % 37 == 0;
}
}
int main() {
string number = "4048675309";
if (isNumberDivisibleBy37(number, 10)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}

## Output

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

Yes

## Conclusion

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

Published on 28-Jan-2021 06:45:26