真题解析│蓝桥杯省赛真题之“分数”
2018年蓝桥杯软件类省赛(软件类)C/C++大学A组第1题“分数”,一道结果填空题。
题目描述
2018省赛A组第1题,题目链接:
分数 http://oj.ecustacm.cn/problem.php?id=1359
1/1 + 1/2 + 1/4 + 1/8 + 1/16 + …
每项是前一项的一半,如果一共有20项,求这个和是多少,结果用分数表示出来。
类似:3/2当然,这只是加了前2项而已。分子分母要求互质。
题解
1+2+4+……+2n=2n+1−1
C++代码
代码中用gcd计算了最大公约数用于约分,使得分子分母互质。不过,其实不用约分,因为本身就是互质的。
#include<bits/stdc++.h>
using namespace std;
int main(){
int a = (1 << 20) - 1; //分子
int b = (1 << 19); //分母
int t = __gcd(a, b); //除去公约数
cout << a/t << "/" << b/t;
return 0;
}
Java代码
public class Main {
public static void main(String[] args) {
int a=(int) Math.pow(2, 20)-1;
int b=(int) Math.pow(2, 19);
System.out.println(a + "/" + b);
}
}
Python代码
还是Python好,写一个C++、Java的功夫,可以写4个Python。
b = 0
a = 1
for i in range(0,20):
b += a
a *= 2
print('%d/%d'%(b,a/2))
print('%d/%d'%(2 ** 20 -1,2 ** 19))
print(str(2 ** 20 -1)+'/'+str(2 ** 19))
print('%d/%d'% (pow(2,20)-1 ,pow(2,19)))

添加 家长论坛微信
全部 0条评论