【數論】capacitor

capacitor

在這裏插入圖片描述

輸入

在這裏插入圖片描述

輸出

在這裏插入圖片描述

輸入樣例

#1

2
1 1
3 2

#2

2
6 5
199 200

輸出樣例

#1

1 
3

#2

6
200

解題思路

其實這道題就是一道數論,把分數先化簡後,然後一步步逆推到1,然後記錄步數即可.

程序如下

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define ll long long
using namespace std;
ll n,a,b,gys,ans;
ll gcd(ll x,ll y)//求最大公因數
{
	ll xx = x,yy = y,r = xx % yy;
	while(r) 
	{
		xx = yy;
		yy = r;
		r = xx % yy;
	}
	return yy;
}
int main()
{
//	freopen("capacitor.in","r",stdin);
//	freopen("capacitor.out","w",stdout);
	scanf("%lld",&n);
	for(ll i = 1;i <= n; ++i)
    {
    	scanf("%lld%lld",&a,&b);
    	ans = 0;
    	gys=gcd(a,b); //最大公因數
    	a /= gys;//化簡因數
    	b /= gys;//同上
		while(a != 0 && b != 0)
		{
			if(a > b)//看是否遞減的
			{
				ans += a/b;//記錄步數
				a%=b;
			} 
			else
			{
				swap(a,b);//不斷往上
				ans += a/b;//記錄步數
				a %= b; 
			} 
		} 
		printf("%lld\n",ans);
    }
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章