在 C++ 中檢查一個數是否能被 23 整除


這裡我們將看到一個程式,可以檢查一個數是否能被 23 整除。例如,給定一個數字 1191216。它可以被 23 整除。

要檢查可整除性,我們必須遵循以下規則 −

  • 每次提取數字的最後一個數字/截斷數字

  • 將 7 *(上一個計算的數字的最後一個數字)新增到截斷數字

  • 重複這些步驟直至必要。

17043, so 1704 + 7*3 = 1725
1725, so 172 + 7 * 5 = 207
207, this is 9 * 23, so 17043 is divisible by 23.

示例

 線上演示

#include <iostream>
#include <algorithm>
using namespace std;
bool isDivisibleBy23(long long int n) {
   while (n / 100) {
      int last = n % 10;
      n /= 10; // Truncating the number
      n += last * 7;
   }
   return (n % 23 == 0);
}
int main() {
   long long number = 1191216;
   if(isDivisibleBy23(number))
      cout << "Divisible";
   else
      cout << "Not Divisible";
}

輸出

Divisible

更新於: 21-Oct-2019

183 次瀏覽

開啟你的事業

完成課程獲得認證

開始學習
廣告
© . All rights reserved.