Divisibility by 12 for a large number in C++ Program

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

We are going to use a little bit of math to solve this problem. If the number is divisible by 3 and 4, then the number will divisible by 12.

A number is divisible by 3 if the sum of its digits is divisible by 3.

A number is divisible by 4 if the last two digits of the number are divisible by 4.

We are going to utilize the above statements and complete the program.

Example

Let's see the code.

Live Demo

#include <bits/stdc++.h>
using namespace std;
bool isNumberDivisibleBy12(string num) {
if (num.length() >= 3) {
int last_digit = (int)num[num.length() - 1];
if (last_digit % 2 != 0) {
return 0;
}
int second_last_digit = (int)num[num.length() - 2];
int sum = 0;
for (int i = 0; i < num.length(); i++) {
sum += num[i];
}
return (sum % 3 == 0 && (second_last_digit * 10 + last_digit) % 4 == 0);
}
else {
int number_as_int = stoi(num);
return number_as_int % 12 == 0;
}
}
int main() {
string num = "1212121212121212121212121212";
if (isNumberDivisibleBy12(num)) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
return 0;
}

Output

If you execute the above program, then you will get the following result.

Yes

Conclusion

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

Updated on: 28-Jan-2021

90 Views