Chinaunix首页 | 论坛 | 博客
  • 博客访问: 39867
  • 博文数量: 22
  • 博客积分: 1130
  • 博客等级: 少尉
  • 技术积分: 280
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-11 17:20
文章分类

全部博文(22)

文章存档

2010年(3)

2009年(19)

我的朋友
最近访客

分类: C/C++

2009-11-14 21:58:43

高精度取模和除法 从低位向高位用9~2除

//220K    63MS


#include <iostream>
#include <string>
#include <math.h>
using namespace std;
#define LEN 1001
//大整形类

int Bak[LEN];
class BigInt
{
private:
    int len;
    int bit[LEN];
public:
    BigInt(const string & str="");
    void Print();
    bool TestDiv(int mod);
    bool TestEnd() {return len==0||(len==1&&(bit[0]==0||bit[0]==1));}
    ~BigInt() {}
};

BigInt::BigInt(const string& str)
{
    len=str.size();
    for(int i=0;i<len;i++)
        bit[i]=str[i]-'0';
}

void BigInt::Print()
{
    for(int i=0;i<len;i++)
        printf("%d",bit[i]);
    printf("\n");
}

bool BigInt::TestDiv(int mod)
{
    if(len==1)
    {
        if(bit[0]%mod==0){
            bit[0]/=mod;
            return true;
        }
        return false;
    }
    int wei=0;
    int now=0;
    int yu=0;
    for(int i=0;i<len;i++)
    {
        now=now*10+bit[i];
        if(now>=mod)
        {
            yu=now%mod;
            Bak[wei++]=now/mod;
            now=yu;
        }
        else Bak[wei++]=0;
    }
    if(yu!=0||now!=0)
        return false;
    else{
        int k=0;
        while(Bak[k]==0)
            k++;
        len=0;
        for(int i=k;i<wei;i++)
            bit[len++]=Bak[i];
        return true;
    }
}

int ans[LEN];
int pos;
int main()
{
    string str;
    while(cin>>str)
    {
        if(str[0]=='-')
            break;
        BigInt big=BigInt(str);
        bool ok=false;
        pos=0;
        if(str.size()==1)
        {
            int answer=10+str[0]-'0';
            printf("%d\n",answer);
            continue;
        }
        while(true)
        {
            bool found=false;
            int i;
            for(i=9;i>=2;i--)
            {
                if(big.TestDiv(i))
                {
                    found=true;
                    ans[pos++]=i;
                    break;
                }
            }
            if(!found)
                break;
            if(big.TestEnd())
            {
                ok=true;
                break;
            }
        }
        if(ok){
            for(int i=pos-1;i>=0;i--)
                printf("%d",ans[i]);
            printf("\n");
        }
        else
            printf("There is no such number.\n");
    }
    return 0;
}


阅读(411) | 评论(0) | 转发(0) |
0

上一篇:POJ 1411

下一篇:我的Emacs配置

给主人留下些什么吧!~~