HIToj How many N 1008 (数论同余&暴力)

来源:互联网 发布:网络协议抽象成软件 编辑:程序博客网 时间:2024/09/21 08:58

How many N

 Source : xy Time limit : 15 sec Memory limit : 32 M

Submitted : 5977, Accepted : 1136

Find a minimal interger K which is merely comprised of N and can be divided by M.

For example,11 is the minimal number that and be divided by 11, and it is comprised of two '1's, and 111111 can be divided by 13 which is comprised of six '1's.

Input

On each line of input , there will be two positive integer, N and M. N is a digit number, M is no more than 10000.

Output

On each single line, output the number of N, if no such K, output zero.

Sample Input
1 51 111 13
Sample Output
026
//真心感觉后台数据太强大了,cnt要开到10000才过(以为会超时,但还好,让我给水过了,跑了5.28s。。。)
#include<stdio.h>#include<string.h>#include<algorithm>#define N 1000010using namespace std;int a[110];int main(){int n,m,i,j,k;while(scanf("%d%d",&n,&m)!=EOF){k=n%m;int flag=0;int cnt=1;while(k){k=(k*10+n)%m;cnt++;if(cnt>=10000){flag=1;break;}}if(flag)printf("0\n");elseprintf("%d\n",cnt);}return 0;}

//这是大神写的,跑的很快。
#include<stdio.h>#include<stdio.h>#include<algorithm>#include<string.h>#include<iostream>#include<math.h>using namespace std;typedef long long ll;ll gcd(ll a,ll b){if(b==0)return a;elsereturn gcd(b,a%b);}ll eular(ll n){ll res=1,i;for(i=2;i*i<=n;i++){if(n%i==0){res=res*(i-1);n=n/i;while(n%i==0){res=res*i;n=n/i;}}if(n==1)break;}if(n>1)res=res*(n-1);return res;}ll exmod(ll p,ll n,ll m){ll sq=1;while(n>0){if(n%2==1)sq=(sq%m)*(p%m)%m;p=(p%m)*(p%m)%m;n=n/2;}return sq%m;}int main(){ll n,m,g,M,phi,i;ll a[1000],num;while(scanf("%lld%lld",&n,&m)!=EOF){g=gcd(m,n);//这里理论上取9m和n的最大公约数也是可行的。恩,但是改掉就WA了,我也不知道为啥M=9*m/g,num=0;if(gcd(M,10)!=1){printf("0\n");continue;}phi=eular(M);for(i=1;i*i<=phi;i++)//其实这里还可以更快,直接质因数分解之后来搞,恩{if(phi%i==0){a[num++]=i;a[num++]=phi/i;}if(i*i==phi)a[num++]=i;}sort(a,a+num);for(i=0;i<num;i++)if(exmod(10,a[i],M)==1){printf("%lld\n",a[i]);break;}}return 0;}

0 0
原创粉丝点击