1. 程式人生 > >wikioi天梯之3118 高精度練習之除法

wikioi天梯之3118 高精度練習之除法

題目

做了天梯的加減乘然後又把除法找出來做了下 利用減法做除法 所以先要保證減法寫的是對的 這次直接寫減法 比上次速度提高了 而且竟然一次寫對了。

之前做過加減乘除 除法就沒有參考資料了 自己獨立寫的 最終也寫出來了。 

#include <iostream>
#include <string>
#include<algorithm>
#include<cstring>

using namespace std;

string sub(const string &a_, const string &b_)
{
    int *tem;
    char *re;
    string result,a,b;
    bool flag = true;
    unsigned i,j;
    if(a_ == b_)return "0";
    a = a_;
    b=b_;
    if(a.length() < b.length())flag = false,swap(a,b);
    else if(a.length() == b.length() && a < b)flag = false,swap(a,b);

    tem = new int[a.length()];
    re = new char[a.length() + 2];

    memset(tem,0,(a.length()) * sizeof(int));
    memset(re,'\0',(a.length() + 2) * sizeof(char));

    for(i = 0,j = 0; i < a.length(); ++i)
    {
        if(i < a.length() - b.length())tem[i] = a[i] -'0';
        else
        {
            tem[i] = a[i] - b[j];
            ++j;
        }
    }

    for(i = a.length() - 1; i > 0; --i)
    {
        if(tem[i] < 0)
        {
            tem[i-1] -= 1;
            tem[i] += 10;
        }
    }
    j = 0;
    while(tem[j] == 0)++j;
    if(flag)
    {
        for(i = j; i < a.length(); ++i)re[i-j] =tem[i] + '0';
        re[i-j] = '\0';

    }
    else
    {
        re[0] = '-';
        for(i = j; i < a.length(); ++i)re[i-j+1] = tem[i] + '0';
        re[i-j+1] = '\0';
    }
    result = re;
    delete []re;
    delete []tem;
    return result;
}

string div(const string &a_, const string &b_)
{
    if(a_ == b_)return "1";
    else if(a_.length() == b_.length() && a_ < b_)return "0";
    else if(a_.length() < b_.length())return "0";
    else if(b_ == "1")return "a_";
    else if(b_ == "0")return "error!";

    char *re;
    string result,a,b;
    a = a_;
    b = b_;
    re = new char[a.length() - b.length() + 2];

    memset(re,'\0',(a.length() - b.length() + 2) * sizeof(char));

    int sub_len = a.length() - b.length();
    int i,j = 0,re_tem = -1;
    string test,a_tem;

    while(1)
    {
        b = b_;
        for(i = 0; i < sub_len; i++)b += "0";
        //cout<<b<<endl;

        while(1)
        {
            a_tem = a;
            // cout<<"a0 = "<<a<<endl;
            a = sub(a,b);
           // cout<<"a = "<<a<<endl;
            ++re_tem;
            if(a[0] == '-')
            {
                re[j] =re_tem + '0';
                ++j;
                re_tem = -1;
                --sub_len;
                a = a_tem;
                //cout<<"a2 = "<<a<<endl;
                break;
            }
        }
        test = sub(a,b_);
        if(test[0] == '-' || a == "0")break;

    }
    re[j] = '\0';
    unsigned m,k = 0;
    while(re[k] == '0')++k;//寫成re[k] == 0 檢查半天才發現。。
    for(m = k;m < a_.length() - b_.length() + 2;++m) re[m-k] = re[m];
    //這裡寫成m < a.length() - b.length() + 2 也檢查了半天 囧

    result = re;
    delete []re;
    return result;
}


int main()
{
    string a,b;
    cin>>a>>b;
    cout<<div(a,b);
    return 0;
}