- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
#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.
Advertisements