Official

E - Product-Bounded Arithmetic Sequences Editorial by en_translator


Exhaustively enumerate the first term and the length of a sequence. Since the total product monotonically increases as the common difference increases. Therefore, the maximum common difference for which the total product is at most \(N\) can be found by binary searching.

Since the sequence must have at least three terms and a positive common difference, it suffices to consider initial terms up to \(N^{1/3}\). Also, since a length-\(m\) sequence with a positive initial term and common difference has a total product of at least \(m!\), it is sufficient to consider sequence lengths up to \(O(\log N)\).

Hence, the problem has been solved in a total of \(O(N^{1/3}(\log N)^2)\) time.

The condition A[1] * ... * A[m] <= N can be transformed into N / A[1] / ... / A[m] > 0 to avoid overflows.

Writer’s solution (C++)

#include<bits/stdc++.h>
using namespace std;
using ll=long long;

int main(){
	ll N;
	cin >> N;
	
	auto calc=[&](int a, int n){
		int ok=0,ng=1e9;
		while(ng-ok>1){
			int mid=(ok+ng)/2;
			ll s=N;
			for(int i=0;i<n;i++)s/=a+i*mid;
			if(s)ok=mid;
			else ng=mid;
		}
		return ok;
	};
	
	ll ans=0;
	for(int a=1;a<=1e6;a++){
		int n=3;
		ll NN=N/a/(a+1)/(a+2);
		while(NN){
			ans+=calc(a,n);
			NN/=a+n;
			n++;
		}
	}
	cout << ans << endl;
}

posted:
last update: