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

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

解释

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+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告