找到从 x 到 y 的数字的整除数
find divisble for a number from x to y
目前我正在尝试查找用户输入的数字的整除率,并且该数字应该可以从 x 到 y 整除
example: 2520 is divisible by all numbers from 1-10.
这是我到目前为止所做的,很明显我的编码方式很糟糕,有人能做得更好吗?
public static void main (String[] args){
Scanner kb = new Scanner(System.in);
int temp = 0,x,y,num;
System.out.println("enter the number to check for");
num = kb.nextInt();
System.out.println("enter the starting number");
x = kb.nextInt();
System.out.println("enter the ending number");
y=kb.nextInt();
while(x >= y){
System.out.println("starting num must be less then the ending num,re-enter the starting num.");
x = kb.nextInt();
System.out.println(" now enter the ending number, must be greater then the starting num");
y=kb.nextInt();
}
while ( num % x == 0 && x < y){
x++;
}
if ( x == y){
System.out.println("the number "+ num + " is divisble by this range.");
}
}
}
写成辅助方法:
public static boolean isDivisibleByAll(int dividend, int fromDivisor, int toDivisor) {
for (int divisor = fromDivisor; divisor <= toDivisor; divisor++)
if (dividend % divisor != 0)
return false;
return true;
}
需要考虑的一些事项:
如果您接受任意顺序的整数,将会更加方便用户使用。如果第一个大于第二个,就从第二个转到第一个。所以,像这样:
int swapInt;
if (x > y)
{
swapInt = x;
x = y;
y = swapInt;
}
如果您在开始和结束时接受相同的整数,将会更加方便用户使用。用户可能只想检查一个数字。 (您将如何更改代码来执行此操作?)
- 您似乎可以接受任何整数,包括零和负整数。你的程序还能用吗?如果不是,您需要更改什么?
目前我正在尝试查找用户输入的数字的整除率,并且该数字应该可以从 x 到 y 整除
example: 2520 is divisible by all numbers from 1-10.
这是我到目前为止所做的,很明显我的编码方式很糟糕,有人能做得更好吗?
public static void main (String[] args){
Scanner kb = new Scanner(System.in);
int temp = 0,x,y,num;
System.out.println("enter the number to check for");
num = kb.nextInt();
System.out.println("enter the starting number");
x = kb.nextInt();
System.out.println("enter the ending number");
y=kb.nextInt();
while(x >= y){
System.out.println("starting num must be less then the ending num,re-enter the starting num.");
x = kb.nextInt();
System.out.println(" now enter the ending number, must be greater then the starting num");
y=kb.nextInt();
}
while ( num % x == 0 && x < y){
x++;
}
if ( x == y){
System.out.println("the number "+ num + " is divisble by this range.");
}
}
}
写成辅助方法:
public static boolean isDivisibleByAll(int dividend, int fromDivisor, int toDivisor) {
for (int divisor = fromDivisor; divisor <= toDivisor; divisor++)
if (dividend % divisor != 0)
return false;
return true;
}
需要考虑的一些事项:
如果您接受任意顺序的整数,将会更加方便用户使用。如果第一个大于第二个,就从第二个转到第一个。所以,像这样:
int swapInt; if (x > y) { swapInt = x; x = y; y = swapInt; }
如果您在开始和结束时接受相同的整数,将会更加方便用户使用。用户可能只想检查一个数字。 (您将如何更改代码来执行此操作?)
- 您似乎可以接受任何整数,包括零和负整数。你的程序还能用吗?如果不是,您需要更改什么?