在C ++程序中可除数为12的整数

在本教程中,我们将编写一个程序来检查给定的字符串格式大数字是否可被12整除。

我们将使用一点数学来解决这个问题。如果该数字可被3和4整除,则该数字将被12整除。

如果数字的总和可被3整除,则该数可被3整除。

如果数字的最后两位可被4整除,则该数字可被4整除。

我们将利用以上陈述并完成程序。

示例

让我们看一下代码。

#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;
}
输出结果

如果执行上述程序,则将得到以下结果。

Yes

结论