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

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

结论

如果你对本教程有任何疑问,请在评论区提及。

更新于:2021 年 1 月 28 日

139 次浏览

开启你的职业生涯

通过完成这门课程获得认证

开始
广告