问题描述
1/1 + 1/2 + 1/4 + 1/8 + 1/16 + … 每项是前一项的一半,如果一共有20项,求这个和是多少,结果用分数表示出来。
类似:3/2
当然,这只是加了前2项而已。分子分母要求互质。
题目解析
这是一道填空题,因此代码起到辅助计算功能,可以先用等比数列求和公式算出结果,最后约分即可得到正确答案。
C++代码
#include<bits/stdc++.h>
using namespace std;
long pow_2(int b) //快速幂运算
{
long x = 2;
long res = 1;
while(b>0)
{
if(b&1) res*=x;
b>>=1; //右移一位
x = x*x;
}
return res;
}
int gcd(long a,long b) //求出最大公约数
{
if(b==0) return a;
return gcd(b,a%b);
}
int main()
{
cout<<gcd(pow_2(20)-1,pow_2(19))<<endl; //最大公约数
cout<<pow_2(20)-1<<"/"<<pow_2(19)<<endl; //输出分子分母
}