我们已获得一个范围 A<=B 和一个数字 M。我们必须找出给定范围内有多少个 M 的倍数。
我的解决方案:
import java.util.Scanner;
class ABC {
public static void main(String args[] ) throws Exception {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
for (int i = 0; i < N; i++) {
long A = sc.nextLong();
long B = sc.nextLong();
long M = sc.nextLong();
int res = 0;
while(A<=B)
{
if(A%M==0)res++;
A++;
}
System.out.println(res+"");
}
}
}
现在这不是很有效。请告诉我如何在最短的时间内解决这个问题。
最佳答案
n1*M ≥ A 的最小整数 n1 为 n1=ceil(A/M),n2*M ≤ B 的最大整数 n2 为 n2=floor(B/M)。 n1 和 n2 之间的整数个数为 max_of(n2−n1+1 ; 0)。
结合以上我们得到答案:
max_of(floor(Z/X)−ceil(Y/X)+1;0)
这是竞争性编程中的一个标准问题:D
关于java - 查找范围内数字的倍数 [Java],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31870932/