C++中計算給定範圍內能被‘M’整除的數字個數


給定三個數字A、B和M。A和B定義了數字的範圍[A,B]。目標是在A和B之間計算能被M整除的數字個數。

我們將從i=A開始,直到M的第一個倍數。如果i%M=0,則遞增計數。現在遞增i,直到i<=B,並遞增計數。

讓我們透過示例來理解。

輸入

A=11,B=20, M=5

輸出

Count of numbers divisible by M in given range: 2

解釋

15和20是唯一能被5整除且在[11,20]範圍內的數字。

輸入

A=20, B=50, M=11

輸出

Count of numbers divisible by M in given range: 3

解釋

22、33、44是唯一能被11整除且在[20,50]範圍內的數字。

下面程式中使用的演算法如下:

  • 我們將A、B和M作為整數。
  • 函式divisiblebyM(int a, int b, int m)將A、B和M作為引數,並返回A和B之間能被M整除的數字個數。
  • 將初始計數設為0。
  • 使用for迴圈,從i=A到i=B。i每次遞增1。
  • 如果i%m=0,則遞增計數。
  • 最後,計數為A和B之間能被m整除的數字個數。
  • 返回計數作為結果。

示例

 線上演示

// Program to count the numbers divisible by
// M in a given range
#include <bits/stdc++.h>
using namespace std;
int divisiblebyM(int a, int b, int m){
   int count = 0;
   // Running a loop from A to B and check
   // if a number is divisible by M.
   for (int i = a; i <= b;i++ ){
      if (i % m == 0){
          count++;
       }
   }
   return count;
}
int main(){
   // A and B define the range, M is the dividend
   int A = 3, B = 15, M = 4;
   cout<<"Numbers divisible by M in given range:"<<divisiblebyM(A, B, M) << endl;
   return 0;
}

輸出

Numbers divisible by M in given range:3

更新於:2020年9月16日

1K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

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