B - Product Calculator Editorial by en_translator
When the calculator shows \(X\), multiplying by \(A_i\) makes it show:
- \(1\) if \((X\times A_i)>10^K-1\), and
- \((X\times A_i)\) otherwise.
It is sufficient to perform this for \(i=1,2,\ldots,K\), and find the integer finally shown.
However, \((X\times A_i)\) can be up to \((10^{18}-1)^2\), causing an overflow error if we compute using \(64\)-bit integer type, so we need a trick. For example, one can utilize the following property: for \(Y=10^K-1\), \((X\times A_i)>Y\) if and only if \(X> \left\lfloor \frac{Y}{A_i}\right\rfloor\), where \(\left\lfloor \frac{Y}{A_i}\right\rfloor\) denotes the maximum integer not exceeding \( \frac{Y}{A_i}\).
Proof
Notice that $A_i>0$ always hold. If $(X\times A_i)>Y$, then by definition $X>\frac{Y}{A_i}\geq \left\lfloor \frac{Y}{A_i}\right\rfloor$. Meanwhile, if $X> \left\lfloor \frac{Y}{A_i}\right\rfloor$, then $X-1\geq \left\lfloor \frac{Y}{A_i}\right\rfloor$ because both sides are integers. This yields $ \left\lfloor \frac{Y}{A_i}\right\rfloor>\frac{Y}{A_i}-1$, so $X>\frac{Y}{A_i}$, thus $(X\times A_i)>Y$.In this case, \(X\) and \(\left\lfloor \frac{Y}{A_i}\right\rfloor\) are both \(10^{18}\), and the latter can be found as an integer division, so it can be computed using \(64\)-bit integer type without an overflow. Alternatively, one can use multi-precision integers (bigints).
Sample code in C++:
#include <bits/stdc++.h>
using namespace std;
int main(void){
int n,k;
long long a,y=1,x=1;
cin>>n>>k;
for(int i=0;i<k;i++)y*=10;
y--;
for(int i=0;i<n;i++){
cin>>a;
if(x>(y/a))x=1;
else x*=a;
}
cout<<x<<endl;
return 0;
}
Sample code in Python:
n,k=map(int, input().split())
a=list(map(int, input().split()))
x,y=1,10**k-1
for i in range(n):
x*=a[i]
if x>y:
x=1
print(x)
posted:
last update: