CodeForces - 376C Divisible by Seven(数论:同余定理)(找规律)

Divisible by Seven

You have number a, whose decimal representation quite luckily contains digits 1, 6, 8, 9. Rearrange the digits in its decimal representation so that the resulting number will be divisible by 7.

Number a doesn't contain any leading zeroes and contains digits 1, 6, 8, 9 (it also can contain another digits). The resulting number also mustn't contain any leading zeroes.

Input

The first line contains positive integer a in the decimal record. It is guaranteed that the record of number a contains digits: 1, 6, 8, 9. Number a doesn't contain any leading zeroes. The decimal representation of number a contains at least 4 and at most 106 characters.

Output

Print a number in the decimal notation without leading zeroes — the result of the permutation.

If it is impossible to rearrange the digits of the number a in the required manner, print 0.

Examples
input
1689
output
1869
input
18906
output
18690


ps:
比如说有一个数为1234561689,那么根据同余定理可以知道1234561689%7=(1234560000%7+1689%7)%7
然后呢,我们可以假设1689(无顺序)为后四位,那么前面所有的数%7的结果只有0~6这七种情况
所以我们可以对这七种情况打表,找出%7为0的后四位“1689”(有0的话可以让0放在最后面,其他非1689的数原样输出就好了)

代码:
#include<stdio.h>
#include<string.h>
#define maxn 1000000+10
char a[][5]={"1869","6198","1896","1689","1986","1968","1698"};
char s[maxn];
int flag[11]={0};

int main()
{
    scanf("%s",s);
    int len=strlen(s);
    int p=0,ps=0;
    for(int i=0;i<len;i++)
    {
        if((s[i]=='1'||s[i]=='6'||s[i]=='8'||s[i]=='9')&&!flag[s[i]-'0'])
            flag[s[i]-'0']=1;
        else if(s[i]=='0')
            ps++;
        else
        {
            printf("%c",s[i]);
            p=p*10+s[i]-'0';
            p%=7;
        }
    }
    printf("%s",a[p]);
    for(int i=0;i<ps;i++)
        printf("0");
    return 0;
}

打表代码:
#include<stdio.h>
int a[5]={1,6,8,9},vis[20];

void dfs(int k,int s,int cnt)
{
    if(cnt==4)
    {
        if((((s%7)+(k*10000%7))%7)==0)
            printf("k=%d s=%d\n",k,s);
    }
    for(int i=0;i<4;i++)
    {
        if(!vis[a[i]])
        {
            vis[a[i]]=1;
            dfs(k,s*10+a[i],cnt+1);
            vis[a[i]]=0;
        }
    }
}

int main()
{
    int i1,i2,i3,i4;
    for(int i=0;i<7;i++)
    {
        dfs(i,0,0);
    }
}

总结:现在接触的数论题大多都是找规律,而且大多可以通过打表找到
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值