21位水仙花,C++大整数类

首先声明,接触这个问题时候,大整数类,我还不大知道,所以,找了网上的源代码看了一下思路,自己敲了一遍,给后来人参考。

运行时间51s,

#include <iostream>
#include <algorithm>
#include <time.h>
using namespace std;
#define  LL   long long
#define  base (LL)100000000000000
#define  N    21
bool cmp(LL a,LL b)
{
    return a>b;
}
LL len(LL x)
{
    LL i=0;
    while(x) i++,x/=10;
    return i;
}
struct bigint
{
    LL high_p,low_p;
    bigint(LL h_p=0,LL l_p=0)//构造函数
    {
        high_p=h_p;
        low_p=l_p;
    }
    //重载bigint类加
    bigint operator +(bigint add)
    {
        LL s1=(add.low_p+low_p)/base;//求出溢出
        LL temp1=(add.low_p+low_p)%base;//低位
        LL temp2=high_p+add.high_p+s1;//高位
        return (bigint(temp2,temp1));
    }
    //重载bigint 与LL加
    bigint operator +(LL add)
    {
        return (bigint(high_p,low_p)+bigint(add/base,add%base));//long long转化为大整数类
    }
    //重载bigint与LL相乘
    bigint operator *(LL mul)
    {
        LL s1=(low_p*mul)/base;
        LL temp1=(low_p*mul)%base;
        LL temp2=high_p*mul+s1;//有一定危险
        return bigint(temp2,temp1);
    }
    LL big_len()
    {
        if(high_p>0)return len(high_p)+14;
        else{
            return len(low_p);
        }
    }
};
bigint mul_table[10];//定义21次方表
LL index[21];
//创建21次方表
void creatTable()
{
    mul_table[0]=0;
    mul_table[1]=bigint(0,1);
    int num;
    LL i=2;
    for(;i<10;i++)
    {
        num=N;
        mul_table[i]=bigint(0,1);//初始化
        while(num--)mul_table[i]=mul_table[i]*i;
    }
}
//判断是否满足条件
//主要判断顺序是否满足
bool judge(bigint sum)
{
    if(sum.big_len()!=N)return false;
    LL container[25];
    LL temp1=sum.high_p,temp2=sum.low_p;
    int i=0;
    while(temp2)
    {
        container[i++]=temp2%10;
        temp2=temp2/10;
    }
    i=14;
    while(temp1)
    {
        container[i++]=temp1%10;
        temp1=temp1/10;
    }
    sort(container,container+N,cmp);
    for(i=0;i<N;i++)
    {
        if(index[i]!=container[i])return false;
    }
    return true;
}
void display(bigint sum)
{
    cout<<sum.high_p<<sum.low_p<<endl;
}
//递归安排21位数顺序
void daffDFS(int x,int data,bigint sum)
{
    if(sum.big_len()>N)return;
    if(x>=N)//安排完
    {

        if(sum.big_len()<N)return;//不符合
        if(judge(sum))display(sum);
    }else
    {
        for(;data>=0;data--)//传入9
        {
            index[x]=data;//按照从大到小顺序排好,这样省了很多事情
            daffDFS(x+1,data,sum+mul_table[data]);
        }
    }


}
int main()
{
    clock_t start=clock();
    creatTable();
    daffDFS(0,9,bigint(0,0));
    clock_t myend=clock();
    float mytime=(myend-start)/CLOCKS_PER_SEC;

    cout<<mytime<<"S"<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/shuiyihang0981/article/details/83032004