Editorial for Добри числа


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.

Submitting an official solution before solving the problem yourself is a bannable offence.
by: donchominkov

Solution with comments for Java:

static void solveGoodNumbers() {
    Scanner in = new Scanner(System.in);

    int n = in.nextInt();
    int m = in.nextInt();

    // Holds the counter of good numbers
    //  each new good number will increase this counter
    int counter = 0;

    // Iterate over all the possible good numbers
    for (int number = n; number < m + 1; number++) {
        // initially, we presume the number is good
        boolean isGoodNumber = true;

        // We copy the number, so we can split
        //  its digits
        int x = number;

        // when x becomes 0, there are no digits left
        //  This is result of integer division
        //  i.e. 1 / 0 = 0
        // Example with 123
        //  Get digit 3, the number becomes 12
        //  Get digit 2, the number becomes 1
        //  Get digit 1, the number becomes 0
        //  The loop stops
        while (isGoodNumber && x > 0) {
            // extract the last digit
            int digit = x % 10;

            // If the digit is not 0
            //  and the digit does not divide the number
            //  the number is not good, so we mark isGoodNumber as false
            if (digit != 0 && number % digit != 0) {
                isGoodNumber = false;
            }

            x /= 10;
        }
        //  If isGoodNumber has remained true,
        //      the number is good
        if (isGoodNumber) {
            ++counter;
        }
    }

    System.out.println(counter);
}

Comments

There are no comments at the moment.