列表

详情


NC229227. Continued Fraction

描述

A continued fraction is an expression of the form:

where  are nonnegative integers.

Given a fraction (x,y are positive integers), please expand it into a continued fraction.

输入描述

The first line contains an integer T (), denoting the number of test cases.

The only line of each test case contains two integers x, y (), denoting a fraction . It's guaranteed that .

输出描述

For each test case, output one line: first an integer n denoting the height of the continued fraction, then  integers denoting . Your solution should gurarantee that , .

If there are multiple valid solutions, you only need to output one of them.

示例1

输入:

2
105 38
1 114

输出:

4 2 1 3 4 2
1 0 114

说明:

For the convenience of you, we give explanation of sample:
\frac{105}{38}=2+\dfrac{1}{1+\dfrac{1}{3+\dfrac{1}{4+\dfrac12}}}

\frac{1}{114}=0+\dfrac{1}{114}

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

pypy3 解法, 执行用时: 126ms, 内存消耗: 24676K, 提交时间: 2023-04-26 15:48:30

t = int(input())
while t>0:
    x,y = map(int,input().split())
    result = []
    if x==1:
        print('1 0 '+str(y))
    else:
        while x!=1:
            result.append(x//y)
            x,y=y,x%y
        print(str(len(result)-1)+' '+' '.join(map(str,result)))
    t-=1

C++(clang++ 11.0.1) 解法, 执行用时: 5ms, 内存消耗: 460K, 提交时间: 2023-03-25 19:10:50

#include<stdio.h>
int main(){
	int T,x,y,n,t,i,a[20];
	for(scanf("%d",&T);T;--T,puts("")){
		for(scanf("%d%d",&x,&y),n=0;y;++n)a[n]=x/y,t=x%y,x=y,y=t;
		for(printf("%d ",n-1),i=0;i<n;++i)printf("%d ",a[i]);
	}
}

Python3 解法, 执行用时: 136ms, 内存消耗: 4804K, 提交时间: 2023-05-11 18:12:43

def dfs(a,b):
    ls.append(a//b)
    if b<=1:
        return
    dfs(b,a%b)
n=int(input())
for i in range(n):
    x,y=map(int,input().split())
    ls=[]
    dfs(x,y)
    print(len(ls)-1,end=' ')
    print(*ls)

上一题