Showing largest divisible number instead of all numbers

I’ve started to learn basics of Java and currently I have to find and print largest divisible number.

For example number 30 can be divided by 2, 3, 6 and 10 so on the console I should show only 10. Another example is number 12 which can be divided by 2, 3 and 6 – should show 6.

I’m stuck at the point where I show the largest number. What I have so far is this one

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

The snipped display the first occurrence instead of the largest. You can tell how new I’m based on the snipped so please bear with me.

Answer

When you want to find the highest divisible number that is not the input you could do the following:

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

If you want to check specific numbers only, you could modify that to use a sorted collection of numbers.

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

Leave a Reply

Your email address will not be published. Required fields are marked *