Enumerate i, then compute the expression in parentheses in O(1) time.
Let g(t,l)=i=1∑l[∀j∈[1,t],gcd(i,pj)=1]f(i), namely, the sum over the numbers in [1,l] that are coprime to all of p1,p2,…,pt of their f values.
The computation in Part 1 becomes i=1∑nf(i)⋅g(m,⌊in⌋).
The base case is g(0,l)=∑i=1lf(i), and the transition is g(t,l)=g(t−1,l)−f(pt)⋅g(t−1,⌊ptl⌋).
The variable l has about n possible values, and each requires enumerating its prime factors, giving complexity O(lnnn⋅n)=O(lognn). This needs to be optimized.
Observe that when pt+12>l, the only number satisfying the condition is 1, so g(t,l)=f(1)=1.
When pt2>l, substituting this into the recurrence gives g(t,l)=g(t−1,l)−f(pt).
Therefore, once pt2>l is found, stop the transition and call this t value tl. Then ∀t>tl,g(t,l)=g(tl,l)−∑i=tlt−1f(pi).
By preprocessing the prefix sums of f over the primes, g can be obtained quickly, reducing the time complexity to O(lognn43).
Part 2
Compute i=1∑n[∀d∈(n,n]∩P,d∤i]f(i).
Let h(t,l)=i=1∑l[i=j=t∏mpjcj,cj∈N]f(i), namely, the sum over all numbers in [1,l] whose prime factors are restricted to pt,pt+1,…,pm of their f values.
Part 2 asks for h(0,n).
The base case is h(m+1,l)=1, and the transition is h(t,l)=h(t+1,l)+c∈N∗∑f(ptc)⋅h(t+1,⌊ptcl⌋).
The variable l has about n possible values, so the direct transition takes O(n⋅lnnn)=O(lognn) time. This needs to be optimized.
As with the optimization for g, when pt>l, the only number that can be formed from pt,pt+1,…,pm is 1, so h(t,l)=f(1)=1.
Similarly, ∀pt2>l,h(t,l)=h(t+1,l)+f(pt).
Therefore, once pt2>l is found, stop the transition and call this t value tl. Whenever h is subsequently used, add the current h value plus i=ptl∑min(l,n)[i∈P]f(i), as needed.
The time complexity is reduced to O(lognn43).
Summation
The sum of the answers to Part 1 and Part 2 is i=1∑nf(i).