所以,使用Java我试图找出在某个范围[a,b]中可被2,3和5除的整数的数量。因为我希望它适用于大数字,我使用包含排除原则对其进行编码。但是,我仍然不知道如何完成我的代码,即编写可以计算x的倍数的代码(2,3,5,10,15和30)。
这是我不完整的代码:
class Multiples {
public static void main(String[] args) {
long m = 0;
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
??????????
m = multiplesOf2 + multiplesOf3 + multiplesOf5 - multiplesOf6 - multiplesOf10 - multiplesOf15 + multiplesOf30;
System.out.println(m);
}
}
所以,显然我错过了'????'部分。我尝试用表达式计算倍数(在这种情况下为2):
multiplesOf2c = Math.ceil(a/2)*2;
multiplesOf2f = Math.floor(a/2)*2;
multiplesOf2 = ((multiplesOf2d - multiplesOf2f)/2 + 1);
但是,这似乎没有办法。结果有时是正确的,但在大多数情况下它会偏离1或2.请问任何想法?
答案 0 :(得分:0)
在考虑表现时简单但不太好!
int counterX=0; int x=// your desired number
for (long i=a; i<=b; i++) {
if(i%x==0){
counterX++;
}
}
答案 1 :(得分:0)
一种方法,也许这可以帮助你:
Scanner sc = new Scanner(System.in);
long a = sc.nextLong();
long b = sc.nextLong();
int flag;
int m=0;
String _mul235="";
String _mulOf2="Multiples 2: ";
String _mulOf3="Multiples 3: ";
String _mulOf5="Multiples 5: ";
for (long i=a;i<b;i++){
flag=0;
if(i%2==0) {
flag+=1;
_mulOf2 += i + " ";
}
if(i%3==0) {
flag+=1;;
_mulOf3 += i + " ";
}
if(i%5==0) {
flag+=1;;
_mulOf5 += i + " ";
}
if (flag==3){
m+=1;
_mul235+= i + " ";
}
}
System.out.println("Range: From " + a + " to "+b);
System.out.println("Integer multiples of (2, 3 y 5): "+ m + "\n[ "+_mul235+"]");
System.out.println("Checking:");
System.out.println(_mulOf2);
System.out.println(_mulOf3);
System.out.println(_mulOf5);