1017. A除以B

1017. A除以B (20)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
CHEN, Yue

本题要求计算A/B,其中A是不超过1000位的正整数,B是1位正整数。你需要输出商数Q和余数R,使得A = B * Q + R成立。

输入格式:

输入在1行中依次给出A和B,中间以1空格分隔。

输出格式:

在1行中依次输出Q和R,中间以1空格分隔。

输入样例:
123456789050987654321 7
输出样例:

17636684150141093474 3

#include <stdio.h>
#include <stdlib.h>
#include <string.h> 
int main(){
  char a[1000];
  int b,t,temp,i,l;
  scanf("%s %d",&a,&b);
  temp = a[0] - '0';
  l = strlen(a);
  if(l==1){
    t =(a[0]-'0')/b;
    temp = (a[0]-'0')%b;
    printf("%d",t);
  }
  for(i=1;i<l;i++){
    t = (temp*10+(a[i]-'0'))/b;
    printf("%d",t);
    temp = (temp*10+(a[i]-'0'))%b;
  }
  printf(" %d",temp);
  return 0;
} 

在PTA平台上实现A除以B有不同的情况和实现方法: ### 普通整数除法 对于给定两个绝对值不超过100的整数A和B,按照“A/B=商”的格式输出结果,同时考虑分母正负和为零的情况。可以使用C语言实现,代码如下: ```c #include<stdio.h> int main() { float A,B; float C; scanf("%f%f",&A,&B); C=A/B; if(B<0) printf("%.0f/(%.0f)=%.2f",A,B,C); else if(B>0) printf("%.0f/%.0f=%.2f",A,B,C); else printf("%.0f/%.0f=Error",A,B); return 0; } ``` 此代码通过判断分母B的正负和是否为零,按照要求输出结果,输出的商保留小数点后2位 [^3]。 ### 简化版大数除法 若处理大数的除法,可使用字符串数组存储“大数”,运用手算除法的思想进行运算。C语言代码如下: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char s[1001]; int b,len,t,temp; int i; scanf("%s %d", s, &b); len = strlen(s); t = (s[0]-'0')/b; if((t!=0 && len>1) || len==1) printf("%d", t); temp = (s[0]-'0')%b; for(i=1; i<len; i++) { t = (temp*10+s[i]-'0')/b; printf("%d",t); temp = (temp*10+s[i]-'0')%b; } printf(" %d", temp); return 0; } ``` 该代码每次用被除数的首位数去除b,若为零则 `temp*10` 加上下一位,直到字符串数组结束,得到余数并输出 [^2]。 ### Java实现 使用Java语言实现时,可借助 `BigInteger` 类处理大数的除法和取模运算,代码如下: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; public class Main { public static void main(String[] args) throws IOException { BufferedReader bf = new BufferedReader(new InputStreamReader(System.in)); String s[] = bf.readLine().split(" "); bf.close(); BigInteger a = new BigInteger(s[0]); BigInteger b = new BigInteger(s[1]); BigInteger sum1 = a.divide(b); BigInteger sum2 = a.mod(b); System.out.print(sum1+" "+sum2); } } ``` 此代码读取输入的两个大数,计算它们的商和余数并输出 [^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值