大數 (整數)乘法,除法

大數相乘

計算兩個正整數m,n的乘積,m,n不超過一千位

<span style="font-size:18px;">#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
    char a[1001],b[1001];//輸入的m,n
    int x[1001],y[1001],s[1005];
    int c1,c2,i,j,t,n;
    while(~scanf("%s%s",a,b))
    {

            c1 = strlen(a);
            c2 = strlen(b);
            memset(s,0,sizeof(s));
            for(i = 0; i<c1; i++)  //字符轉換爲數字
                x[c1-1-i] = a[i]-'0';
            for(i = 0; i<c2; i++)
                y[c2-1-i] = b[i]-'0';
            for(i = 0; i<c1; i++)
            {
                for(j = 0; j<c2; j++)//逐位相乘
                {
                    t = x[i]*y[j];
                    s[i+j] += t; //進位先不處理
                }
            }
            int f = 0; //代表每位的進位
            for(i = 0; i<=c1+c2; i++)//處理進位
            {
                t = s[i]+f;
                s[i] = t%10;
                f = t/10;
            }
            i =  c1+c2+1;
            while(i--)
                if(s[i]) break;//去掉前導0
            if(i == -1) printf("0");
            else
              for(; i>=0; i--)
                 printf("%d",s[i]);
            printf("\n");
    }
    return 0;
}</span>
                                                     
                                                 大數除法

輸入兩個正整數,m,n,0<=m<10的1000次方,n>0且不超過int型.求m/n.

<span style="font-size:18px;">#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
    char a[1001];
    int b[1001],i,j,n,c,t;
    int dest[1001];  //儲存商
    while(~scanf("%s%d",a,&n))
    {
        c = strlen(a);
        for(i = 0;i<c;i++)
            b[i] = a[i]-'0';
            int s = 0,k = 0,flag = 0;
        for(i = 0;i<c;i++)
        {
            t = s*10+b[i];//t代表當前的被除數
            if(t/n>0||t == 0)//被除數在第一次可能爲0,則dest【0】 = 0;
            {
                dest[k++] = t/n;
                s = t%n;
                flag = 1;//說明已經有有效位了
            }
            else
            {
                s = t;
                if(flag) dest[k++] = 0;
            }
        }
        for(i = 0;i<k;i++)
            printf("%d",dest[i]);
        if(!k) printf("0");
        printf("\n");
    }
    return 0;
}</span>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章