gpt4 book ai didi

java - 求 x 到 y 之间的数能否被整除

转载 作者:行者123 更新时间:2023-12-02 04:20:28 25 4
gpt4 key购买 nike

目前我正在尝试查找用户输入的数字的整除性,并且该数字应该可以从 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;
}

关于java - 求 x 到 y 之间的数能否被整除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32832097/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com