Codeforces 396B:On Sum of Fractions

Codeforces 396B:On Sum of Fractions

题目链接:http://codeforces.com/problemset/problem/396/B

题目大意:共$t$组数据,每组给出一个数$n$,求$sum_{i=2}^n{\frac{1}{v(i) \times u(i)}}$。其中$v(i)$为不大于$i$的最大质数,$u(i)$为大于$i$的最小质数。

数学

设$p_k$为第$k$个质数,数列$a_i=\frac{1}{v(i) \times u(i)}$,

可以发现当$p_k \leqslant i \leqslant p_{k+1}$时,$a_i$的值均相同;

将这些相同的项合并,形成一个新的数列$b_i=\frac{p_{i+1}-p_i}{p_i \times p_{i+1}}$.

若我们快速求得$S_n=sum_{i=1}^nb_i$,那么题目所要求的的值也就可以快速得到.

打表得到$S_n$的前几项:

$S_1=\frac{1}{2 \times 3},S_2=\frac{3}{2 \times 5},S_3=\frac{5}{2 \times 7},S_4=\frac{9}{2 \times 11},S_5=\frac{11}{2 \times 13}$

猜想$S_i=\frac{p_{i+1}-2}{2 \times p_{i+1}}$.

设$S_k=\frac{p_{k+1}-2}{2 \times p_{k+1}}$,则

$$
\begin{align}
S_{k+1}
&=S_k+b_{k+1}\\
&=\frac{p_{k+1}-2}{2 \times p_{k+1}}+\frac{p_{k+2} - p_{k+1}}{p_{k+1} \times p_{k+2}}\\
&=\frac{p_{k+2} \times (p_{k+1}-2)+2 \times (p_{k+2}-p_{k+1})}{2 \times p_{k+1} \times p_{k+2}}\\
&=\frac{p_{k+1} \times (p_{k+2}-2)}{2 \times p_{k+1} \times p_{k+2}}\\
&=\frac{p_{k+2}-2}{2 \times p_{k+2}}\\
\end{align}
$$

故猜想正确.(亦可以从$b_i=\frac{p_{i+1}-p_i}{p_i \times p_{i+1}}=\frac{1}{p_i}-\frac{1}{p_{i+1}}$得到)

而题目所要求的$sum_{i=2}^n\frac{1}{v(i) \times u(i)}$,即为$S_k-\frac{u-1-n}{v(i) \times u(i)}$,其中$u$为第$k$个质数。

代码如下:

 1 #include <iostream>
 2 using namespace std;
 3 typedef long long ll;
 4 ll T,n,v,u;
 5 bool prime(ll n){
 6     for(ll i=2;i*i<=n;++i)
 7         if(n%i==0)return 0;
 8     return 1;
 9 }
10 ll gcd(ll a,ll b){
11     return b?gcd(b,a%b):a;
12 }
13 struct fraction{
14     ll p,q;
15     fraction(ll _p=1,ll _q=1){
16         p=_p;q=_q;
17     }
18     friend fraction operator - (fraction a,fraction b){
19         fraction c;
20         ll tmp=gcd(a.q,b.q);
21         c.p=b.q/tmp*a.p-a.q/tmp*b.p;
22         c.q=a.q/tmp*b.q;
23         tmp=gcd(c.p,c.q);
24         c.p/=tmp;c.q/=tmp;
25         return c;
26     }
27 }a,b;
28 int main(void){
29     std::ios::sync_with_stdio(false);
30     cin>>T;
31     while(T--){
32         cin>>n;
33         v=n;u=n+1;
34         while(!prime(v))v--;
35         while(!prime(u))u++;
36         a=fraction(u-2,2*u);
37         b=fraction(u-1-n,v*u);
38         a=a-b;
39         cout<<a.p<<"/"<<a.q<<endl;
40     }
41 }

 

posted @ 2017-02-22 16:30  barriery  阅读(298)  评论(0编辑  收藏  举报