第九届蓝桥杯大赛个人赛省赛(软件类)真题C 语言 A 组-分数

solution1

直观上的分数处理

cpp 复制代码
#include <iostream>
using namespace std;
int main()
{
  printf("1048575/524288");
  return 0;
}
cpp 复制代码
#include<stdio.h>
#include<math.h>
typedef long long ll;
struct fraction{
	ll up, down;
};
ll gcd(ll a, ll b){
	if(!b) return a;
	return gcd(b, a % b);
}
fraction r(fraction f){
	if(gcd(f.down, f.up) > 1){
		f.down /= gcd(f.down, f.up);
		f.up /= gcd(f.down, f.up);
	}
	return f;
}
fraction add(fraction f1, fraction f2){
	fraction f;
	f.down = f1.down * f2.down;
	f.up = f1.up * f2.down + f2.up * f1.down;
	return r(f);
}
int main(){
	fraction f, t;
	f.up = f.down = 1;
	for(ll i = 2; i <= pow(2, 19); i *= 2){
		t.up = 1;
		t.down = i;
		printf("%lld %lld\n", t.down, f.up);
		f = add(f, t);
	}
	printf("%lld %lld, %lld %lld", f.up / f.down, f.up % f.down, f.up, f.down);
	return 0;
}

solution2

手动通分计算为

(219+218+217......+20)/219= (220-1)/219

  • 20+21+22+......+2n-1 = 2n-1
  • 较大的数若比 较小的数 的两倍大于或者小1,则两者互质
cpp 复制代码
#include<stdio.h>
#include<math.h>
typedef long long ll;
int main(){
	printf("%lld/%lld", (ll) pow(2, 20) - 1, (ll) pow(2, 19));//注意别漏了强转double -> ll
	return 0;
}
相关推荐
RuoZoe2 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_6 天前
C语言内存函数
c语言·后端
norlan_jame7 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874757 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237177 天前
C语言-数组练习进阶
c语言·开发语言·算法
qq_459234427 天前
【题库】| 商用密码应用安全性评估从业人员考核题库(四十)
职场和发展·密码学·学习方法·考核·商用密码·商用密码应用安全性评估·密评
敲敲了个代码7 天前
[特殊字符] 空数组的迷惑行为:为什么 every 为真,some 为假?
前端·javascript·react.js·面试·职场和发展
Z9fish7 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人7 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J7 天前
从“Hello World“ 开始 C++
c语言·c++·学习