int a,b,c,d=0;
cin>>a>>b>>c;
for (int i=a;i<=b;i++)
{
if (i%c==0){d++;}
}
cout<<d;
Run Code Online (Sandbox Code Playgroud)
所以这是代码,a..b是数字范围,c是除数,并d计算的倍数c.例如,当a=5, b=15, c=3,d等于4,因为"6,9,12,15"是5和15,我需要找到更快的方法来做到这一点的倍数,谁能帮助?
一种方法就是这样做(不需要循环):
int lower = (a + c - 1) / c; // find lowest divisor (round up)
int upper = b / c; // find higher divisor (round down)
d = upper - lower + 1; // get no of divisors
Run Code Online (Sandbox Code Playgroud)
对于你的例子,lower将是2,upper将是5,d等于4.
| 归档时间: |
|
| 查看次数: |
2653 次 |
| 最近记录: |