java - 显示最大可除数而不是所有数字
问题描述
我已经开始学习 Java 的基础知识,目前我必须找到并打印最大的整除数。
例如,数字 30 可以除以 2、3、6 和 10,所以在控制台上我应该只显示 10。另一个例子是数字 12,它可以除以 2、3 和 6 - 应该显示 6。
我被困在我显示最大数字的地方。我目前拥有的是这个
double isItDivisible = Double.parseDouble(scanner.nextLine());
int num = 2;
if ( isItDivisible % 2 == 0 ) {
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 3 == 0 ) {
num = 3;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 6 == 0 ) {
num = 6;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 10 == 0 ) {
num = 10;
System.out.println("The number is divisible by " + num);
} else if ( isItDivisible % 7 == 0 ) {
System.out.println("The number is divisible by " + 7);
}
剪辑显示第一次出现而不是最大的出现。你可以根据剪报告诉我我有多新,所以请多多包涵。
解决方案
当您想找到不是输入的最大可除数时,您可以执行以下操作:
int highest = 1; //1 should always apply - at least for integers
//iterate from highest to lowest number
for( int d = input-1; d > 1; d-- ) {
//stop at the first number that divides the input without a rest
if( input % d == 0 ) {
highest = d;
break;
}
}
如果您只想检查特定数字,您可以修改它以使用排序的数字集合。
//TreeSet is sorted and the reserved comparator makes it sort from high to low
SortedSet<Integer> divisors = new TreeSet<>(Comparator.reversed());
//if the collection itself is sorted the order of additions doesn't matter
//if you're using a list and don't sort it after adding elements then order of insertion is relevant though
divisors.add(2);
divisors.add(10);
divisors.add(3);
divisors.add(7);
divisors.add(6);
Integer highest = null;
//iterates in sorted order
for( Integer d : divisors ) {
if( input % d == 0 ) {
highest = d;
break;
}
}
推荐阅读
- sql - 如何将 SELECT 使用 Oracle 中 SQL 中的两个表的列中的总和值相加
- tsql - 如何制作一个用户可以输入年份和月份的功能,自动查找该月的最后一天?
- azure - 如何将 WAR 文件部署到使用 Docker OPEN Liberty Image 创建的 Azure 应用服务
- java - cpu使用率高和内存泄漏
- jscript - 有时不支持 Exists 属性
- c# - 选择对象集合的列/字段并导出为 List<>
- reactjs - 将全局变量与局部变量进行比较后如何重定向到另一条路由
- javascript - 从他们的 API 检索 Stripe 发票时,如何扩展对象以检索信用卡详细信息和其他信息?
- quill - How to get the last index of quill editor?
- java - 为什么 JTextfield 和 JButton 只在启动程序 3 次后才出现?