PTA 乙级 1017 A除以B

本文介绍了一个使用C语言实现的整数除法算法,该算法能够处理任意长度的整数并返回商和余数。通过将输入字符串转换为数字数组,并逐位进行除法运算,最终输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码实现:

#include<stdio.h>
#include<string.h>

int main()
{
	char a[1001];
	int b, q, r, len;

	scanf("%s %d", a, &b);
	len = strlen(a);
	for (int i = 0; i < len; i++)a[i] -= '0';
	if (len == 1)
	{
		r = a[0] % b;
		printf("%d %d", a[0] / b, r);
	}
	else
	{
		for (int i = 0; i < len; i++)
		{
			if(i!=len-1)
				if (a[i] / b != 0)
				{
					a[i + 1] += 10 * (a[i] % b);
					a[i] /= b;
				}
				else
				{
					a[i + 1] += 10 * a[i];
					a[i] = 0;
				}
			else if (i == len - 1)
			{
				r = a[i] % b;
				a[i] /= b;
			}
		}
		for (int i = 0; i < len; i++)
			if (i == 0 && a[i] != 0)printf("%d", a[i]);
			else if (i != 0)printf("%d", a[i]);
		printf(" %d", r);
	}

	return 0;
}
### PTA 多项式 A 除以 B 的算法实现 对于多项式 \(A\) 和 \(B\),目标是找到商 \(Q\) 和余数 \(R\),使得 \(A = B \times Q + R\) 并且 \(R\) 的阶数严格小于 \(B\) 的阶数。以下是具体的算法描述和 Python 实现。 #### 算法概述 1. 初始化商 \(Q\) 和余数 \(R\) 均为空。 2. 将被除数 \(A\) 赋给当前处理的多项式 `current`。 3. 当 `current` 不为零且其最高次幂不低于除数 \(B\) 的最高次幂时: - 计算当前应减去的部分:令该项等于 `current` 中最高次幂项与 \(B\) 中最高次幂项的比例关系形成的单项式; - 更新 `current` 减去上述计算得到的新项乘上整个 \(B\) 后的结果; - 把新产生的项加入到 \(Q\) 中作为新的部分。 4. 终止循环后剩下的 `current` 即为最终的余数 \(R\);而累加起来的各项构成完整的商 \(Q\)。 此过程类似于手工做长除法的过程,在计算机中通过不断减少高次项来逼近解。 #### Python 实现代码 ```python def poly_divide(A, B): from collections import defaultdict def parse_poly(poly_str): terms = {} parts = poly_str.split() n = int(parts[0]) for i in range(1, len(parts), 2): exp = int(parts[i]) coef = float(parts[i+1]) terms[exp] = coef return terms def format_output(polynomial): if not polynomial: return "0 0 0.0" items = sorted([(k, v) for k, v in polynomial.items() if abs(v)>1e-6], reverse=True) result = [] for item in items: result.extend([str(item[0]), f"{item[1]:.1f}"]) return ' '.join(result) # 解析输入字符串成字典形式 {指数:系数} a_terms = parse_poly(A)[^4] b_terms = parse_poly(B)[^4] q = {} # 商初始化为空列表 r = dict(a_terms) # 初始设置r=a max_b_exp = max(b_terms.keys()) if b_terms else None while r and (max(r.keys()) >= max_b_exp): # 只要还有剩余项可处理并且次数大于等于b的最大次数 lead_r_coef = r[max(r.keys())] lead_q_term = (max(r.keys()), lead_r_coef / b_terms[max_b_exp]) # 新增q的一项 q[lead_q_term[0]] = round(lead_q_term[1], 1)[^5] temp_product = {key + lead_q_term[0]-max_b_exp : value*lead_q_term[1] for key,value in b_terms.items()}[^3] for power in list(temp_product.keys()): if power in r: r[power] -= temp_product[power] if abs(r[power])<1e-6: del r[power] # 如果接近于0则删除此项 elif abs(temp_product[power])>1e-6: r[power]=-temp_product[power] print(format_output(q)) print(format_output(r)) # 示例调用函数 poly_divide("4 3 5.0 2 3.0 1 2.0 0 1.0", "2 1 1.0 0 1.0") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值