首页 > 解决方案 > 显示最大可除数而不是所有数字

问题描述

我已经开始学习 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); 
    }

剪辑显示第一次出现而不是最大的出现。你可以根据剪报告诉我我有多新,所以请多多包涵。

标签: java

解决方案


当您想找到不是输入的最大可除数时,您可以执行以下操作:

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;
  }
}

推荐阅读