cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2020 · EasyDigit arithmetic

Numbers Divisible by Their Digit Product

National Olympiad — Municipal round (2020 season)

Submission name: int.cpp

Problem summary

Count integers in [A,B] divisible by the product of their decimal digits. Exclude zero-product numbers because divisibility by zero is undefined.

Input

A B.

Output

The qualifying count.

Constraints

1 ≤ A ≤ B ≤ 10^9; at most 100001 integers in the interval.

Worked example

Input and output for the worked example discussed below.

Input

1 12

Output

11

Solution analysis

  1. The endpoints may be large but the interval is short. Enumerate only its at-most 100001 members.
  2. Extract digits and multiply them. If the product is zero reject the number; otherwise test number modulo product.
  3. In [1,12], all nine single digits qualify. Number 10 fails, while 11 and 12 qualify, giving eleven total.

Why it works

Every candidate is counted exactly when its nonzero digit product divides it.

Complexity: O((B−A+1) log B) time and O(1) space.

Watch out. Never take modulo zero and do not scan from 1 to the large endpoint.

Commented C++17 solution

An independently written complete program with standard headers.

// Every candidate is counted exactly when its nonzero digit product divides it.
#include<iostream>
using namespace std;
int main(){
    long long left,right;
    cin>>left>>right;
    int answer=0;
    for(long long number=left;number<=right;number++){
        long long product=1;
        for(long long remaining=number;remaining>0;remaining/=10){
            product*=remaining%10;
        }
        if(product!=0&&number%product==0){
            answer++;
        }
    }
    cout<<answer<<'\n';
}

Source: Arena Olimpiici ↗